Skip to content
Advertisement

Simple version of jQuery live function

Is it possible to get anywhere a pure Javascript function for event handler with similar functionality as jQuery’s live() ? I need to have the ability to attach events to objects not yet created but both jquery-livequery as well as jquery-events sources are not useful due to dependencies on jQuery core.

Advertisement

Answer

Event delegation is quite simple. Take this example:

Markup:

<div id="container">
    <p>Test</p>
    <p>Test</p>
    <p>Test</p>
</div>

<button id="add">Add new paragraph</button>

Script:

document.getElementById("container").onclick = function(e) {

    // e.target is the target of the event or "source element"
    alert(e.target.innerHTML);
};

// dynamically adds new paragraph on button click
document.getElementById("add").onclick = function() {
    var p = document.createElement("p");
    p.innerHTML = "a new paragraph";
    document.getElementById("container").appendChild(p);
};

Since the event handler is attached to the parent, it will work for any future elements inserted.

You can try it here.

Useful reference:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement