How To Apply Live() Like Feature For Javascript Appended Dom Elements
Solution 1:
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 elementwhile (target && target !== root) { // Tree traversingif (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);
Solution 2:
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');
});
Solution 3:
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.
Post a Comment for "How To Apply Live() Like Feature For Javascript Appended Dom Elements"