Make a div element draggable using jQuery UI

Today in this tutorial we are going to learn how to make a div element draggable so that we can move it anywhere just by dragging using jQuery UI.

Here I am going to show you a simple example. In this example, we will use jQuery and a jQuery plugin that called jQuery UI. jQuery UI is so much popular these days that lots of popular websites are also using it.

jQuey UI Accordion With Demo Code

Live word counter from HTML textarea in JavaScript

Let’s start by including the jQuery and jQuery UI JavaScript file first:

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

After that create our HTML content inside the body tag. In our example we are going to use the HTML code that you can see below:

<div id="draggable">
  <h2>Drag me anywhere</h2>
</div>

Now the most important thing is to write jQuery UI code:

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

In the above piece of jQuery code, we have applied the draggable method to the div element with div ID “draggable”. As you can see that, it is only three lines of code. But soon, you will see that these few lines of code are so powerful.



Convert seconds to HH-MM-SS format in JavaScript

After that add some CSS to give it a better look:

#draggable {border: solid 2px #777; background: #ccc; cursor: move;}

You can see that we have set the cursor property move which you see on any website where draggable content uses.

Complete HTML code of draggable div element

Below is the complete HTML code that you can run on your browser:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Draggable - Default functionality</title>
  <style>
  #draggable { width: 150px; height: 150px; padding: 0.5em; }
  </style>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#draggable" ).draggable();
  } );
  </script>

  <style type="text/css">
  	#draggable {border: solid 2px #777; background: #ccc; cursor: move;}
  </style>

</head>
<body>
 
<div id="draggable">
  <h2>Drag me anywhere</h2>
</div>
 
 
</body>
</html>

Save the above code as an HTML file and give it any name that you prefer. After that, open it with your browser and you will see a div element with the text “Drag me anywhere”. You can drag it anywhere on the browser screen.

Retrieve the width of div element in JavaScript

I hope you liked this tutorial and you have understood. If there is any problem to understand then let me know. I would like to help you.

Leave a Reply

Your email address will not be published. Required fields are marked *