Question

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
}
Was it helpful?

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.

OTHER TIPS

It is because the priority order of a class is lower than the style attribute.

When you set the CSS property directly on the element, this takes priority over your toggled class. To make it work you have to add another class.

.enter {
   background: #656565;
}

And then your JS would be like this:

$('div').mouseenter(function(){
   $(this).addClass("enter");
});
$('div').mouseleave(function(){
   $(this).removeClass("enter");
});
$('div').click(function(){
   $(this).toggleClass('active');
});

See this fiddle http://jsfiddle.net/w8yuZ/5/

Try this:

$(function(){

    $('div').mouseenter(function(){
        $(this).css('background','#656565');
    });

    $('div').mouseleave(function(){
        $(this).css('background','#4a4a4a');
    });

    $('div').click(function(){
        $(this).toggleClass('active');
    });

});

this will help you:

.active {
    background: #96f226 !important;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top