In a bid to write better code and improve how I use jQuery, I've been doing some reading recently. One of the new tips I learnt is using event delegation with jQuery.
While reading, I discovered two "supposed" different methods of addressing it. Below are code snippets to illustrate them.
Assuming I have an HTML block like this:
<html>
<head>
<title>Test Code</title>
</head>
<body>
<div id="switcher">
<button id="button1">Button 1</button>
<button id="button2">Button 1</button>
<button id="button3">Button 2</button>
<button id="button4">Button 3</button>
<button id="button5">Button 4</button>
<button id="button5">Button 5</button>
<button id="button6">Button 6</button>
<button id="button7">Button 7</button>
<button id="button8">Button 8</button>
<button id="button9">Button 9</button>
</div>
<!-- rest of code here -->
</body>
</html>
On click, I want to:
- Retrieve the id of the button clicked (for further manipulation).
- Toggle the class to "active" for any of the buttons.
Instead of doing this:
$('#switcher').find('button').click(function(){
var $element = $(this);
var elementid = this.id;
$element.toggleClass('clicked');
//rest of code here
});
I can either do this (Method 1)
$('#switcher').click(function(eventName){
if ($(eventName.target).is('button')) {
var $element =$(eventName.target);
var elementid = eventName.target.id;
$element.toggleClass('active');
//rest of code here
}
});
Or this (Method 2)
$('#switcher').on('click', 'button', function(){
var $element = $(this);
var elementid = this.id;
$element.toggleClass('active');
//rest of code here
});
- Are these 2 actually both delegation techniques?
- If so, Which of the two methods is faster (or better performance wise) and handles delegation better?
- Are there browser limitations?