Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .toggleClass not toggling CSS class

Tags:

html

jquery

css

The .highlight class isn't working when toggled on #button. What am I doing wrong?

HTML:

<form>
    <input id="button" type="submit" value="Click Me">
</form>

CSS:

#button {
    background-color: #AABF1A;
}

.highlight {
    background-color: #555BBB;
}

jQuery:

$(document).ready(function () {
    $("#button").click(function() {
        $(this).toggleClass("highlight");
    });
});
like image 514
dpren Avatar asked Dec 13 '25 00:12

dpren


2 Answers

Your jQuery code is working. The issue is that your .highlight class does not have a high enough specificity to override the styles placed on the element by the #button selector. Try changing your CSS to this:

#button.highlight {
    background-color: #555BBB;
}
like image 103
Rory McCrossan Avatar answered Dec 15 '25 23:12

Rory McCrossan


Full code:

$(document).ready(function () {
$("#button").click(function(event) {
    event.preventDefault
    $(this).toggleClass("highlight");
});
});

Working fiddle: http://jsfiddle.net/robertrozas/9g8Jj/2/

like image 43
Hackerman Avatar answered Dec 15 '25 23:12

Hackerman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!