Book Image

PHP jQuery Cookbook

By : Vijay Joshi
Book Image

PHP jQuery Cookbook

By: Vijay Joshi

Overview of this book

As web technology evolves, the gap between desktop applications and web applications continues to vanish. And what better way to bridge that gap, for your own website, than using the best two open source technologies in the market: PHP and jQuery. The power-combo of these two is leading the way in revolutionizing the RIA world. Although they are easy to integrate, finding or figuring out how to do what you want to do is rather arduous.The PHP jQuery Cookbook will be your handy guide with walkthroughs of common integration tasks and problems that will help you master the possibilities available using the PHP and jQuery combo. You will learn quick solutions to necessary tasks to integrate the power of two of the best known and most widely used web technologies of today – PHP on the server side and jQuery on the client side. Glide through the basics and move to advanced topics to create dynamic and interactive web applications with this book in hand.This book covers a wide array of technical aspects of creating an interactive website. Apart from basics of PHP and jQuery, you will go through advanced topics like creating plugins, validating controls, and useful utilities that you will be able to use as stand-alone tools. AJAX, the key technique of browser-server communication is covered in detail. You will also learn to use JSON, which is becoming preferred as a mode of data interchange over XML, both in web applications and web services.The book also covers database interaction, which is an important part of any dynamic web application. You will also gain expertise in debugging JavaScript with the help of useful tools that will save you hours of tedious manual debugging.Most importantly, by using jQuery and PHP together, you will be able to develop applications that are compatible with all major browsers, with no need to write code targeted at specific browsers!
Table of Contents (17 chapters)
PHP jQuery Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
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.