Jordan U. Jordan U. - 2 months ago 6
jQuery Question

jQuery toggleClass Isn't Working

I'm working on a website that has a button that shows a menu when clicked. I'm trying to get it to change colour when active, but the toggleClass isn't changing the background colour when the button is clicked. Here is the code I'm using.

HTML

<div class="services-btn mobile">Services</div>


CSS

div.services-btn {
background-color: black;
color: #f9f9f9;
cursor: pointer;
float: left;
margin: 10px;
padding: 15px 0;
text-align: center;
width: 80px;
}

.active-btn {
background-color: darkred;
}


jQuery

$(".services-btn").click(function () {
$(this).toggleClass("active-btn");
});

Answer

Change your CSS to this

div.services-btn {
    background-color: black;
    color: #f9f9f9;
    cursor: pointer;
    float: left;
    margin: 10px;
    padding: 15px 0;
    text-align: center;
    width: 80px;
}

div.services-btn.active {
    background-color: darkred;
}

It because in your jQuery your add .active class, not .active-btn as you type on your code on CSS. You can also change your jQuery add class into .active-btn and don't change your CSS and it works properly too.

Comments