0

I have a strange problem with JQuery when I try to click on append element that is inside timeout function I got the following code:

function generate(){
    box = shuffle(box);
    console.log(box);
    $("#game").empty();
    for (var i = 0; i < 4; i++) {
        $("#game").append("<div class=box>" + box[i] + "</div>");
    }
}

function lvl1(){
    box = shuffle(box);
    console.log(box);
    $("#game").empty();
    for (var i = 0; i < 4; i++) {
        $("#game").append("<div class=box>" + box[i] + "</div>");
    }
}

generate();

setTimeout(function(){
    lvl1();
}, 1000);

$(".box").click(function(){
    alert("OK");
});

If I try to click on box within a 1 sec the alert is showed correctly but if I try to click after the timeout it does nothing also no error is showing

http://jsfiddle.net/f4kgvaL5/

4
  • 1
    Can you create a fiddle with all your code and html...easier to help you jsfiddle.net Commented Aug 10, 2014 at 16:24
  • Please take the time to format your code correctly. It makes it much easier for you and others to read. Commented Aug 10, 2014 at 16:27
  • Why are you expecting clicking on .box to do anything other than show an alert? Commented Aug 10, 2014 at 16:28
  • Well thats the problem it doesn't show after timeout fire lvl1 Commented Aug 10, 2014 at 16:28

3 Answers 3

2

The .box elements are being appended dynamically, so you need to use a delegated event:

$("#game").on('click', '.box', function () {
    alert("OK");
});

Updated fiddle

Sign up to request clarification or add additional context in comments.

4 Comments

I think I won by 6 seconds :P
Why the first one works but one inside setTImeOut don't?
I would imagine it's because the first group of .box elements are available to the DOM on page load. Subsequent sets are loaded via AJAX.
Yes this is correct. When you call generate you initialize the first set of box elements then you attach the event to them. However subsequent calls you dont attach the event so the alert is never fired.
1

This looks like an event delegation issue. On the new boxes created during lvl1 you arnt assigning the event handler again.

Try

$( "#game" ).on( "click", ".box", function(){
    alert("OK");
});

Comments

0

see the code:-

 $(document).on("click",".box",function(){
            alert("OK");
 });

working example:- http://jsfiddle.net/f4kgvaL5/2/

thanks

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.