hey there. I am playing around with some code today and I found something interesting that I dont understand. In this code there is a grid of boxes. when you hover over a box it will change colors. When you click a box it will stay that color. there is a clear button at the bottom which resets all the boxes to the original color. The weird thing is when you click the clear button the :hover psuedo class no longer works. I am curious as to why this is happening? any ideas, please let me know. Thanks, and happy coding.
I could be wrong, but I believe this is because JS has a higher specificity than most CSS does, including the pseudo selectors. This would mean that the JS setting the background-color would override the CSS.
Now I believe you could set the CSS higher using !important
though I’d try to steer away from that. Perhaps use the js .onmouseover
attribute to set the background color?
Agreed. On the clear event, instead of setting all of the background colors back to the original color, why not just remove the background-color property completely so they are back to their original state?
That would make sense. Thanks for the insight!
I’d suggest using classes and the classList methods. Inline styles often lead to specificity issues. It’s also cleaner than having to write the styles in the JS.
thanks for the input @lasjorg. I looked over the mdn docs, but i’m curious on your opinion. how should I implement classList methods to this project?
You would create a class for the color and add/remove/toggle it as needed.
But you didn’t have the color picker when I looked at the project. For it to work without inline styles you might use custom properties. The property is set inline but the actual styles are coming from a class (with a class specificity).
.selected-color {
--color: lightgrey;
background-color: var(--color);
}
point.forEach((item, index, array) => {
item.setAttribute("x", item.offsetLeft);
item.setAttribute("y", item.offsetTop);
item.onclick = () => {
item.classList.toggle("selected-color");
item.style.setProperty("--color", colorPicker.value);
};
});
clear.onclick = function () {
point.forEach((element, index) => {
element.classList.remove("selected-color");
});
};
Hey,
I just wanted to post an update on this project for everyone that helped me out along the way. @bbsmooth , @8-bitgaming , @lasjorg . Believe it or not, this project has been a couple years in the making. This new version was coded in about 2 weeks. It is a small milestone on my coding journey and I’m thankful for the help I’ve received along the way. I still need to polish it up a bit, but the functionality is working like I want it to. I’m always open to suggestions on how I can improve. thanks, and happy coding!
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.