Moving DIV Element using jQuery

by Vincy. Last modified on July 6th, 2023.

In this tutorial, we will learn how to move a DIV element to the top, right, bottom, and left directions using jQuery. In previous older tutorials, we have seen jQuery DIV drag-and-drop animation.

We have icons to trigger the jQuery function to move the DIV element to the corresponding direction. In this example, we are using jQuery animate() function to move DIV by changing its position and margin using CSS.

View Demo

Movable DIV Element

This HTML code contains the movable DIV element and the top, right, bottom, and left icons to trigger the jQuery move event.

jquery-move

<div id="movable">
	<div class="move-icon">
	<div><img src="up.jpg" class="arrow" onClick="moveDIV('up');" /></div>
	<div><img src="left.jpg" class="arrow"  onClick="moveDIV('left');" /><img class="arrow"  src="right.jpg" onClick="moveDIV('right');" /></div>
	<div><img src="down.jpg" class="arrow"  onClick="moveDIV('down');" /></div>
	</div>
</div>

jQuery Move Animation with DIV

This jQuery function is called when the user clicks the HTML direction icons. We are changing the CSS position and margin property.

function moveDIV(action) {
	switch(action) {
		case "up":
			$('#movable').animate({'marginTop' : "-=15px"});
		break;
		case "left":
			$('#movable').animate({'marginLeft' : "-=15px"});
		break;
		case "right":
			$('#movable').animate({'marginLeft' : "+=15px"});
		break;
		case "down":
			$('#movable').animate({'marginTop' : "+=15px"});
		break;
	}
}

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

↑ Back to Top

Share this page