1

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');
Naftali
  • 144,921
  • 39
  • 244
  • 303
Mike
  • 3,017
  • 1
  • 34
  • 47
  • 1
    possible duplicate of [jQuery: select random elements](http://stackoverflow.com/questions/1764160/jquery-select-random-elements) – Felix Kling Mar 01 '12 at 23:02
  • I've seen that but it did not work to me – Mike Mar 01 '12 at 23:04
  • 1
    Works for me: http://jsfiddle.net/n3Lgn/. Maybe you thought that the whole construction returns a jQuery object, but it does not. `.get()` returns an array and `.sort()` and `.slice()` are native array methods. In my example I omitted `.get()`. – Felix Kling Mar 01 '12 at 23:10
  • Yes, that makes sense in the way you put it. – Mike Mar 01 '12 at 23:19

1 Answers1

3

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.

Kevin B
  • 94,570
  • 16
  • 163
  • 180