Home > Enterprise >  How do I change the contents of a CSS element after a :hover pseudo-element activates using JavaScri
How do I change the contents of a CSS element after a :hover pseudo-element activates using JavaScri

Time:01-07

I currently have 2 boxes, one box that is red, and when my mouse hover overs it the box turns red. The other box is blue, and when my mouse hovers over the box it turns blue.

What I want to have happen is that when my mouse hovers over box 1 the box turns blue AND box 2 turns red. (Same idea with Box 2 but switch the colors

Here is the code that I tried already, I know that the issue is with the JavaScript but I don't understand why the JavaScript isn't working

const outlineOne = document.querySelector('.outlineOne');
const outlineOneHover = window.getComputedStyle(outlineOne, ':hover');
const outlineTwo = document.getElementsByClassName('outlineTwo')
if (outlineOneHover.style.background = blue) {
  outlineTwo[0].style.backgroundColor = 'red';
};
body {
  background: #2F2F2F
}

.outlineOne,
.outlineTwo {
  display: inline-block;
  background: #2F2F2F;
  width: 100px;
  height: 100px;
  border: 2px solid black;
  margin: 20px 20px;
}

.outlineTwo {
  background: blue;
}

.outlineOne {
  background: red;
}

.outlineOne:hover {
  background: blue;
}

.outlineTwo:hover {
  background: red;
}
<div class='parent'>
  <div ></div>
  <div ></div>
</div>

CodePudding user response:

You can toggle a single class on both objects on mouseover and mouseout.

const outlineOne = document.querySelector('.outlineOne');
const outlineTwo = document.querySelector('.outlineTwo');

function changeBG(){
    outlineOne.classList.toggle("active");
    outlineTwo.classList.toggle("active");
}


outlineOne.addEventListener("mouseover",changeBG);
outlineTwo.addEventListener("mouseover",changeBG);

outlineOne.addEventListener("mouseout",changeBG);
outlineTwo.addEventListener("mouseout",changeBG);
body {
  background: #2F2F2F
}

.outlineOne,
.outlineTwo {
  display: inline-block;
  background: #2F2F2F;
  width: 100px;
  height: 100px;
  border: 2px solid black;
  margin: 20px 20px;
}

.outlineTwo {
  background: blue;
}

.outlineOne {
  background: red;
}

.outlineOne.active {
  background: blue;
}

.outlineTwo.active {
  background: red;
}
<div class='parent'>
  <div ></div>
  <div ></div>
</div>

CodePudding user response:

You have two options here:

  1. Have a div that wraps both outlineOne and outlineTwo and have a :hover selector on that, and then no JavaScript is needed (like your parent div in your example)
.parent:hover .outlineOne {
    background: blue;
}

.parent:hover .outlineTwo {
    background: red;
}
  1. Add a CSS class instead of adding :hover via JavaScript (so like .outlineOne.addedClass { background: blue; }, and listen for a mouseover event in JavaScript.

Technically you're not supposed to manually add a :hover to an element manually because it's a trusted event that should be user-activated.

  • Related