Gavin Steinhoff
Gavin Steinhoff

Reputation: 35

Dynamically Add active class

I am in charge of making a website for a club, but I cannot figure out how to add the active class dynamically.

I am restricted to just JS, so no server sided stuff.

Here is my header.

    <div class="topnav" id="myTopnav">
        <a href="index.html">Home</a>
        <a href="./about.html">About</a>
        <a href="./signUp.html">Sign Up</a>
        <a href="./host.html">Host a site</a>
        <a href="./photos.html">Photo Album</a>
        <a href="javascript:void(0);" style="font-size:15px;" class="icon" 
           onclick="myFunction()">&#9776;</a>
    </div>

I am loading my header from a file, so I don't know if that is messing with all the examples I have tried.

    $(function() {
        $("#header-placeholder").load("./layouts/header.html");
    });

Thanks in advance for your help!

Upvotes: 2

Views: 74

Answers (1)

Kishor Velayutham
Kishor Velayutham

Reputation: 818

Try this one.

$(function(){
        var current = location.pathname;
        $('#myTopnav a').each(function(){
            var $this = $(this);
            if($this.attr('href').indexOf(current) !== -1){
                $this.addClass('active');
            }
        })
    })

Hope it helps..!

Upvotes: 3

Related Questions