Search code examples
jqueryhtmlcsstoggleclass

$().toggleClass(); not working


Here is the Fiddle. I am trying to make my own checkbox by using a <div>, and applying colors with $().css(). When you click the div, I am trying to use $().toggleClass() in a click function to change the background-color to #96f226

jQuery:

$('div').mouseenter(function(){
    $(this).css('background','#656565');
});
$('div').mouseleave(function(){
    $(this).css('background','#4a4a4a');
});
$('div').click(function(){
    $(this).toggleClass('active');
});

HTML:

<div></div>

CSS:

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

Solution

  • 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
    }
    div.active, div.active:hover {
        background: #96f226
    }
    

    And here's a Fiddle to play with.