1

Notice how if you onmousedownover the div, it turns from green to red. This is expected. But if you hold the mouse down and drag your cursor off and away from the div, then let go of your mouse, onmouseupwon't function because the cursor is no longer hovering over the div. The div remains red instead of returning to its initial green state.

Should I use onmousemove?

Any ideas how to solve this?

function mouseDown() {
    document.getElementById("test").style.backgroundColor = "red";
}

function mouseUp() {
    document.getElementById("test").style.backgroundColor = "green";
}
#test {
position: absolute;
height: 50px;
width: 100px;
background-color: green;
}
<div id="test" onmousedown="mouseDown()" onmouseup="mouseUp()">
</div>
logoologist
  • 205
  • 3
  • 15

1 Answers1

0

function mouseDown() {
    document.getElementById("test").style.backgroundColor = "red";
    document.getElementsByTagName("BODY").onmouseup = function() {mouseUp()};
}

function mouseUp() {
    document.getElementById("test").style.backgroundColor = "green";
}
#test {
position: absolute;
height: 50px;
width: 100px;
background-color: green;
}
<body>
<div id="test" onmousedown="mouseDown()" onmouseup="mouseUp()" 
onmouseout="mouseUp()">
</div>
</body>

you should use onmouseout() which allow you to change content when mouse leave element.

here is a link for more info

or you shoud use mouseup with parent element in our case div element with id=full look here

function mouseDown() {
          document.getElementById("test").style.backgroundColor = "red";
      }

      function mouseUp() {
          document.getElementById("test").style.backgroundColor = "green";
      }
  #test {
    position: absolute;
    height: 50px;
    width: 100px;
    background-color: green;
    }
  #full{
      width: 100%;
      height: 2000px;
      background: blue;
    }
<body>
<div id="full" onmouseup="mouseUp()" >

    <div id="test" onmousedown="mouseDown()" onmouseup="mouseUp()">
  </div>
  
</div>
  

</body>
manan5439
  • 898
  • 9
  • 24
  • you can also use onmouseup() with body element it is also work thank you for this question. i learn lots things. i hope you figure out. ;-) – manan5439 Jun 23 '18 at 18:08
  • Yes, this works. This is very thorough and complete answer, and beyond. Thank you! – logoologist Jun 23 '18 at 18:40