Saturday, January 7, 2012

Attach a handler to an event for the elements in jQuery

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements.  

Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs.

  • .bind( eventType [, eventData], handler(eventObject) )

    eventTypeA string containing one or more DOM event types, such as "click" or "submit," or custom event names.
    eventDataA map of data that will be passed to the event handler.
    handler(eventObject)A function to execute each time the event is triggered.
  • version added: 1.4.3.bind( eventType [, eventData], preventBubble )

    eventTypeA string containing one or more DOM event types, such as "click" or "submit," or custom event names.
    eventDataA map of data that will be passed to the event handler.
    preventBubbleSetting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true.
  • version added: 1.4.bind( events )

    eventsA map of one or more DOM event types and functions to execute for them.

    The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.
    • .on( events [, selector] [, data], handler(eventObject) )

      eventsOne or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".
      selectorA selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.
      dataData to be passed to the handler in event.data when an event is triggered.
      handler(eventObject)A function to execute when the event is triggered. The valuefalse is also allowed as a shorthand for a function that simply does return false.
    • version added: 1.7.on( events-map [, selector] [, data] )

      events-mapA map in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).
      selectorA selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element.
      dataData to be passed to the handler in event.data when an event occurs.


No comments:

Post a Comment