jquery - How to fade loop gallery background images -
i wish rotate background image of div believe precludes me using excellant jquery cycle plugin.
the code below have far not behave like, is:
- fade out first image
- swap image second image while not showing image - (fails fade in second image)
- and repeat infinity ...and beyond.
<script type='text/javascript' src='http://code.jquery.com/jquery-1.5.2.js'></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js"></script> <link rel="stylesheet" type="text/css" href="/css/normalize.css"> <link rel="stylesheet" type="text/css" href="/css/result-light.css"> <style type='text/css'> #mydiv { width: 100%; height: 365px; margin-left: auto; margin-right: auto; position: relative; display: block; background: url(hp_jquery1.jpg) center top no-repeat; } </style> <script type='text/javascript'> $(window).load(function(){ var firsttime = true; var arr = ["url(hp_jquery2.jpg)", "url(hp_jquery3.jpg)"]; (function recurse(counter) { var bgimage = arr[counter]; if (firsttime == false) { $("#mydiv").fadeout("slow"); $('#mydiv').css('background-image', bgimage); $("#mydiv").fadein("slow"); } else { firsttime = false; } delete arr[counter]; arr.push(bgimage); settimeout(function() { recurse(counter + 1); }, 3600); })(0); }); </script> </head> <body> <div id="mydiv"> </div> </body>
in order cross-fade background image, you'll need layer overlay gallery.
here's example of logic involved:
so create div place normal <img>
tags browser pre-load images, we'll use src
afterwards use covered background-image
2 elements:
jquery(function($) { var $gallery = $("#gallery"); // html gallery var $overlay = $("<div/>"); // overlay x-fade var $images = $gallery.find("img"); var n = $images.length; // how many images have var c = 0; // counter loop using reminder operator % $gallery.css({backgroundimage: "url("+ $images[c].src +")"}).append( $overlay ); (function loopbg(){ $overlay.hide().css({backgroundimage: "url("+ $images[++c%n].src +")"}).delay(2000).fadeto(1200, 1, function(){ $gallery.css({backgroundimage: "url("+ $images[c%n].src +")"}); loopbg(); }); }()); });
html, body{ height:100%; margin:0; /*if needed*/ } #gallery, /*your gallery id */ #gallery > div /*immediate div child, created jquery*/ { position:absolute; width: 100%; height:100%; background: #000 none 50% / cover; } #gallery img{ display:none; /*exactly. we'll use them bg images*/ }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="gallery"> <!-- we'll not show images, used browser preload them let's steal images sources , use them #gallery , #overlay backgrounds --> <img src="http://dummyimage.com/600x365/fc5/fff&text=image1" /> <img src="http://dummyimage.com/600x365/cf5/fff&text=image2" /> <img src="http://dummyimage.com/600x365/f5c/fff&text=image3" /> </div>
Comments
Post a Comment