menu active in static html page Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of menu active in static html page without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a website with single header and footer, and I include header and footer in home and about pages, how the active class working

<ul>
    <li><a class="active" href="">menu1</a></li>
    <li><a class="" href="">menu1</a></li>
    <li><a class="" href="">menu1</a></li>
</ul>

Is using javascript and CSS the only way?

Answer

I know it’s will not run properly in there so i give you my git repo for clone : enter link description here. (dummy example).

Note:

  1. you need to run in host : http://127.0.0.1:5500/index.html.. or other .. i run it vs code (live server)
  2. I do it by matching window.location.pathname and a href url ..
  3. maybe there is many way to match current path a tag url
  4. if you have issue please comment. also i need to solve this problem for my own purpose

  // after page loaded  and page refresh  this will run to active current <a> tag
        window.addEventListener('DOMContentLoaded', (event) => {
            activeClass();
        });
       // after <a> button click
        document.querySelectorAll(".btn").forEach(function (btn) {
            btn.addEventListener("click", function (e) {
             
                activeClass();
            })
        })


        function activeClass() {
            document.querySelectorAll(".btn").forEach(function (btn) {

                // get href index.html or about.html or contact.html and add slash (/)
                var href = '/' + btn.getAttribute('href');

                // get path /index.html or /about.html or /contact.html from current url
                var pathname = window.location.pathname;

                // check click <a> element that contains .btn class
                if (btn.classList.contains('btn')) {

                    // check a href (/index.html) and current pathname (/index.html) are equal then add active class
                    if (href == pathname) {
                        btn.classList.add('active')
                        console.log('1')
                    }


                }

            });
        }
<a href="index.html" class="btn ">Home</a>
<a href="contact.html" class="btn ">Contact</a>
<a href="about.html" class="btn ">About</a>
We are here to answer your question about menu active in static html page - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji