Learn

In the last exercise, we were toggling every ‘Recent Projects’ button instead of only the one we clicked on.

We can select the specific element we clicked on with the jQuery selector $(this).

The syntax looks like this:

$('.example-class').on('click', function() { $(this).toggleClass('active'); });
  1. $(this) selects the clicked element. If there are multiple elements with a class of .example-class, this will only toggle the class of the one that is clicked on.
  2. Notice that $(this) does not require quotes around it, since it is not a CSS class. Instead, this is a JavaScript keyword.
  3. $(this) behaves just like our other selectors. We can attach toggleClass or toggle to it in the same way.

Instructions

1.

Let’s begin by only changing the class of the element we clicked.

Modify the toggleClass we wrote in the last exercise to use $(this) as its selector.

2.

Now click on the ‘Recent Project’ buttons within each section and see that only the button you click on will toggle its class.

Next up, let’s toggle the projects in the section we clicked on, instead of toggling them all.

Click ‘Next’ to continue.

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Already have an account?