Joe P. Joe P. - 4 months ago 4x
HTML Question

$().toggleClass(); not working

Here is the Fiddle. I am trying to make my own checkbox by using a

, and applying colors with
. When you click the
, I am trying to use
in a click function to change the background-color to






div {
width: 15px;
height: 15px;
background: #4a4a4a;
cursor: pointer;
.active {
background: #96f226


With that .css call for 'background' property, you change the corresponding inline style of an element, specified as its attribute. In other words, your mouseenter handler turns <div> into <div style="background: ##656565">. mouseleave works the similar way, it's just the value of style attribute that is different.

The problem is that style rule set in that way - within style attribute - has the highest specificity than the one applied as a result of a class-match rule (or any combination of selectors) given in the CSS ruleset.

That's why you don't see any changes when class active is added to the element (and it's easy to check that the class IS added indeed; it's just its rule that's not accounted).

That problem is quite easy to fix if you remove all fiddling with inline styles altogether, and use another class - for mouseenter handler to set, and mouseleave to remove.

But actually, you don't even need that: the events you're trying to process are already handled by browser, in quite a good way. It's to easy to leverage: just set up the style rules for :hover pseudo-class, like this:

div:hover {
    background: #656565
}, {
    background: #96f226

And here's a Fiddle to play with.