There are several div blocks of the same size, located side by side in 2x1, 2x2, 4x4, 5x4 schemes and the like (many surveillance cameras). It is necessary, having captured one block, drag it to another and onmouseup to replace the cameras. But you can not reach the block and release it somewhere at the intersection of other blocks, and then you need to determine the intersection with which of the blocks that the user released the dragged block, the largest, to make a swap of these cameras.

Please tell onmouseup how you can track the position of the dragged element at the moment of onmouseup in relation to other elements. Is the analysis of screen coordinates of elements the only method, or are there simpler and more concise solutions (on pure JS)?

    1 answer 1

    There are three ways.

    1. Use mouse events, in particular onmouseup . Read more to learn.javasript

    2. Use native Drag'n'Drop , which appeared in HTML5. More on Habré

    3. Use ready-made library. For example, a plugin for jQuery draggable . Or an independent dragula library.

    A small example using mouse events:

     var ball = document.getElementById('ball'); function getCoords(elem) { // (1) var box = elem.getBoundingClientRect(); var body = document.body; var docEl = document.documentElement; // (2) var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop; var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft; // (3) var clientTop = docEl.clientTop || body.clientTop || 0; var clientLeft = docEl.clientLeft || body.clientLeft || 0; // (4) var top = box.top + scrollTop - clientTop; var left = box.left + scrollLeft - clientLeft; // (5) return { top: Math.round(top), left: Math.round(left) }; } ball.onmousedown = function(e) { var coords = getCoords(ball); var shiftX = e.pageX - coords.left; var shiftY = e.pageY - coords.top; ball.style.position = 'absolute'; document.body.appendChild(ball); moveAt(e); ball.style.zIndex = 1000; // над другими элементами function moveAt(e) { ball.style.left = e.pageX - shiftX + 'px'; ball.style.top = e.pageY - shiftY + 'px'; } document.onmousemove = function(e) { moveAt(e); }; ball.onmouseup = function() { document.onmousemove = null; ball.onmouseup = null; }; } ball.ondragstart = function() { return false; }; 
     #ball { background-color: red; width: 50px; height: 50px; } 
     <div id="ball"></div>