Dragging elements on a page

There are many plugins based on JavaScript, jQuery, and other libraries, which let users implement the dragging functionality. A user presses the mouse button on an element and moves it without releasing it. The element gets dragged along with the mouse pointer. The dragging stops once the mouse key is released.

After finishing this recipe, you will be able to implement a dragging feature for elements on your own. This recipe will show you how to make elements on a page draggable.

Getting ready

Get the jQuery library to use with this recipe.

How to do it...

  1. Create a new file in the chapter1 directory and name it as drag.html.
  2. Create some DIV elements and assign the dragMe class to customize their appearance. This class will also be used to attach event handlers to the DIV.
    <html>
      <head>
        <title>Dragging</title>
        <style type="text/css">
          .dragMe
          {
            background-color:#8FBC8F;
            border:1px solid black;
            color: #fff;
            float:left;
            font-family:verdana,arial;
            font-size:14px;
            font-weight:bold;
            height:100px;
            margin:10px;
            text-align:center;
            width:100px;
          }
        </style>
      </head>
      <body>
      
        <div class="dragMe">Drag Me</div>
        <div class="dragMe">Drag Me too</div>
      </body>
    </html>
    How to do it...
  3. In the jQuery code, declare variables that will hold the coordinates of DIV being dragged and the mouse pointer. Proceed to attach event handlers for mouse movement to elements with the dragMe class.

    We have attached two event handlers. The first is mousedown, which will execute while the mouse button is in a pressed state on the target DIV. This will get the current left and top coordinates of the DIV being dragged and the mouse pointer. Now bind the mousemove element to the current DIV. The dragElement function will be called when the mouse moves while its button is pressed.

    The function dragElement calculates new values for the top and left of the DIV by determining mouse movements and the DIV's current position and applies these properties to the DIV. This results in the movement of the DIV.

    Finally, bind the mouseup event to the document, which will stop the dragging after the mouse has been released.

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
      $(document).ready(function ()
      {
        var mousex = 0, mousey = 0;
        var divLeft, divTop;
        $('.dragMe').mousedown(function(e)
        {
          var offset = $(this).offset();
          divLeft = parseInt(offset.left,10);
          divTop = parseInt(offset.top,10);
          mousey = e.pageY;
          mousex = e.pageX;
          $(this).bind('mousemove',dragElement);
        });
    
        function dragElement(event)
        {
          var left = divLeft + (event.pageX - mousex);
          var top = divTop + (event.pageY - mousey);
          $(this).css(
          {
            'top' :  top + 'px',
            'left' : left + 'px',
            'position' : 'absolute'
          });
          return false;
        }
        $(document).mouseup(function()
        {
          $('.dragMe').unbind('mousemove');
        });
    
      });
    </script>
  4. Open the browser and run the drag.html file. Both DIV elements would be draggable by now. You will now be able to drag any of these DIV elements by pressing the mouse button over them and moving them around.

How it works...

Global variables mousex an d mousey will be used to store the left and top positions for the mouse pointer, and the div Left and divTop variable will store the left and top coordinates of the DIV. Then we attached two event handlers to the DIV with class dragMe. First is mousedown, which will execute when the mouse button is in a pressed state on the target DIV. In this function get the left and top positions of the DIV being dragged and store them in the divLeft and divTop variables respectively. Secondly, get the left and top values for the current mouse pointer position from the event object and save them in the mousex and mousey variables. Now when the button is pressed, bind the mousemove element to current DIV. The dragElement function will be called when the mouse pointer moves while its button is pressed.

The dragElement function now calculates the new left and top values for the DIV being dragged. To calculate the new value for left, take the left value for the DIV (divLeft) and add the difference in the mouse position to it. The difference in mouse position can be calculated by subtracting the previous left value for mouse pointer from the current left value. Similarly calculate the new value for top.

After both these values are calculated, use the css() method to apply these values to the DIV being dragged. Don't forget to set the position as absolute. Without absolute positioning the DIV will not be able to move.

See also

  • Capturing mouse movements in this chapter explains the method of retrieving mouse coordinates.
  • Binding and unbinding elements in this chapter teaches the basics of event handling.