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

Binding and unbinding elements


This recipe will demonstrate how you can attach events to DOM elements using the .bind() method and how to remove them using the .unbind() method.

Getting ready

Get a latest copy of the jQuery library to use with this recipe.

How to do it...

  1. Create a new file, in a directory named chapter1, and name it as binding.html.

  2. Write the HTML markup to create some HTML elements. Create an unordered list with the names of some countries. After that, create a select box containing names of continents as options. Finally, create a button that will be used to remove the event handler from the select box.

    <html>
      <head>
        <title>Binding Elements</title>
        <style type="text/css">
          ul { background-color:#DCDCDC; list-style:none; margin:0pt; padding:0pt; width:250px;}
          li { cursor:pointer; margin:10px 0px;}
        </style>
      </head>
      <body>
        <ul>
          <li>India</li>
          <li>USA</li>
          <li>UK</li>
          <li>France</li>
        </ul>
    
        <select> 
          <option value="Africa">Africa</option>
          <option value="Antarctica">Antarctica</option>
          <option value="Asia">Asia</option>
          <option value="Australia">Australia</option>
          <option value="Europe">Europe</option>
          <option value="North America">North America</option>
          <option value="South America">South America</option>
        </select>
    
        <input type="button" value="Unbind select box"/>
      </body>
    </html>
  3. It's time to add some jQuery magic. Attach a click event handler to list items using the .bind() method, which will set the background color of the clicked item to red. Attach the change event handler to the select box, which will display the value of the selected item. Finally, add a click handler to the button. Clicking on the button will remove the event handler from the select box.

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
      $(document).ready(function ()
      {
        $('input:text').bind(
        {
          focus: function()
          {
          $(this).val('');
          },
          blur: function()
          {
            $(this).val('Enter some text');
          }
        });
    
        $('li').bind('click', function()
        {
          $(this).css('background-color', 'red');
        });
        
        $('select').bind('change', function()
        {
          alert('You selected: '+ $(this).val());
        });
        
        $('input:button').bind('click', function()
        {
          $('select').unbind('change');
        });
      });
    </script>
  4. Run the binding.html file in your browser and click on some items in the list. The background color of each item clicked upon will change to red. Now select some value from the select box and you will see an alert box that displays the selected value as shown in the following screenshot:

    Clicking on the Unbind select box button will remove the change event handler here and the selection of a value from the combo box will now do nothing.

How it works...

jQuery uses the .bind() method to attach standard JavaScript events to elements. .bind() takes two parameters. The first parameter is the event type to attach. It is passed in string format, and event types such as click, change, keyup, keydown, focus, blur, and so on can be passed to it. The second parameter is the callback function, which will be executed when the event fires.

In the previous code, we used .bind() for the list items to attach a click handler. In the callback function, $(this) refers to the element that fired the event. We then use the .css() method to change the background color of the element that is clicked upon.

Similarly, we attached the change event to the select box using the .bind() method. The callback function will be called each time the value of the select box is changed.

The input button has also been attached to a click event. Clicking on the button calls the .unbind() method. This method accepts an event type name and removes that event from the element. Our example code will remove the change event from the select box. Therefore, changing the value of the select box will not display any further alerts.

There's more...

Binding multiple events

Multiple events can also be attached using the .bind() method. The following code attaches two events focus and blur to a textbox. Focusing on a textbox will empty it, whereas taking the focus away from it will put some text in it.

$('input:text').bind(
{
  focus: function() 
  {
    $(this).val('');
  },
  blur: function() 
  {
    $(this).val('Enter some text');
  }
});

Tip

Note that this functionality was added in Version 1.4 of jQuery. So, make sure that you have the correct version before running this code.

Shortcut method for binding

Instead of using .bind(), events can be attached directly by using shortcut event names to elements. For example, $(element).click(function() { }); can be written instead of using $(element).bind('click', function() { });.

Other events can be attached similarly.

Triggering events

Events can also be triggered from the code. For this we have to pass the event name without any parameter.

$(element1).click(function()
{
  $(element2).keydown();
});

The above code will execute the keydown event of element2 when element1 is clicked.

Common event types

Here is a list of some common events that can be passed to the bind() and unbind() methods.

blur

focus

load

unload

scroll

click

dblclick

mousedown

mouseup

mousemove

mouseover

mouseout

change

select

submit

keydown

keypress

keyup

Unbinding all events from an element

If no parameter is passed to the .unbind() method, it will remove all event handlers associated with the specified element.

$(element).unbind();
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