Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript jQuery Basics (2014) Creating a Mobile Drop Down Menu Perform: Part 3

Robert Leonardi
Robert Leonardi
17,151 Points

Alternative solution to SELECTED

First of all, I deleted ALL files with <li class="selected"> to just <li>

then I added this to app.js These will automatically add the class=selected on menu ul li and will automatically add selected=selected on select option both according to current page

        // set pathname
    let url = window.location.pathname;
    // cut all the pathname except the file name.
    let filename = url.substring(url.lastIndexOf('/')+1);
    // find the li a href = filename and ADD class selected to the li
    $('#menu li a[href|="'+filename+'"]').parent("li").addClass("selected");
    // find the seleect option value = filename and ADD selected to the option
    $('#menu select option[value|="'+filename+'"]').attr("selected","selected");

1 Answer

Steven Parker
Steven Parker
215,960 Points

Dynamic handling is not needed for this.

Sure, it would work, but which item should have the selected class would never change for any particular page, so this is an occasion where it makes more sense to include the class directly in the HTML.

However, dynamic handling might come in handy when the control is being used for something other than changing the page location, but in that case you would have an event handler and use the event target to identify the selected item.

Robert Leonardi
Robert Leonardi
17,151 Points

I think that make sense I hate it when I overdo something hahaha thanks for valuable input