Highlight current menu item not working, why?

Highlight current menu item not working, why? I think I am doing everything right, but it does not work.

Can you help a little?

Html:

<section id="menu-container">
    <div id="bar"><img src="border.png" /></div>
    <nav id="menu">
        <ul>
            <li id><a href="#">Home</a></li>
            <li><a href="page.html1">Home2</a></li>
            <li><a href="page.html2">Home3</a></li>
            <li><a href="page.html3">Home4</a></li>
            <li><a href="page.html4">Home5</a></li>
        </ul>
    </nav>
</section>

JavaScript:

$(function(){

    var url = window.location.href; 

    $("#menu ul  li a").each(function() {

        if(url == (this.href)) { 
            $(this).closest("li").addClass("active");
        }
    });
});

CSS

.active{
    background-color:#0C3;
}
+4
source share
3 answers

Use $(this).attr("href")to get value hreffrom your links since you are already using jQuery.

Combine this with the andrew clause to get the end of the current URL, and now you have the best values ​​to check in the instruction if.

$(function(){
    var url = window.location.href.split('/'); 
    url = url[url.length-1];

    $("#menu a").each(function() {
        var $this = $(this); // to minimize DOM traversal
        if (url === $this.attr("href")) {
            $this.closest("li").addClass("active");
        }
    });
});


UPDATE:

Even better would be to use advanced jQuery selectors:

$(function(){
    var url = window.location.href.split('/'); 
    url = url[url.length-1];

    $("#menu a[href='" + url + "'").addClass("active");
});
+1
source
this.location.href // http://stackoverflow.com/questions/22120946/highlight-current-menu-item-is-not-working-why

to try:

 var url = window.location.href.split('/');
 url = url[url.length-1];
0
source
var url = window.location.href;
$('#menu a').each(function(k,s) {
    if(this == url){
        $(this).addClass('active');
    }
});

fiddle . .

0

Source: https://habr.com/ru/post/1529606/


All Articles