Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to add class (active) on specific li on user click with jQuery

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.65k
    Comment on it

    Mostly every website contains a navigation menu so it's constantly great to make it so the guests or client on the website knows on which page or part of the website he is on. This can be proficient by including a "dynamic class" or "active class" to the menu thing that links to the page on which the guest or client is.

    For this purpose we are making a navigation menu with the help of html just to explain how to add active class on the links.

    Below is html code :-

    <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">Events</a></li>
    <li><a href="#">Blogs</a></li>
    <li><a href="#">FAQ</a></li>
    </ul>
    

     Below is css for above navbar :-

    ul li{
    float:left;
    list-style:none;
    margin-right:20px;
    }
    ul li a{
     text-decoration:none;
    }
    .active
    {
        background-color:green;
    }

    Now we need jQuery code for adding active class for particular <li> in which we have clicked.

    $('li a').click(function(){
        $('li a').removeClass("active");
        $(this).addClass("active");
    });

    With the help of above jQuery code when we click on any <li> ,a active class get append on the anchor tag with in  it which makes its background-color green and it remove the active class from previously selected anchor .

    Working demo:- https://jsfiddle.net/232h7xvd/9/

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: