Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
PHP jQuery Cookbook

You're reading from   PHP jQuery Cookbook jQuery and PHP are the dynamic duo that will allow you to build powerful web applications. This Cookbook is the easy way in with over 60 recipes covering everything from the basics to creating plugins and integrating databases.

Arrow left icon
Product type Paperback
Published in Dec 2010
Publisher Packt
ISBN-13 9781849512749
Length 332 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Vijay Joshi Vijay Joshi
Author Profile Icon Vijay Joshi
Vijay Joshi
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

PHP jQuery Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. Handling Events with jQuery FREE CHAPTER 2. Combining PHP and jQuery 3. Working with XML Documents 4. Working with JSON 5. Working with Forms 6. Adding Visual Effects to Forms 7. Creating Cool Navigation Menus 8. Data Binding with PHP and jQuery 9. Enhancing your Site with PHP and jQuery Firebug Index

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

You have been reading a chapter from
PHP jQuery Cookbook
Published in: Dec 2010
Publisher: Packt
ISBN-13: 9781849512749
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image