I already saw this thread, but I think my case is a bit different.
This is an example class, whose constructor receives an element as parameter, that can be moved dragging it. But it does not stop being dragged on mouse up. If I good understood what I read in the other thread, I guess I have to assign the methods to variables, but I don't know how, as they take the event
parameter:
class Example
{
rect;
constructor(rect)
{
this.rect = rect;
this.rect.addEventListener('mousedown', event => this.onMouseDown(event));
}
onMouseDown(event)
{
document.addEventListener('mousemove', event => this.onMouseMove(event));
document.addEventListener('mouseup', event => this.onMouseUp(event));
}
onMouseMove(event)
{
this.rect.style.left = event.clientX;
this.rect.style.top = event.clientY;
}
onMouseUp(event)
{
document.removeEventListener('mousemove', this.onMouseMove);
document.removeEventListener('mouseup', this.onMouseUp);
}
}
document.addEventListener("DOMContentLoaded", function()
{
var rect = document.getElementById('rect');
var ex = new Example(rect);
});
#rect {
position: absolute;
border: 1px solid #ccc;
background-color: #DFD;
width: 100px;
height: 100px;
}
<html>
<head>
<meta charset="utf-8"/>
<title>Test</title>
</head>
<body>
<div id="rect"></div>
</body>
</html>
I don't know why the snippet here does not work, I copied the code from some files, that perfectly work.