Niyanta Prasad
Niyanta Prasad

Reputation: 1

Javascript: mouseover function not working for div

The following is the code I have written:

window.onload = function() {
  var test = document.getElementsByClassName("experiment");
  for (var i = 0; i < test.length; i++) {
    test[i].addEventListener("mouseover", function(event) {
      console.log('its working');
      event.target.style.color = "orange";
    }, false);
  }
};
body {
  background-color: #aaa;
}

.parent-experiment {
  width: 500px;
  height: 500px;
  background-color: yellow;
  display: flex;
  justify-content: space-around;
  perspective: 500px;
}

.experiment {
  width: 250px;
  height: 250px;
  margin-top: 100px;
  background-color: blue;
  transform: rotateY(45deg);
}
<div class="parent-experiment">
  <div class="experiment"></div>
</div>

The functioning I want is when I hover the mouse over the inner div element its color should change to orange. But it's not working at all.Moreover, I want to do the entire functioning using javascript only.

Upvotes: 0

Views: 283

Answers (1)

Renzo Calla
Renzo Calla

Reputation: 7696

Correct me If I am wrong but I think you are trying to change background color property and not color property.. like the example...

On the other hand you could achieve this using only css with the :hover selector..

window.onload=function(){
var test=document.getElementsByClassName("experiment");
for(var i=0;i<test.length;i++){
    test[i].addEventListener("mouseover",function(event){
        console.log('its working');
         event.target.style.backgroundColor="orange";
    },false);
    test[i].addEventListener("mouseout",function(event){
        console.log('its working');
         event.target.style.backgroundColor="blue";
    },false);
}
};
body{
background-color: #aaa;
}
.parent-experiment{
width: 500px;
height: 500px;
background-color: yellow;
display: flex;
justify-content: space-around;
perspective: 500px;
}
.experiment{
width: 250px;
height: 250px;
margin-top: 100px;
background-color: blue;
transform: rotateY(45deg);
}
    <div class="parent-experiment">
        <div class="experiment"></div>
    </div>

Upvotes: 2

Related Questions