Home > Mobile >  one element to change color while hovering another one
one element to change color while hovering another one

Time:10-20

This is what I tried so far. As they are in different divs and in no parent, sibling or child relation with each other, by my understanding CSS is no valid option.

 <script>
var circleOne = document.querySelector('.first_circle');
var adressOne = document.querySelector('.first_adress');

if (circleOne.matches(':hover')) {
    adressOne.style.color='green'; 
} else {
    adressOne.style.color='black';
}

</script>

CodePudding user response:

You can use a combination of onmouseenter and onmouseleave

var circleOne = document.querySelector('.first_circle');
var adressOne = document.querySelector('.first_adress');

circleOne.onmouseenter = () => adressOne.style.color='green';
circleOne.onmouseleave = () => adressOne.style.color='black';
<div class="first_circle">First Circle</div>
<div class="first_adress">First Address</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You should use mouseenter, mouseleave event listeners for this task

const firstEl = document.getElementById('first');
const secondEl = document.getElementById('second');

firstEl.addEventListener('mouseenter', () => secondEl.style.background = 'black');
firstEl.addEventListener('mouseleave', () => secondEl.style.background = 'transparent');

secondEl.addEventListener('mouseenter', () => firstEl.style.background = 'blue');
secondEl.addEventListener('mouseleave', () => firstEl.style.background = 'transparent');
#first, #second {
  display: inline-block;
  width: 100px;
  height: 100px;
  border: 1px solid #e0e0e0;
}
<div id="first"></div>
<div id="second"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

YOU CAN TRY mouseover event listener in one and apply condition to make change on other element.

  • Related