javascriptonmousedownonmouseup

How to cause "onmouseup" to function if the user drags the cursor off the div


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>


Solution

  • 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>