Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery drag image

i want to make a draggable image in jquery. first of all my experience with jquery is 0. having said that let me describe what i want to achieve. i have fixed width/height div. and the image contained inside the div is large in size. so i want the image to be draggable inside that div so that the user can see the entire image.

can someone help. pls be a little elaborate about the procedure considering my jquery fluency.

like image 322
amit Avatar asked Jun 19 '09 20:06

amit


2 Answers

You can use the following;

$(function() {
  $("#draggable").draggable();
});
.container {
  margin-top: 50px;
  cursor: move;
}

#screen {
  overflow: hidden;
  width: 200px;
  height: 200px;
  clear: both;
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<div class="container">
  <div id="screen">
    <img src="https://picsum.photos/200/200" class="drag-image" id="draggable" />
  </div>
</div>
like image 55
Shadi Almosri Avatar answered Sep 19 '22 06:09

Shadi Almosri


You want the jQuery Draggable UI tool. The code for this, as with all jQuery, is very simple:

$(document).ready(function(){
  $("#draggable").draggable();
});

Will create a draggable object from a standard html tag (the IMG in your case). And for limiting it's mobility to a specific region, you would look into its containment option.

Update: "What is '#draggable' and 'ready'"?

  1. '#draggable' represents the element that you want to be able to drag. The hash (#) symbol represents an ID. When you add your image tags, may give give it an id like the following:

    <img src="myimage.jpg" id="draggable" />

    That will make the javascript above make your image draggable, because it has the '#draggable' id that the jQuery is looking for.
  2. '.ready()' is the method that is automagically raised by your browser once the page is finished loading. Developers are encouraged by the jQuery group to place all jQuery code within this method to ensure all of the elements on the page are completely loaded prior to any jQuery code attempts to manipulate them.
like image 34
Sampson Avatar answered Sep 22 '22 06:09

Sampson