Continuous Image Swap While Mouse Is Hovering
i have an idea but i'm not quite sure how to execute it. i want have an image that when the mouse hovers over it, it quickly changes to a random image, and changes pretty quickly t
Solution 1:
JQuery's .hover() can use a function for the mouseover and mouseout states, so it's trivial to do something like
html:
<img id="swap" src="http://lorempixum.com/200/200/sports" alt=""/>
jquery:
var images = ["http://lorempixum.com/200/200/sports",
              "http://lorempixum.com/200/200/food",
              "http://lorempixum.com/200/200/abstract",
              "http://lorempixum.com/200/200/people",
              "http://lorempixum.com/200/200/technics",
              "http://lorempixum.com/200/200/city"
             ],//store a bunch of images in an array
    i = 0,//counter
    $swap = $("#swap"),//only get the object once
    swapper;//setup a var for setInterval
function swapImg(){
    i = i % images.length;//keep i under the array length
    $swap.attr("src",images[i]);// change image src        
    i++;
}
$swap.hover(function(){//mouseover
    swapper = setInterval(swapImg,10);//call function every 10ms
},function(){//mouseout
    clearInterval(swapper);//stop calling the image swapper
});
I'm using http://lorempixel.com/ for the dummy images, but they'll return a random image each time you request one, so this displays more images than are in the array, and that makes it load funky sometimes.
Solution 2:
Every jQuery event has a callback function, so on mouseover you could start a callback function A that calls function B that calls function A, etc.
On mouseout, break the infinite callback loop.
Post a Comment for "Continuous Image Swap While Mouse Is Hovering"