Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery late binding

i have a code that bind's on click action on page load, it is a link. When i clicking it, it send ajax request and replace content in some div with jquery append() function. This new content has a links and i need to bind some action for them, but i could't.. bind did't work i think, because jquery append doesn't update DOM tree. How could i get a late binding?

like image 287
andymcgregor Avatar asked Dec 14 '09 18:12

andymcgregor


People also ask

What is event binding in jQuery?

The jQuery bind() event is used to attach one or more event handlers for selected elements from a set of elements. It specifies a function to run when the event occurs. It is generally used together with other events of jQuery. Syntax: $(selector).

What is difference between on and bind in jQuery?

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 .

How do you bind click events?

The bind() is an inbuilt method in jQuery which is used to attach one or more event handlers for selected element and this method specifies a function to run when event occurs. event: This is an event type which is passed to the selected elements. data: This is the data which can be shown over the selected elements.


1 Answers

There are 3 functions that can do this:

  • $(selector).live(events, data, handler); - jQuery 1.3+ - version deprecated: 1.7, removed: 1.9 (reference)
  • $(document).delegate(selector, events, data, handler); - jQuery 1.4.3+ - As of jQuery 1.7, .delegate() has been superseded by the .on() method. (reference)
  • $(document).on(events, selector, data, handler); - jQuery 1.7+ - preferred (reference)

It's generally adviced to use on() and it's use is simple and probably preferred way.

  1. The first selector must exist when calling the function and may not be deleted or the event will be gone too (this can be document).
  2. The first parameter is the event (e.g. "click")
  3. The second parameter is the selector of which you want to bind the event on.
  4. Then finally you can add some custom data and a function to the event.

Here's some sample code:

// Make sure the DOM is ready
$(function() {
    // Bind the click event to the function
    $(document).on("click", "a.class", function(event) {
        // Put your code here.
    });
});
like image 93
Broxzier Avatar answered Sep 23 '22 13:09

Broxzier