view raw
Anonymous Anonymous - 6 months ago 31
Javascript Question

How to make mouseup fire anyehere?

I have a drag and drop script that is relatively functional. However, I want to be able to trigger mouseup anywhere on the screen. Is there a way to trigger mouseup outside of the window, or outside of the current element? I know this is possible and I've seen other questions like this. I wanted to find a way in vanilla Javascript to detect mouseups like this.

document.onmousemove = mouseCoords;

var x = 0;
var y = 0;
var cl1= false;
var divid;
var offs1;
var offs2;
var topPos;
var leftPos;

function mouseCoords(e) {
x = e.x
y = e.y
if(cl1 === true){
document.getElementById(divid) = topPos + (y-offs1) + 'px';
document.getElementById(divid).style.left = leftPos + (x-offs2) + 'px';
var drag = function(i, cas) {
divid= i
case 1:
var rect = document.getElementById(divid).getBoundingClientRect();
leftPos = rect.left;
topPos =;
offs1 = y;
offs2 = x;
cl1= true;
case 0:
offs1 = 0;
offs2 = 0;
cl1= false;

width: 100px; z-index: 20; height: 50px; background-color: blue; position: fixed; user-select: none; -webkit-user-select: none;
width: 200px; height: 100px; background-color: red; position: fixed;

<div id="block">mouseup doesn't trigger over me!</div>
<div id="1" class="drag" onmousedown="drag(1, 1)" onmouseup="drag(1, 0)"></div>



document.addEventListener("mouseup", drag(null, 0)); for mouseup,

and this code for mousedown.

document.addEventListener("mousedown", drag(null, 1));

Basically, document.addEventListener works for the whole window. "mouseup" tells the script that the event is a mouseup, and the final bit is the function to be executed (drag(1, 0))