Here's a simple example:
function live(eventType, elementId, cb) {
document.addEventListener(eventType, function (event) {
if (event.target.id === elementId) {
cb.call(event.target, event);
}
});
}
live("click", "test", function (event) {
alert(this.id);
});
The basic idea is that you want to attach an event handler to the document and let the event bubble up the DOM. Then, check the event.target
property to see if it matches the desired criteria (in this case, just that the id
of the element).
Edit:
@shabunc discovered a pretty big problem with my solution-- events on child elements won't be detected correctly. One way to fix this is to look at ancestor elements to see if any have the specified id
:
function live (eventType, elementId, cb) {
document.addEventListener(eventType, function (event) {
var el = event.target
, found;
while (el && !(found = el.id === elementId)) {
el = el.parentElement;
}
if (found) {
cb.call(el, event);
}
});
}
.live()
is deprecated for a long, long time. It was replaced by.delegate()
, which was replaced by.on()
, so please use the last one. Furthermore, the last one shows the difference between binding and delegating, so you may wish to take a look. The most important is checking for event target. – Highlands