iLikeBreakfast
iLikeBreakfast

Reputation: 1565

jQuery Hover Random Element

I need to set up a function that hovers and "de-hovers" on a random element in a class every 5 seconds. Thus far I have the onhover working with the following:

jQuery.fn.random = function() {
    var randomIndex = Math.floor(Math.random() * 56);  
    return jQuery(this[randomIndex]);
};
var timer = window.setInterval(function () {$('.graphic-container img').random().mouseover();}, 5000);

There are 56 fixed elements in the class, thus the " * 56"

For the life of me I can't figure out how to get the mouseout event working on that random element? This must happen before the next random element is hovered on.

Any help would be much appreciated!

Upvotes: 2

Views: 669

Answers (2)

Sudz
Sudz

Reputation: 4308

Use this

var timer = window.setInterval(function () {
   $('.graphic-container img').random().mouseover().delay(800).mouseout();
}, 5000);

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388416

Try

jQuery.fn.random = function() {
    var randomIndex = Math.floor(Math.random() * 56);  
    return jQuery(this[randomIndex]);
};
var prev;
var timer = window.setInterval(function () {
    if(prev){
        prev.mouseleave();
    }
    prev = $('.graphic-container img').random().mouseenter();
}, 5000);

Demo: Fiddle

Upvotes: 2

Related Questions