How to Drag / Pan an Image in a Container div using jQuery?

CSSjQueryWeb DevelopmentFront End Technology

With the help of events like mousedown, mouseup and mousemove, we can translate the image thereby creating a drag effect.

The following example portrays how an image can be moved using jQuery.

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
#parent{
   position: absolute;
   margin: 20px;
   width: 200px;
   height: 200px;
   border-radius: 25px;
   background-color: khaki;
}
#mover {
   position: relative;
   margin: 10px;
}
</style>
</head>
<body>
<div id=parent>
<img id="mover" src="https://images.unsplash.com/photo-1613333238609-
ef9218f3ddbd?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=100&ixlib=rb1.2.1&q=80&w=100" />
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
let ele = {startPositionX:0,startPositionY:0};
let disp = {x:0,y:0};
$('#parent').on("mousedown",function(e){
   let container = $(this);
   ele.startPositionX=e.pageX-disp.x;
   ele.startPositionY=e.pageY-disp.y;
   $(document).on("mousemove",function(e){
      disp.x=e.pageX-ele.startPositionX;
      disp.y=e.pageY-ele.startPositionY;
      $('#mover').css('transform','scale('+1.0+') translate('+disp.x+'px, '+disp.y+'px)');
   });
});
$(document).on("mouseup",function(){
   $(this).off("mousemove");
});
</script>
</body>
</html>

Output

This will produce the following result −

Drag

raja
Published on 13-Mar-2021 12:39:34
Advertisements