In one of the earlier article I have explained about Event Delegation in MooTools. So if you are not sure about the Event Delegation in JavaScript then you can refer this link.
Now in this article I am going to cover Event Delegation with jQuery.
MooTools uses [code]relay[/code] for this while earlier version of jQuery use [code].delegate()[/code] form the version 1.7 this function is replaced by the [code].on()[/code].
So now rather than explaining about Event Delegation, I will just explain the code in jQuery. Here you can find the example with both methods which are [code].on()[/code] and [code].delegate()[/code].
[cc lang=”html”]
[/cc]
[cc lang=”javascript”]
// Getting the object of parent Element
var obj = $(‘#parent_ele’);
// Here comes the Event Delegation
// For jquery below 1.7
obj.delegate(“a”, “click”, function(){
console.log(‘I am Clicked’);
});
// For jQuery 1.7 and above
obj.on(“a”, “click”, function(){
console.log(‘I am Clicked’);
});
[/cc]
really nice tips!, thanx
But “delegate” function on jQuery works when you add other element into a website, for example.
[cc lang=”javascript”]
obj.on(“a”, “click”, function(){
obj.append(“Testing“);
});
[/cc]
This doesn’t works but if you use:
[cc lang=”javascript”]
obj.delegate(“a”, “click”, function(){
obj.append(“Testing“);
});
[/cc]
Works
I think you’re missing a ‘#’ here: var obj = $(‘parent_ele’); before parent, as you’re referencing the id “parent_ele”
Yes I am, updated thanks for noticing… :)