Reputation: 11
I want the color of the active elements to change when it's hovered, and when it's not active the hover color should be different.
"highlightbutton" class is not removed after the "toggleclass" and I can't seem to manage to apply a code to change hover color when the item is clicked and when it's clicked back to default unclicked state it should revert back to original hover color when hovered.
Here is my code:
$(".toggle").hover(function() {
$(this).addClass("highlightbutton");
}, function() {
$(this).removeClass("highlightbutton");
});
$(".toggle").click(function() {
$(this).toggleClass("active");
$(this).removeClass("highlightbutton");
});
css
.active {
background-color: #E8F2FF;
}
.highlightbutton {
background-color: #E4E4E4;
}
Upvotes: 1
Views: 210
Reputation: 20830
Use jQuery to add and remove your .active
class. Everything else can be handled by CSS
$(".toggle").click(function() {
$(this).toggleClass("is-active");
});
.toggle:hover {
background-color: #E4E4E4;
}
.toggle.is-active {
background-color: black;
color: white;
}
.toggle.is-active:hover {
background-color: #666;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="toggle">toggle button</button>
The toggling of an active
class can also be achieved with vanilla JS:
[...document.querySelectorAll('.toggle')].forEach(toggle => {
toggle.addEventListener('click', e => e.target.classList.toggle('is-active'));
})
.toggle:hover {
background-color: #E4E4E4;
}
.toggle.is-active {
background-color: black;
color: white;
}
.toggle.is-active:hover {
background-color: #666;
}
<div class="toggle">toggle button</div>
<div class="toggle">toggle button 2</div>
<div class="toggle">toggle button 3</div>
Upvotes: 2
Reputation: 2300
As @connexo has said, this is more of a css case.
you can either add an id to the thing you want to highlight do this:
.toggle:hover{
//Colour changing
}
.toggle:active{
//Colour changing
}
or you could add an ID to the element and do it this way:
#toggle:hover{
//Colour changing
}
Upvotes: 2
Reputation: 1301
Just edited my fiddle, here is your answer : https://jsfiddle.net/csdgyhof/2/
$(".toggle").hover(function() {
$(this).addClass("highlightbutton");
}, function() {
$(this).removeClass("highlightbutton");
});
$(".toggle").click(function() {
$(this).toggleClass("active");
});
CSS
.active {
background-color: #E8F2FF !important;
}
.highlightbutton {
background-color: #E4E4E4;
}
On the click event you removed the needed class. Instead of using !important (hard to override) look into css priorities.
Upvotes: 1