javascript – document.onmouseup = null

Question:

thumb.onmousedown = function(e) {

  ...

    document.onmouseup = function() {
        document.onmousemove = document.onmouseup = null;
      };

  ...

}

This is how the handler for Drag'n'Drop looks like. He works. But it's not clear to me how the " document.onmouseup = null " assignment works, in the handler function on this very document.onmouseup … In theory, this should be a one-time function – assigned null, it should cross out this function itself. But it doesn't work that way. The function continues to work. Why?

Answer:

thumb.onmousedown , document.onmouseup events are hung on different elements, the approximate logic is as follows:

pressed the LMB on the element, added an eventhandler to the document to track the coordinates of document.onmousemove , well, to know where we are moving the current element.

if they released the LMC, then the Drag'n'Drop process is completed, the element is in the place where the LMC was released, and event handlers on the document are no longer needed, so we delete them ( document.onmousemove = document.onmouseup = null; ).

When you press the LMB on the next element, we simply repeat the above steps.

Scroll to Top