Any emulation or alternative of live jquery function ?
I need to use an alternative of the live function without JQuery and JQuery.Live.
Especialy that i need to use addEventListner for future elements on the page.
Any alternative?
Thanks
Any emulation or alternative of live jquery function ?
I need to use an alternative of the live function without JQuery and JQuery.Live.
Especialy that i need to use addEventListner for future elements on the page.
Any alternative?
Thanks
Something like the following should work:
var live = function(elm, eventType, callback) {
document.addEventListener(eventType, function(event) {
if(event.target === elm) {
callback.call(elm, event);
}
});
};
You would then use it like follows:
var element = document.getElementById('test');
live(element, 'click', function() {
// handle click event here
});
EDIT: Excellent comments below. Here is a revised version:
var live = function(selector, eventType, callback) {
document.addEventListener(eventType, function(event) {
var elms = document.querySelectorAll(selector),
target = event.target || window.event.srcElement;
for (var i=0; i<elms.length; i++) {
if (elms[0] === target) callback.call(elms[i], event);
}
});
};
Use it with css selectors
live('#test', 'click', function() {
// handle click event here
});
jsFiddle: http://jsfiddle.net/49aJh/2/
You can emulate the .on()
functionality with this code:
HTMLElement.prototype.on = function (type, selector, func) {
var attach = window.addEventListener ? "addEventListener":"attachEvent",
elements = this.querySelectorAll(selector);
this[attach](type, function (e) {
var target = e && e.target || window.event.srcElement,
success = false;
while(target != this){
console.log("searching"+ target);
if (contained()){
success = true;
break;
}
target = target.parentNode;
}
if(success){func()}
// helpermethod
function contained(){ for (var i=elements.length;i--;){ if(elements[i] == target) return true; } }
});
};
document.querySelector("div").on("click", "span", function() {
console.log("gotcha!");
});
Should work in all browser down to IE8.