Question

I have this javascript:

$('.foto').filter(function(index) {
    return index == Math.floor(Math.random() * 8) + 1;
}).trigger('mouseover');

I want to simulate a hover effect on a photo, but somehow the filter function does not work. I also tried

$('.foto:random').trigger('mouseover');
Was it helpful?

Solution

Try this:

$.fn.rand = function(){
    return this.eq(Math.floor(Math.random()*this.length));
};
$(".foto").rand().trigger("mouseover");

Note: you only have to define $.fn.rand once, usually right after including jquery.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top