I have a div with it’s style class. I define it’s style as follow.
.widgetContainer:hover{ border-radius: 0rem; top: 0rem; left: 0rem; height: 100%; width: 100%; }
And in JS I define a method for a click event.
exitWidget(event){ if(event.target === document.getElementsByClassName("widgetContainer")[0]) { document.getElementsByClassName("widgetContainer")[0].style.height = "3rem"; document.getElementsByClassName("widgetContainer")[0].style.width = "3rem"; } }
The CSS style and the event do what is expected. The problem is when I hover the div again after the event. The properties height and width don’t grow to fill the screen. It’s like JS overrided the CSS properties. Is there something I’m missing?
Advertisement
Answer
While the comments do correctly tell you that inline styles are the most specific type of style you can apply, and are therefore the most difficult to override, avoid using !important
whenever you can because it’s an override to the normal specificity rules that CSS follows and makes your code harder to understand and maintain.
Instead, use CSS classes when you can because it’s easy to override a class with another class. And while you’ve done that for your ":hover"
styling, you can also do it in JS using the classList
API, which makes the code even simpler and easy to scale without duplication of code.
Oh, and don’t use getElementsByClassName()
.
// Just get your static element references just once, not every time // the function runs and don't use getElementsByClassName(). const widget = document.querySelector(".widgetContainer"); widget.addEventListener("mouseout", exitWidget); function exitWidget(event){ if(event.target === widget){ widget.classList.add("otherClass"); // <-- How simple is that?! } }
.widgetContainer:hover{ border-radius: 0rem; top: 0rem; left: 0rem; height: 100%; width: 100%; background:yellow; } .otherClass { height:3rem; width:3rem; }
<div class="widgetContainer">This is the widget container</div>