Travus Gonzalez
Travus Gonzalez

Reputation: 89

jQuery toggle not working after addClass is called

So I have a click function that toggles a button on my page. I also have another function that adds a class to the button if a checkbox is checked. My problem is if the class is added to the button then the click function is hit the toggle does not change the inline style.

$(".btn").click(function() {
    $(".anotherBtn").toggle();
}


function getsCalledWhenCheckBoxIsChecked() {
    $(".anotherBtn").addClass("hideBtn");
}

<style>
.hideBtn {
    display: none !important;
}
</style>

This is part of a much larger system and I have greatly over simplified the code simply to display what is generally happening. When viewing the page in chrome with developer tools I can see that when the "hideBtn" class is added the inline style does not change when toggle is hit yet it does on other elements. When the class is removed it works again.

Toggle works

<button class="anotherButton" style="display: inline-block;"></button> 
<button class="anotherButton" style="display: none;"></button>

Toggle does not change to display: none

<button class="anotherButton hideBtn" style="display: inline-block;"></button>
<button class="anotherButton hideBtn" style="display: inline-block;"></button>

Any thoughts or help is appreciated.

Upvotes: 0

Views: 81

Answers (1)

charlietfl
charlietfl

Reputation: 171700

Your problem is that when you use display: none !important; it will override the inline style style="display: inline-block;" that toggle() will generate.

The specific issue is using !important

You can confirm this in a browser console by inspecting the CSS rules applicable to the element.

There are a number of workarounds but the first one would be to see if you really need !important at all

Upvotes: 2

Related Questions