Search code examples
jqueryrandomeventtrigger

trigger mouse enter on random element


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');

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.