0

How to apply live() like feature for JavaScript appended DOM elements?

Like a li list inside ul which is added through JavaScript. I need to do this in plain JavaScript.

vetri02
  • 3,199
  • 8
  • 32
  • 43

4 Answers4

5

Since .live() is simply event delegation, place your handler on the nearest element to the ones being added.

var container = document.getElementById('my_container');

container.onclick = function(e) {
    e = e || window.event;
    var target = e.target || e.srcElement;

    while(target && target.nodeName.toUpperCase() !== 'LI' ) {
        if( target === this )
            target = null;
        else 
            target = target.parentNode;
    }

    if( target ) {
        // work with the LI
    }
};

This is also similar to .live() in the sense that it searches from the e.target up to the container with the delegate to see if it is your targeted element.

Just testing the e.target itself isn't enough if the li has descendants.


For more complex analysis of the elements, you could use .matchesSelector, though you'd need to stick it on the HTMLElement.prototype under the correct name, since most browsers include it as an extension.

Also, you'd need a patch for IE8, but that's pretty easy.

if (HTMLElement) {
    if (!HTMLElement.prototype.matches && !HTMLElement.prototype.matchesSelector) {
        HTMLElement.prototype.matches =
        HTMLELement.prototype.matchesSelector = 
            HTMLElement.prototype.webkitMatchesSelector ||
            HTMLElement.prototype.mozMatchesSelecvtor ||
            HTMLElement.prototype.msMatchesSelector ||
            HTMLElement.prototype.oMatchesSelector;
    }
} else if (!Element.prototype.matchesSelector && Element.prototype.querySelectorAll) {

    Element.prototype.matches = 
    Element.prototype.matchesSelector =
        function() {
            // exercise for reader to implement using .querySelectorAll, 
            //    though it's pretty easy, and available online if you search
        }
}
  • @Ian: Yeah, the `target &&` test wasn't strictly necessary here since it would `break` at `this`, but I think it's better form to include it, so I threw it in. :) –  May 22 '13 at 15:09
  • Haha it was just funny cause it's over a year old, and the only reason I'm here, and saw that, is because it was linked from this question: http://stackoverflow.com/questions/16694269/any-emulation-or-alternative-of-live-jquery-function – Ian May 22 '13 at 15:10
  • @Ian: Ah, I see. I think I'll throw a `matchesSelector` note in there as well. –  May 22 '13 at 15:14
2

You have to bind an event to the document root, and check the event.target property. If it matches the given selector, then do something.

Example (assuming addEventListener)
Example: Match all elements with id test:

var root = document.documentElement;
root.addEventListener('click', function(event) {
    var target = event.target;          // <-- Clicked element
    while (target && target !== root) { // Tree traversing
        if (target.id == 'test') {      // <------ Matches selector
            // Do something.
            break; // Optional: Stop traversal, because a match has been found

        }
        target = target.parentNode; // Go up in the tree
    }
}, true);
Rob W
  • 341,306
  • 83
  • 791
  • 678
0

the live() is a function of jquery library

  .live( events, handler(eventObject) )

events: A string containing a JavaScript event type, such as "click" or "keydown." As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names.

handler(eventObject): A function to execute at the time the event is triggered.

for your example, when you created the li inside the ul, you have to you live to capture the li,e.g,

$('li').live('mouseover',function(){
   alert('hello');
});
Skyrel
  • 200
  • 3
  • 12
  • I think it might make more sense to call `live` on the `ul` since that's the persistent parent element. – pimvdb Feb 08 '12 at 17:59
  • 1
    The OP wanted to do this in pure JS no outside libs. – scrappedcola Feb 08 '12 at 17:59
  • for the ul dont need to use live() since it is created when the html loaded, and i think he is asking for binding events to the newly created one, i.e. li – Skyrel Feb 08 '12 at 18:01
  • @scrappedcola: so his question is confusing? he asked about live() but want only plain javascript! and what point to use js only – Skyrel Feb 08 '12 at 18:02
  • @Skyrel: Not every one wants to use jQuery on every site. OP is asking how to replicate `.live()` behavior without jQuery. –  Feb 08 '12 at 18:06
0

You can manually attach the event handler whenever you create a new element. Or, you can do it exactly how jQuery is doing it by looking into the jQuery library and extracting the parts you need.

caleb
  • 1,579
  • 12
  • 12