Simple Version Of Jquery Live Function
Solution 1:
Event delegation is quite simple. Take this example:
Markup:
<divid="container"><p>Test</p><p>Test</p><p>Test</p></div><buttonid="add">Add new paragraph</button>
Script:
document.getElementById("container").onclick = function(e) {
// e.target is the target of the event or "source element"alert(e.target.innerHTML);
};
// dynamically adds new paragraph on button clickdocument.getElementById("add").onclick = function() {
var p = document.createElement("p");
p.innerHTML = "a new paragraph";
document.getElementById("container").appendChild(p);
};
Since the event handler is attached to the parent, it will work for any future elements inserted.
Useful reference:
Solution 2:
Yes, it's called event delegation and has been around longer than jQuery and "live".
"live" works by listening for events on the body or document, then when when an event occurs looks at the event.target to see if it's selector matches one of those stored in a cache. It is quite inefficient, but works OK for some.
A more efficient approach is to add elements you want listeners on to an array, then listen for bubbling events on the lowest common ancestor of the elements you want to delegate events for. The body element is the fallback, but it's the least efficient. When the listener gets an event it's waiting for, check if the event.target is one of the elements in the array and if so, call the related function with the element as this.
You can also just store the element id as a property of an object so looking it up is faster if you have lots of elements, or you can register events based on class.
There are a few limitations and foibles (some events bubble in some browsers but not others, and some don't bubble at all), and it can be very inefficient, so use with care.
Solution 3:
I know little of Jquery and your functions. You are looking how works with events in javascript? You can make this:
element.addEventListener('onclick',
function() {
//do something
});
or
element.onclick =
function() {
//do something
});
the element
var is an reference of dom document.
check https://developer.mozilla.org/en/DOM for more details.
Solution 4:
JQuery is pure JavaScript and OpenSource, so just have a look into the sources, then copy what you need and adapt it.
Post a Comment for "Simple Version Of Jquery Live Function"