Last active
August 15, 2016 22:14
-
-
Save scott-thrillist/af6e68ac2de7289fa079481b201fb07a to your computer and use it in GitHub Desktop.
Event Delegation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<body> | |
<ul> | |
<li class="list-1">Item 1</li> | |
<li class="list-2">Item 2</li> | |
<li class="list-3">Item 3</li> | |
<li class="list-4">Item 4</li> | |
<li class="list-5">Item 5</li> | |
</ul> | |
<p><a href="#">Linkypoo</a></p> | |
<accordion> | |
<pane>Content 1</pane> | |
<pane>Content 2</pane> | |
<pane>Content 3</pane> | |
</accordion> | |
</body> | |
<!-- **** JS **** --> | |
<script> | |
// 5 separate event listeners - Bad | |
$('li').on('click', doSomething); | |
</script> | |
<script> | |
// 1 single event listener - Good | |
$('ul').on('click', 'li', doSomething); | |
</script> | |
<script> | |
// 1 single event listener, but event will run if anything on <body> is clicked, including the link and the accordion. - Bad practice | |
$('body').on('click', 'li', doSomething); | |
</script> | |
<script> | |
var doSomething = function() { | |
$(this).css('color', 'red'); | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment