javascript - How to fix the offset x position of this div on click? -
using vanilla javascript work on panel drag function.
right stuck @ how correctly offset x position of dragger div not snap right of cursor.
how correct x
offset below?
http://jsfiddle.net/leongaban/rrcl63y9/41/
window.onload = addlisteners(); var xposition = 0; function addlisteners() { document.getelementbyid('drag-container').addeventlistener("click", getclickposition, false); document.getelementbyid('dragger').addeventlistener('mousedown', mousedown, false); window.addeventlistener('mouseup', mouseup, false); } function getclickposition(e) { xposition = e.clientx; console.log(xposition); } function mouseup() { window.removeeventlistener('mousemove', divmove, true); } function mousedown(e) { window.addeventlistener('mousemove', divmove, true); } function divmove(e) { var max = 443; var x = event.clientx; if (x > 100 && x < max) { var div = document.getelementbyid('dragger'); div.style.position = 'absolute'; div.x = xposition; div.style.left = e.clientx + 'px'; } //console.log(x); }
you can knowing width of draggable element , adjusting offset -(width/2);
function divmove(e) { var max = 443; var x = event.clientx; var div = document.getelementbyid('dragger'); var offset = div.offsetwidth/2; if (x > (100 + offset) && x < (max+offset)) { div.style.position = 'absolute'; div.x = xposition; div.style.left = (e.clientx - offset) + 'px'; } //console.log(x); }
here updated fiddle