Skip to content

Instantly share code, notes, and snippets.

@scott-thrillist
Last active August 15, 2016 22:14
Show Gist options
  • Save scott-thrillist/af6e68ac2de7289fa079481b201fb07a to your computer and use it in GitHub Desktop.
Save scott-thrillist/af6e68ac2de7289fa079481b201fb07a to your computer and use it in GitHub Desktop.
Event Delegation
<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