PropSoft
PropSoft

Reputation: 597

jQuery live() in plain JavaScript?

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

Thanks!

Upvotes: 6

Views: 799

Answers (2)

Šime Vidas
Šime Vidas

Reputation: 185933

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]
        }
    }
}

Upvotes: 2

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

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.

Upvotes: 2

Related Questions