I have a simple script below where I want to change the background color on hover for different buttons (regular/inactive and active) and toggle between the two states upon clicking.
Although the code successfully changes the background color during hover, it does not toggle as intended.
<script type="text/javascript>
$(".button").hover(
function() {
$(this).css("background-color", "#E4E4E4");
},
function() {
$(this).css("background-color", "#EDEDED");
}
);
$(".active").hover(
function() {
$(this).css("background-color", "#F5F9FF");
},
function() {
$(this).css("background-color", "#EBF3FF");
}
);
$(".button").click(function() {
alert("The button is clicked!");
$(this).toggleClass("active");
});
</script>
This other code successfully toggles the buttons but requires disabling hover functionality for the toggle to occur.
<script type="text/javascript">/*
$(".button").hover(
function() {
$(this).css("background-color", "#E4E4E4");
},
function() {
$(this).css("background-color", "#EDEDED");
}
);
$(".active").hover(
function() {
$(this).css("background-color", "#F5F9FF");
},
function() {
$(this).css("background-color", "#EBF3FF");
}
);*/
$(".button").click(function() {
alert("The button is clicked!");
$(this).toggleClass("active");
});
</script>
In summary, I am facing difficulty using hover()
and toggleClass()
simultaneously.
Note: The alert message still functions.