jqueryaddclassremoveclass

if hasclass addclass else removeclass not working


This is my markup

<header id="header">
    <nav>
        <ul class="menu">
            <li id="homeSecLink" class="active"><a href="#Home" class="homeLink">Home</a></li>
            <li><a href="#Partners">Partners</a></li>
            <li><a href="#About">About</a></li>
            <li><a href="#Contact">Contact</a></li>
        </ul>
    </nav>
</header>

On page load I am trying to add class borderGap on header if homeSecLink has active class else remove borderGap

Here addClass working but removeClass not working

This is what I have done:

$(document).ready(function() {
    if ($('#homeSecLink').hasClass("active")) {
        $('#header').addClass('borderGap');
    } else {
        $('#header').removeClass('borderGap');
    }
});

Solution

  • For removeClass to work you need to remove active class

    HTML

    <header id="header">
        <nav>
            <ul class="menu">
                <li id="homeSecLink" class="active"><a href="#Home" class="homeLink">Home</a></li>
                <li><a href="#Partners">Partners</a></li>
                <li><a href="#About">About</a></li>
                <li><a href="#Contact">Contact</a></li>
            </ul>
        </nav>
    </header>
    <a id="toggle">Toggle</a>
    

    JavaScript

    $(document).ready(function() {
        $('#toggle').click(function() {
            if ($('#homeSecLink').hasClass("active")) {
                $('#header').addClass('borderGap');
                $('#homeSecLink').removeClass('active');
            } else {
                $('#header').removeClass('borderGap');
                $('#homeSecLink').addClass('active');
            }
        });
    });
    

    Demo Link