Skip to content Skip to sidebar Skip to footer

Move Element With Mouse Starts To Snap Up And Down

I am trying to make a drag on y axis functionality using mousedown, mousemove events. The formula is as follows: var position = e.clientY - getOrigin(myDiv).top; myDiv.style.transf

Solution 1:

Because I couldn't exactly figure out what was causing the problem in OPs question (for an unknown reason box.top was returning 2 different values alternately on each pixel movement in OPs script), I've written a different script that works perfectly fine:

//document.addEventListener('DOMContentLoaded', function(){var myDiv = document.getElementById('myDiv');

	myDiv.addEventListener('mousedown', handleMouseDown);
	window.addEventListener('mouseup', handleMouseUp);

	functionhandleMouseDown(e) {
		window.addEventListener('mousemove', mouseMove.start(this, 'body',e));
	}

	functionhandleMouseUp(e) {
		window.removeEventListener('mousemove', mouseMove.stop('body'));
	}

	var mouseMove = function(){
		return {
			move: function(elm, posY){
				elm.style.top = posY + "px";
			},
			start: function(elm, container, e){
				e = e || window.event;
				var posY = e.clientY,
					elmTop = elm.style.top,
					elmHeight = parseInt(elm.style.height),
					conHeight = parseInt(document.getElementById(container).style.height);
				elmTop = elmTop.replace('px','');
				var diffY = posY - elmTop;

				document.onmousemove = function(e){
					e = e || window.event;
					var posY = e.clientY,
						Y = posY - diffY;
					if (Y < 0) Y = 0;
					if (Y + elmHeight > conHeight) Y = conHeight - elmHeight;
					mouseMove.move(elm,Y);
				}
			},
			stop : function(container){
				var a = document.createElement('script');
				document.onmousemove = function(){}
			},
		}
	}();
//});
#body {
	margin-top: 50px;
	position: absolute;
}
#myDiv {
	position: absolute;
	background-color: orange;
	width: 200px;
	height: 100px;
}
<divid="body"><divid="myDiv"></div></div>

Post a Comment for "Move Element With Mouse Starts To Snap Up And Down"