JavaScript jQuery Basics Understanding jQuery Events and DOM Traversal What is Traversal?

Ming Chi Wong
Ming Chi Wong
1,158 Points

The purpose of using button?

I don't quite understand why the "button" is used in the on click function?

2 Answers

Michael Hulet
Michael Hulet
Treehouse Moderator 47,600 Points

According to jQuery's documentation, you can pass a string to the on method as the 2nd parameter that will act as a filter on which element(s) to add the listener to. In our case, we have this line:

$(".spoiler").on("click", "button", () => {});

This gets all elements with the spoiler class, and then applies our click handler to all button elements that are children of an element with the spoiler class. For example:

<div class="spoiler">
    <p>No click handler will be applied to this element</p>
    <button>The click handler will work with this element!</button>

<button>The click handler will not apply to this element</button>
Anastasios Poursaitedes
Anastasios Poursaitedes
8,810 Points

Well to understand why the button is used you have to understand Event Delegation. In a nutshell, event delegation is the ability to attach a single event listener (as opposed to attaching many event listeners to every single button on the page in our case) to a parent element that will fire for all of its descendants(its children) that match a selector(in our case the button selector). In other words we're saying 'Ok parent element I want you to hear for an event but only when it happens to a child of yours that matches the selector I'm giving '. What's cool about this way of attaching event listeners is that if we want to add another spoiler, the event handler will be attached to the new spoiler's button. If we had done it the other way(attaching the event to each and every spoiler ) then whenever we add a new button we'd have to attach the event handler to that button.