0

I'm generating and appending several spans to divs on page load.

HTML structure like:

    <div id="holder">
        <div id="grid"></div>
    </div>

Then loop through and append spans to the nested div:

    $span = $('<span />').attr('class', 'colorSquare');
    $("#grid").append($span);

Then, I want to click a button and reset (delete the originally appended spans, because I don't want to reappend spans) what's inside the div's with:

    $("#holder > div").html("");

On initial page load / initial generation of spans inside the div, the click event handler is registered to the div's spans on document.ready , and the following works:

$("#grid span").click(function () { console.log("working"); }); 

However, after resetting with $("#holder > div").html("");, the click handler doesn't work. I'm assuming this is because the handler is only assigned on initial document ready, but I wasn't expecting all handlers to be removed once you reset the div's content. How do I prevent assigned handlers from being removed?

user3871
  • 12,432
  • 33
  • 128
  • 268

1 Answers1

1

This is because you are assigning the click handler onto the span element that you have added to #grid. When you clear #grid, you also remove the span and therefore you lose the click handler. You will either have to re-assign the handler again as soon as another span is created, or use an alternate handler that is tied to an element that does not get removed (such as #grid):

$('#grid').on('click', 'span', function() { console.log("working"); });

This alternative uses jQuery's on method, and binds the handler to the #grid element. However, the second parameter labels that you only care about clicking on span elements which are children of #grid.

Lochemage
  • 3,974
  • 11
  • 11