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 (2014) Creating a Mobile Drop Down Menu Perform: Part 3

Chetan Jaisinghani
Chetan Jaisinghani
2,896 Points

Why hasn't anyone asked this?

In the code shown in the video, the class "selected" has been given to only one anchor's parent, i.e. to the "events" link. If that is the case, why does the if condition apply to all the other links? I tried doing it along the video and the if clause never applied to any other links besides "Home" because apparently in my workspace only the Home anchor's parent has the class "selected". So I modified the index file to have the class "selected" to all the anchors and then it works just as required. Am I missing something here? How do they never have any issues with their code whatsoever? Not even browser issues or cached history? According to what's being taught in the video, the if clause should not be working for any other link besides the "events" link. What's happening?

1 Answer

Samuel Webb
Samuel Webb
25,370 Points

You're selecting the element based on the class, not on the event. So on each page, you set the class of that specific link (parent) to selected. For example, when you're on the home page, index.html's link should be the only one to have the class selected. Same for any other page, only the corresponding link should be the one with the selected class. Then you're selecting that one element and giving it the actual HTML property selected.

A little further, this actually has nothing to do with the event. When the page loads, this selection happens $('#menu a') which is all of the anchor elements in the menu. Then you run a .each() function which means it will perform what's inside of the function body on all of the elements in the array returned from$('#menu a'). Along with a few other things, the function checks to see if the current element in the array has the selected class. If it doesn't, it won't apply the HTML selected property to it. Once it's done, it checks the next element, and the next element. That's why the if statement applies to all of the anchor elements in the menu. Again, this has nothing to do with the event (clicking the button), this is something that happens every time one of the pages load.

Thanks for this answer. It certainly helped me understand what is happening much better.