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:
    How to do it...

    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.

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();