Reputation: 10713
Hey, I have this piece of jQuery/Javascript:
$(document).ready(function() {
var points = 0;
var iterations = 10;
var winWidth = $(window).width();
var winHeight = $(window).height();
setInterval(function() {
if (iterations > 0) {
var rndX = Math.ceil(Math.random() * winWidth);
var rndY = Math.ceil(Math.random() * winHeight);
$('div.item').remove();
$('body').append('<div class="item" style="left: '+rndX+'px; top: '+rndY+'px;"></div>');
iterations--;
} else {
location.href = "http://www.google.com/";
$('*').remove();
}
}, 1750);
$('div.item').click(function() {
$(this).remove();
points = points + 1;
$('#points').val(points);
return false;
});
});
But for some reason, the $('div.item').click(function()
doesn't fire up :(
Any ideas?
Upvotes: 3
Views: 1844
Reputation: 6496
I would suggest using JQuery's .live method for similar reasons as Pointy.
Live will bind to elements as they are created.
$('div.item').live('click', function() {
$(this).remove();
points = points + 1;
$('#points').val(points);
return false;
});
Upvotes: 0
Reputation: 45525
your divs dont exist when you try and bind your click function to the elements...
You need to bind them ahead of time (dynamically).
see .live() and .delegate()
Upvotes: 0
Reputation: 413717
Instead of using "click", use "delegate":
$('body').delegate('div.item', 'click', function() {
$(this).remove();
points = points + 1;
$('#points').val(points);
return false;
});
When your interval handler code removes all the "div.item" elements from the document, that will also remove the handlers you established. By using "delegate" instead, you put just one handler on the <body>
element, and it takes advantage of event bubbling to handle all the clicks. Those that come from elements that match the "div.item" selector will be handled with your code, just as if the handler had been directly bound to the elements.
Because the "delegate" mechanism applies the selector at the time the events actually happen, it doesn't matter whether the target element existed since the page was first received or if the element was just dynamically added (as is the case in your code).
Upvotes: 10