CodingBison

jQuery enables us to add or remove an event handler using the .on() or the .off() methods, respectively. As of jQuery 1.7, .on() and off() methods are the preferred methods for adding/deleting event registrations.

So, right off the bat, let us provide signature of these two methods.

 .on(eventNames, optionalFilter, optionalData, eventHandlerFunction); [Added in 1.7]
 .on(eventNames, optionalFilter, optionalData);                       [Added in 1.7]

 .off(eventNames, optionalFilter, optionalEventHandlerFunction);      [Added in 1.7]
 .off(eventNames, optionalFilter);                                    [Added in 1.7]

The eventNames argument is the name of one or more events that need to be attached with the object that invokes these methods. The optionalFilter is the selection filter that will enable the events to be attached only to the filtered descendants of the element that invokes these methods -- the event will be triggered only when the event occurs on the filtered descendants. For example, '$("body").on("click", "<p>", handlerFunctionFoo)' would mean that that the click event is attached to only the "<p>" elements. Once the click event occurs on any of the <p> elements, it will trigger the handlerFunctionFoo() function.

For both versions of .on(), passing selection filter and data is optional. Similarly, for versions of .off(), passing selector and handler function is optional.

What makes .on() different is that it also accepts "optionalData" as an argument that can be passed to the callback handler. This argument is passed as "data" property of the argument of the callback handler.

With that, let us see an example that demonstrates the .on() method. The example is based on a simple HTML form; the form has two elements. The first element is a text input field that accepts input from the user. The second element is a submit element that the user can click once she has provided all the information.

In terms of events, the example uses the .on() method to bind two types of events: "ready" event for the document and the "click" event for the submit button. The "click" event is triggered when the user clicks the submit button of the form. To retrieve the submit button using its CSS id, we can use '$("#idInputSubmit")'. Once we have the element, we use the .on() method to add a handle for the "click" event. Here is the example:

 <!doctype html>
 <html>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
 </script>

 <body>
 <form id="formSearch"> Name of the Nobel Laureate:<br>
     <input type="text" id="idInputText" value=""><br>
     <input type="submit" id="idInputSubmit" value="Search">
 </form>

 <script type="text/javascript">
 $(document).on("ready", function () {
     $("#idInputSubmit").on("click", dataText, function (event) {
         // Get the passed object. 
         var passedData = event.data;
         // Get value from the Name text field. 
         alert(passedData.text + "You entered: " + $("#idInputText").val());
     });
 });
 </script>
 </body>
 </html>

Let us now load the above page. If we were to enter some input and click the search button, we would see the following output:



Figure: Registering Events Using the .on() Method

The .on() method applies only to those events that are present on the page when we invoke it. If an element is added later, then .on() would not take that into account. Hence, if we add a new element, then we would need to insert in into the event list. Accordingly, it is a good idea to wait for the HTML DOM (document to be ready) to be ready before adding any events. Yet another way to handle addition of future elements is to use delegated methods that handle events for descendant elements. Thus, even if descendants are added/deleted, these methods would still work.

Earlier Variants: .bind(), .delegate(), and .live()

As of jQuery 1.7, the .on()/.off() methods are the preferred methods for registering/deregistering events. However, the earlier versions of jQuery had several other methods to do the same: .bind(), .live(), and .delegate() methods. We discuss them merely for the sake of completeness. Unless we are dealing with backward compatibility issues, we should stick with .on() and .off() methods.

Here is the status on these methods. The .live() method is deprecated as of jQuery 1.7 and has been removed from jQuery 1.9. Starting with jQuery 1.7, the preferred method is the .on() method instead of .delegate() and .bind() methods. For earlier versions, where .on() is not available, using .delegate() and .bind() is acceptable. It is worth noting that one of the main differences between .live() and .bind() is that the .bind() method works only for those elements that exist on the page and not on elements that will be created in the future. The .live() method works even on elements that get added later.

For the sake of completeness, we provide below a quick overview of two of these methods: .bind() and .delegate(). Since the .live() method is deprecated, we skip its discussion here.

 .bind(eventNames, optionalData, eventHandlerFunction);              [Added in 1.0]
 .bind(eventNames, optionalData, booleanPreventBubble);              [Added in 1.4.3]
 .bind(eventObjects);                                                [Added in 1.4]

 .delegate(filter, eventNames, optionalData, eventHandlerFunction);  [Added in 1.4.2]
 .delegate(filter, eventNames, optionalData);                        [Added in 1.4.2]
 .delegate(filter, eventObjects);                                    [Added in 1.4.3]

For the above methods, the eventNames is a string that consists of one or more event names. The optionalData field is same as that of the .on() method. The boolPreventBubble is a boolean parameter and when set to True (1), it stops the triggered event from bubbling up. The filter is the selection filter that will enable the events to be attached only to the filtered descendants of the element that invokes these methods. Thus, '$("body").delegate(""<p>", "click", handlerFunctionFoo)' would mean that that the click event is attached to the "<p>" elements of the document body.

Let us now look at their counterparts for removing previously attached events. We begin with the .unbind() method.

 .unbind(eventNames, optionalEventHandlerFunction); [Added in 1.0]
 .unbind(eventNames, false);                        [Added in 1.4.3]
 .unbind(eventObject);                              [Added in 1.0]
 .unbind();                                         [Added in 1.0]

The first form of .unbind() takes an event name (like "click" or "focus") and the handler function -- once run, this event handler function would not be invoked any more. The second variant, .unbind(eventNames, false), unbinds a previous bind call that was made using .bind(eventNames, false). We can see the "false" as a trivial function that returns false. The third version, .unbind(eventObject), takes event objects as argument and unbinds them. The last variant of .unbind() does not take any arguments -- when called, it removes all attached events.

Let us wrap-up by quickly looking at the .undelegate() method.

 .undelegate(filter, eventNames, eventHandlerFunction); [Added in 1.4.2]
 .undelegate(filter, eventNames);                       [Added in 1.4.2]
 .undelegate(filter, eventObjects);                    [Added in 1.4.3]
 .undelegate(namespace);                               [Added in 1.6]
 .undelegate();                                        [Added in 1.4.2]

For this method, the filter is the selection filter for filtering event results. The eventNames is the name of the event (like "click" or "focus") and we can pass one or more events. One of the variants also accepts a set of event objects. The variant, .undelegate(namespace), will delete all the registered events within the passed namespace. By comparison, the .undelegate() variant is more extreme -- it will remove all the registered events with .delegate() method!





comments powered by Disqus