Hello.

There is a js code with which you can move elements, but I don’t understand how to limit the area of ​​movement of an element, for example, within a specific block? Please tell me how to do this in pure javascript.

2 answers 2

Element.prototype.makeDraggable=function(){ var o=this o.onmousedown=function(e){ var offsetX=e.pageX-parseInt(o.style.left) var offsetY=e.pageY-parseInt(o.style.top) document.onmousemove=function(e) { o.style.left=Math.max(Math.min(e.pageX-offsetX,o.parentNode.clientWidth-o.clientWidth),0)+'px' o.style.top=Math.max(Math.min(e.pageY-offsetY,o.parentNode.clientHeight-o.clientHeight),0)+'px' } document.onmouseup = function(e) { document.onmousemove=o.onmouseup=null } } o.ondragstart = function(){return 0} } document.getElementById('object1').makeDraggable() 
 #parent{ position:absolute; top:10px; left:10px; background:yellow; width:300px; height:300px; } #object1{ width:100px; height:100px; position:absolute; background:green; } 
 <div id="parent"> <div id="object1" style="left:10px;top:10px;"></div> </div> 

    If you are using jQuery UI drag and drop, then here is an example from this manual .

    For binding to a specific container, the option with the value is responsible:

      containment: parent 
    • I do not use jQuery !!! I would like to understand on pure js how the restriction works. - sew810i9
    • What a cool :) what way d & d are you using? HTML5? Or just something samopisny with mousedown, etc.? In any case, when an element is outside the zone in which you can drag, simply do not update its coordinates. - zb '
    • would be cool, did not ask such questions! I have this code jsfiddle.net/acchtbcb but something on jsfiddle does not work, everything is fine in the browser. Or maybe you know, plugins like jquery draggable use the same principle, on reaching a certain place, the coordinates cease to be updated? - sew810i9
    • @ sew810i9, and what's the problem? You know, when an element moves in you, the boundaries of what moves and the field boundaries. What is the problem? Here is the jsfiddle.net/acchtbcb/1 demo to work on jsfiddle - zb '30
    • In general, everything is wrong with you there :) - zb '