Neuran
Neuran

Reputation: 147

empty() method interrupts dynamic event

Why after use the .empty() method, the click event doesn't work anymore?

$(document).ready(function(){
    var a = "<button>click</button>";
    $("p").append(a);
    $("button").click(function(){
        alert("ok");
        $("p").empty();
        // it disappears
        $("p").append(a);
        // it reappears but if I click it again it doesn't work
    });
});

...

<p></p>  

Since I have a program with a button created globally and I have to place it and remove it frequently, but after the first use, nothing happens.

var checkAnswer = $("<button>",
{
    text: 'Check',
    click: function () {
    // do something

    }
});

Upvotes: 1

Views: 67

Answers (1)

jfriend00
jfriend00

Reputation: 707836

Static event handlers are attached to a specific DOM element. If you remove that DOM element (which you are doing with .empty() and create a new DOM element (which you are doing with .append(), the original event handler attached to the now removed DOM element is gone.

In jQuery, it feels like you are attaching an event to a selector, but when you use the static form of .on() or .click() (like you are), the selector is evaluated once when you initially install the event handler. That selector turns into a list of DOM elements and those DOM elements at that specific time get the event handler attached to them. If you later create new DOM elements that also match that selector, they won't have any event handlers on them.

Delegated event handling can be used to solve this issue for some types of events.

Your options are:

  1. Don't replace the DOM element (perhaps just replace its content)
  2. Attach the event handler to the newly created DOM element after you create the new DOM element.
  3. Use delegated event handling which attaches the event handler to a much higher level DOM object (a parent you are not removing) and looks for events that occurred on child objects that have bubbled up to the static parent.

If you want to read more about delegated event handling, here are some other answers that explain it:

Does jQuery.on() work for elements that are added after the event handler is created?

jQuery .on does not work but .live does

jQuery .live() vs .on() method for adding a click event after loading dynamic html

JQuery Event Handlers - What's the "Best" method

Upvotes: 4

Related Questions