Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

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
47,912 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>
</div>

<button>The click handler will not apply to this element</button>

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.