Highlight active link with jquery

I am trying to highlight the active link, it underlines it, but the underline is suddenly deleted. I can’t understand what I am doing wrong:

$(document).ready(function () {
    var str = location.href.toLowerCase();
    $('nav ul li a').each(function () {
        if (str.indexOf(this.href.toLowerCase()) > -1) {
            $('a.active').removeClass('active');
            $(this).parent().addClass('active');
        }
    });
});

HTML:

<nav>
    <ul>
        <li><a class="active" href="#intro" title="Intro">Intro</a></li>
        <li><a href="#what" title="What We Do">What We Do</a></li>
        <li><a href="#how" title="How We Do It">How We Do It</a></li>
        <li><a href="#modus" title="Our Modus Operandi">Our Modus Operandi</a></li>
    </ul>
</nav>

Any help? Thank.

+4
source share
2 answers

I can tell you what you are doing wrong! You remove the active class from the tag a, and then add it to it parent, which is equal li. So basically you need to add it back to the current one a, and you can do it by simply deleting it .parent()before adding the class active, and your updated function will look like this:

$(document).ready(function () {
    var str = location.href.toLowerCase();
    $('nav ul li a').each(function () {
        if (str.indexOf(this.href.toLowerCase()) > -1) {
            $('a.active').removeClass('active');
            $(this).addClass('active');
        }
    });
});
+1
source

, :

$('nav li').click(function(e) {
    e.preventDefault();
    $('nav li a.active').removeClass('active');
    $('a', this).addClass('active');
});

Fiddle .

0

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


All Articles