rterrani
rterrani

Reputation: 526

jQuery click event not working with setInterval replacing link

I am making an incremental game in javascript, so I am replacing some links in the page all the time, this links are showing a really weird behavior. I am attaching the click events with .on(, and some times the click event is fired and some times not, is very random. Here is a clear example of the beheavior. I can imagine that is something related with the time interval, because if I set the interval in 1000 millis, the event always is fired. Of course that I can make some changed in the code in order to don't replace the link and only update it, but I want to know if this is fixable first.

HTML:

<div id="container"><a id="link" href="#">test</a></div>

JS:

$(document).ready(function(){
$("#container").on("click","#link",function(){
    alert("clicked");
});
setInterval(function(){
    var newA = $("#link").clone();
    $("#link").remove();
    $("#container").append(newA);
},100);});

Example in jsFiddle: http://jsfiddle.net/MtR6b/1/

Thanks!!

Upvotes: 0

Views: 591

Answers (1)

Your setInterval code is very fast 100 ms that's why when then event is about to trigger element is replaced with new one so click event is not triggered.

Try clicking on the link many times you will see the alert.


DEMO with 1000ms=1s setInterval

Upvotes: 2

Related Questions