I’m working on a portfolio website and I have a menu bar at the top with 3 buttons.
My issue is that, when I change the theme of the page from dark to light with a toggle, effects on hover for some elements such as buttons stops working.
HTML
<div class="container-menu">
<button class="menu-button" id="home">Home</button>
<button class="menu-button" id="project">Projects</button>
<button class="menu-button" id="about">About Me</button>
</div>
CSS
.container-menu{
padding-top: 0.5em;
display: flex;
justify-content: space-around;
width: 20em;
}
.menu-button{
font-size: 20;
width: fit-content;
height: 2em;
padding-top: 0;
padding-bottom: 0;
border: 0;
background-color: rgb(10, 0, 10);
color: #f0f0f0;
cursor: pointer;
}
I have a toggle switch that changes the page from light mode to dark mode with the help of javascript.
js
const checkbox=document.querySelector(".theme-checkbox");
const containertop=document.querySelector(".container-top");
const menubuttons = document.querySelectorAll(".menu-button");
checkbox.addEventListener("change", () => {
if(checkbox.checked){
document.body.style.backgroundColor="#f0f0f0";
document.body.style.color="#0a000a";
containertop.style.backgroundColor="#f0f0f0";
menubuttons.forEach((button) => {
button.style.backgroundColor = "#f0f0f0";
button.style.color = "#0a000a";
});
} else {
document.body.style.backgroundColor="#0a000a";
document.body.style.color="#f0f0f0";
containertop.style.backgroundColor="#0a000a";
menubuttons.forEach((button) => {
button.style.backgroundColor = "#0a000a";
button.style.color = "#f0f0f0";
});
}
});
Just giving
.menu-button:hover{
color: rgb(255, 105, 105);
transition-duration: 0.3s;
}
Makes the color of the button change when I hover but once I toggle to light mode or even toggle back to dark mode, the hover effect does not work. This seems to be some issue with the fact that I am changing the color of the text on hover as well as during theme change. Is there any way to get around this?
Doing the following works but it is unstable. When i switch to light mode, the text color changes to the hover color and when I hover over the button, it changes back to black and then the hover function works. Is there any alternative to this?
.menu-button:hover{
color: rgb(255, 105, 105) !important;
transition-duration: 0.3s !important;
}
2
Answers
Instead of changing the styles directly on your Javascript, change to a toggle to add a property definid on your CSS code (
Dark mode
andLight Mode
), and then you can definy the styles for your button for both modes.CSS:
Javascript:
The style attribute is more important than class.
You can change this behavior by adding a custom class name instead of a "style" attribute"
and create a css class for that: