简体   繁体   中英

Navbar active using javascript

I have this one problem regarding the highlighted navbar menu which will only highlight when we clicked on it. For that to work, I'm using javascript. However, each pages has its own sub pages, for example, page Home has a link of local/home, but its content will lead to local/home/content. The sub link will not make the navbar to function The navbar was coded in different file, which I just extends in the home and other pages. I'm not very good at explaining but if I can elaborate more on any part I would do so. Below I attached my JS and my navbar:

HTML:

<ul class="navbar-nav mr-auto" id="nav">
            <li class="nav-item">
                <a class="nav-link active" href="{{ url('/') }}">Home
                    <span class="sr-only">(current)</span>
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="{{ route('courses') }}">opportunities</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="{{ route('events') }}">events</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="{{ route('uqalc') }}">courses</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="{{ route('contact') }}">contact</a>
            </li>
        </ul>

JS:

const currloc = location.href;
        const menuItem = document.querySelectorAll('a');
        const menuLen = menuItem.length;
        for (let i = 0; i < menuLen; i++) {
            menuItem[i].classList.remove('active');
            if (menuItem[i].href === currloc) {
                menuItem[i].className = "nav-link active";
            }
        }

From what I read from your question, you want the navbar to change color when clicked. This can be easily accomplished in two different ways.

The first is making a #Active id that would be given to the proper navbar link on every page. (More here )

The second is if you are staying on the same page but still want the button to change color when clicked. (More here )

Either way is effective.


Have questions? Comment download below. Like my answer? Give me a checkmark and up-vote.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM