Moving DIV Element using jQuery

by Vincy. Last modified on July 12th, 2022.

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

We are having icons to trigger 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 DemoDownload

Movable DIV Element

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


<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>

jQuery Move Animation with DIV

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

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

View DemoDownload

↑ Back to Top

Share this page