Skip to content Skip to sidebar Skip to footer

Jquery .click() Not Working With Setinterval

Hey, I have this piece of jQuery/Javascript: $(document).ready(function() { var points = 0; var iterations = 10; var winWidth = $(wi

Solution 1:

Instead of using "click", use "delegate":

$('body').delegate('div.item', 'click', function() {
  $(this).remove();
  points = points + 1;
  $('#points').val(points);
  returnfalse;
});

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).

Solution 2:

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()

Solution 3:

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);
             returnfalse;
          });

Post a Comment for "Jquery .click() Not Working With Setinterval"