Why does my toggleClass event add the class, but not remove it on subsequent clicks?

1.5k views Asked by At

I have a dropdown menu with the initial state of display: none. I'm using a toggleClass event to add a class with display: block, so that when the button is clicked on, the dropdown menu will appear and disappear.

The toggleClass works to add the class, but it won't remove the class when the button is clicked on again. When I look in my 'inspect element' tool in the browser, you can see the class "active" being added, but on subsequent clicks, "active" remains on the div. The classes still flash as though it is recognizing it's supposed to do something on click, but doesn't remove the "active" class.

The relevant code is as follows. You shouldn't need the css as the jquery is what's not working, but I've included it for reference.

    <div class="dropdown">
      <a class="dropbtn" id="button-services"><h4 class="button-arrow down-arrow">Service</h4></a>
      <div class="dropdown-content" id="dropdown-services">
        <a href="ourwork-advertising.php">Advertising</a>
        <a href="ourwork-environmental.php">Environmental</a>
        <a href="ourwork-interactive.php">Interactive</a>
        <a href="ourwork-logos.php">Logo</a>
        <a href="ourwork-packaging.php">Packaging</a>
        <a href="ourwork-print.php">Print</a>
      </div>
    </div>


.dropdown-content {
   display: none; }

.active{
   display: block; }


$('#button-services').click(function () {
    $('#dropdown-services').toggleClass("active");

});
2

There are 2 answers

0
sd.n On

if you return false after click it works for me if you return false after click it works for me $('#button-services').click(function () { $('#dropdown-services').toggleClass("active"); return false; });

0
Igor On

It does - see below. But I suspect from your description that you attach click event handlers multiple times. At some point there is even number of them firing - which removes and adds the class back. Where is the code attaching the click event handler located?

$('#button-services').click(function () {
    $('#dropdown-services').toggleClass("active");
    return false;
});
.dropdown-content 
{
   display: none; 
}

.active
{
   display: block; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown">
      <a class="dropbtn" id="button-services"><h4 class="button-arrow down-arrow">Service</h4></a>
      <div class="dropdown-content" id="dropdown-services">
        <a href="ourwork-advertising.php">Advertising</a>
        <a href="ourwork-environmental.php">Environmental</a>
        <a href="ourwork-interactive.php">Interactive</a>
        <a href="ourwork-logos.php">Logo</a>
        <a href="ourwork-packaging.php">Packaging</a>
        <a href="ourwork-print.php">Print</a>
      </div>
    </div>