6

I am trying to accomplish what the jQuery live() function can do, but in plain JavaScript. Can anyone here help with this?

Thanks!

PropSoft
  • 597
  • 4
  • 8
  • 20

2 Answers2

2

Here is a little startup example

document.onclick = function(evt){

    evt =  evt  ||  window.event;
    var element = evt.target  ||  evt.srcElement;

};

wherever you click you get a reference to the element that received the click.

More useful, though, in a real scenario would be to use the attachEvent method for IE, or the addEventListener for the rest.

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
2

Something like this:

myLive("div", "click", function() { ... }); 

var liveArray = [];

function myLive(selector, type, handler) {
    liveArray.push([selector, type, handler]);
}

// this handler should fire for any event on the page, and should be attached
// to the document node
function documentAnyEvent(e) {
    var e = e || window.event;
    var target = e.target || e.srcElement;
    for (var i = 0; i < liveArray.length; i++) {
        if (target mathes the selector AND e.type matches the type) {
            // fire the handler liveArray[i][2]
        }
    }
}
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385