In the example below, the ball is -as expected- being dropped when the mouseup event occurs:
ball.ondragstart = function() {
return false;
};
ball.onmousedown = function(e) {
let ballRect = ball.getBoundingClientRect();
let shiftX = e.pageX - ballRect.left;
let shiftY = e.pageY - ballRect.top;
ball.style.position = "absolute";
ball.style.zIndex = 1000;
document.body.append(ball);
function moveball(x, y) {
ball.style.left = x + "px";
ball.style.top = y + "px";
}
moveball(e.pageX - shiftX, e.pageY - shiftY);
document.addEventListener('mouseup', () => {
document.removeEventListener('mousemove', onmousemove);
ball.onmouseup = null;
});
function onmousemove(e) {
moveball(e.pageX - shiftX, e.pageY - shiftY);
}
document.addEventListener('mousemove', onmousemove);
}
#court {
width: 400px;
height: 200px;
margin: 0 auto;
position: relative;
background-color: lightgreen;
border: 1px solid green;
border-radius: 10px;
}
#ball {
width: 40px;
height: 40px;
border-radius: 100%;
background-color: red;
position: absolute;
}
<div id="court">
<div id="ball">
<div>
</div>
but when the onmousemove
function definition is put inside the addEventListener
function, the ball is not dropped when the mouseup event occurs (against the expectation) :
document.addEventListener('mousemove', function onmousemove(e) {
moveball(e.pageX - shiftX, e.pageY - shiftY);
});
How does defining the named event handler inside or outside the addEventListener
make a difference?