How to add active class on a onepage site?

Asked

Viewed 150 times

1

Nice club, you guys. I have a onepage site that has a menu in Sticky-top mode, would like to know how I do to add s class "active" via JS in the correct way according to the page being viewed at the moment.

<nav class="navbar navbar-expand-lg navbar-dark bg-color4 shadow sticky-top" id="navbar">
<div class="container">
    <a class="navbar-brand" href="#">
        <img src="img/cafe.png" alt="spella icon" class="w-35 invert-img">
    </a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav ml-auto">
        <li class="nav-item active">
            <a class="nav-link nav-text scroll" href="#home">Home <span class="sr-only">(Home)</span></a>
        </li>
        <li class="nav-item">
            <a class="nav-link nav-text scroll" href="#about">About</a>
        </li>
        <li class="nav-item">
            <a class="nav-link scroll" href="#menu">Menu</a>
        </li>
        <li class="nav-item">
            <a class="nav-link scroll" href="#comments">Comments</a>
        </li>
        <li class="nav-item">
            <a class="nav-link scroll" href="#map">Map</a>
        </li>
        </ul>
    </div>
</div>

That’s my JS code, it’s doing the smooth scroll function, but I’d like you to add the "active" class to the menu.

var $doc = $('html, body');
$('.scroll').click(function () {
    $doc.animate({ scrollTop: $($.attr(this, 'href')).offset().top }, 500);
    $($doc).toggleClass("active");
    return false;
});

1 answer

0

I’m not sure in which action you intend to change the class to active.

try this:

$(function () {
            var nav = $('#navbar');
            $(window).scroll(function () {
                if ($(this).scrollTop() > 500) {
                    nav.addClass("active");
                } else {
                    nav.removeClass("active");
                }
            });
        });

if not, explains what I would like to happen with the navbar and in what action.

hope it helps

Browser other questions tagged

You are not signed in. Login or sign up in order to post.