Search code examples
javascriptonmouseoveronmouseout

onmouseover with javascript


I would like div a and div b to switch places when the mouse is over div b then switch back when mouse leaves div a. But its super glitchy and will switch even when mouse hasn't left div a. How do i get it to not run navMouseOut when mouse is still in div a, and why is it doing this. (please test code to see whats wrong)

document.getElementById("b").onmouseover = function() {
  navMouseOver()
};
document.getElementById("a").onmouseout = function() {
  navMouseOut()
};

function navMouseOver() {
  document.getElementById("a").style = ("top: 50%;");
  document.getElementById("b").style = ("top: 40%; ");
}

function navMouseOut() {
  document.getElementById("a").style = ("top: 40%;");
  document.getElementById("b").style = ("top: 50%;");
}
#a {
  position: fixed;
  top: 40%;
  left: 20%;
  background-color: red;
}

#b {
  position: fixed;
  top: 50%;
  left: 20%;
  background-color: lightblue;
}
<div id="a">
  <p>content a</p>
</div>
<div id="b">
  <p>content b...</p>
</div>


Solution

  • use onmouseenter instead of onmouseover

    document.getElementById("b").onmouseenter = function() {
    navMouseOver()
    };
    
    document.getElementById("a").onmouseout = function() {
    navMouseOut()
    };