S
S
Shahriyor_dev2022-04-17 17:18:07
css
Shahriyor_dev, 2022-04-17 17:18:07

How to write navigation bar js script?

The site has a navigation bar, but it does not work correctly:
1. On reload, 1 remains active, but the hash remains as 3 or 4
2. When scrolling to a certain section, it does not change activity

An example of how this navigation works is here: https://bankrot-fpk .ru/

My js code:

const navLink = document.querySelectorAll('.m_scrollspy ul .nav-link');


for (let i = 0; i < navLink.length; i++) {
    navLink[i].onclick = () => {
        // Удаляем класс у всех
        navLink.forEach(function(el) {
            el.classList.remove('active');
        });
        //Добавляем класс выбранному
        if (!navLink[i].classList.contains('active')) {
            navLink[i].classList.add('active')
        }
    }
}


<div class="m_scrollspy" id="navbar-example">
        <ul class="nav nav-tabs" role="tablist">
            <li class="nav-item"><a href="#m_one" class="nav-link active">01</a></li>
            <li class="nav-item"><a href="#m_two" class="nav-link">02</a></li>
            <li class="nav-item"><a href="#m_three" class="nav-link">03</a></li>
            <li class="nav-item"><a href="#m_four" class="nav-link">04</a></li>
            <li class="nav-item"><a href="#m_five" class="nav-link">05</a></li>
            <li class="nav-item"><a href="#m_six" class="nav-link">06</a></li>
            <li class="nav-item"><a href="#m_seven" class="nav-link">07</a></li>
            <li class="nav-item"><a href="#m_eight" class="nav-link">08</a></li>
        </ul>
    </div>


Please help me more

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey T, 2022-04-22
@tihomirovPro

Here is an example solution, you can adapt it to your code
https://codepen.io/tihomirovpro/pen/abExZrv

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question