I want to randomly choose a single <div>
and then trigger the same event handler that would be triggered if I clicked it. My event handler looks like this:
function move(){
var currentLeft = $(this).css("left")
var currentTop = $(this).css("top")
if($(this).hasClass("movable")){
$(this)
.css("left", leftOld)
.css("top", topOld);
leftOld = currentLeft;
topOld = currentTop;
}
findMovable();
}
Normally this event is triggered by a click event. The event listener looks like this:
$(".piece").click(move);
I want to have a function that can randomly click these divs and trigger the same event handler. I'm working with something like this, but can't figure out how to finish:
$("#shufflebutton").click(shufflePieces); //event listener
function shufflePieces(){
var clickTile = Math.floor(Math.random() * $(".movable").length);
$(".movable")[clickTile].trigger(move); //this is the line I can't figure out
}
It's important that the event handler (move) knows what div was "clicked" because it must access information regarding that <div>
using $(this)
. Any help for me? Thanks!
Like this:
$('.movable').eq(clickTile).click();
$(...)
returns a jQuery object. Indexed properties ([3]
) of a jQuery object return raw DOM elements, not jQuery objects.
To get a jQuery object for a specific element within a jQuery object, call .eq()
.