Reputation: 69
function highlight1(){
document.getElementById("div1").classList.add("red");
}
function highlight2(){
document.getElementById("div2").classList.add("red");
}
function highlight3(){
document.getElementById("div3").classList.add("red");
}
div{
display: inline-block;
border: 1px solid black;
height: 100px;
width: 100px;
}
div:hover{
background: yellow;
}
.red{
background: red;
}
<div id="div1" onclick="highlight1()">Division</div>
<div id="div2" onclick="highlight2()">Division</div>
<div id="div3" onclick="highlight3()">Division</div>
I'm new to CSS and I have two questions for the code.
Upvotes: 3
Views: 390
Reputation: 13801
You can do this by applying, div.red:hover
by doing this you are actually overriding div:hover
with div.red:hover
prioritizing div.red:hover
function highlight1(){
document.getElementById("div1").classList.add("red");
}
function highlight2(){
document.getElementById("div2").classList.add("red");
}
function highlight3(){
document.getElementById("div3").classList.add("red");
}
div{
display: inline-block;
border: 1px solid black;
height: 100px;
width: 100px;
}
div:hover{
background: yellow;
}
div.red:hover,.red{
background: red;
}
<div id="div1" onclick="highlight1()">Division</div>
<div id="div2" onclick="highlight2()">Division</div>
<div id="div3" onclick="highlight3()">Division</div>
Upvotes: 0
Reputation: 371233
Your :hover
is making hovered div
s, even .red
div
s, appear hovered (yellow) instead of red. You could make hovered .red
divs red as well if you wanted.
If you only want one to be red at a time, you can remove .red
from all divs before using classList.add
.
It would also be more appropriate to use classes than individual id
s, because the elements are part of a collection rather than being unique in some way:
const divs = document.querySelectorAll('.box');
function reset(i) {
divs.forEach(div => div.classList.remove("red"));
divs[i].classList.add('red');
}
.box {
display: inline-block;
border: 1px solid black;
height: 100px;
width: 100px;
}
.box:hover {
background: yellow;
}
.red,
.red:hover {
background: red;
}
<div class="box" onclick="reset(0)">Division</div>
<div class="box" onclick="reset(1)">Division</div>
<div class="box" onclick="reset(2)">Division</div>
</html>
Upvotes: 2