wowpatrick
wowpatrick

Reputation: 5180

jQuery - Create new function on event

In JavaScript/jQuery, if I want to have a function that can run on an element that has been appended to the DOM, it has to be created after the element has been appended to the DOM. How can I do this? I heard one can do this with the jQuery .on() function, but I'm not quite sure how.

HTML:

<span>Hello Stackoverflow</span>​

JavaScript:

$("span").click(function () {
   addMyElement();
});

$("p").click(function () {
   removeMyElement(this);
});

function addMyElement() {
    $("<p>Hello World</p>").appendTo("body");
}
function removeMyElement(myElement) {
    $(myElement).remove();
}

Example on jsFiddle.net.

Upvotes: 1

Views: 659

Answers (2)

Jeff Watkins
Jeff Watkins

Reputation: 6359

function addMyElement() {
    $("<p>Hello World</p>").appendTo("body").click(function () {
       removeMyElement(this);
    });
}

Will work for you, not hugely readable with all that chaining though.

Upvotes: -2

VisioN
VisioN

Reputation: 145388

This is called delegated-events approach and it works as follows:

$("body").on("click", "p", function () {
    // ...
});

Instead of body you can use any parent element of p.

DEMO: http://jsfiddle.net/wWXrK/6/

Upvotes: 7

Related Questions