Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get event listeners to recognize new document elements?

Tags:

jquery

How can I get jQuery event listeners to listen to elements loaded through ajax calls?

I load comments into my document via ajax. Each comment has an ajax delete button. For comments that were loaded originally with the document, my function works fine.

But any newly created comments, or comments retrieved through ajax, the event lister does not pick-up on them.

<a class="comment-delete" href="/comments/delete/124">delete</a>

$(".comment-delete").click(function(e) {
    e.preventDefault();

    var $link = $(this),
        url = $link.attr('href');

        $.ajax(url, {
            dataType: 'json',
            beforeSend: function() {
            },
            error: function() {
            },
            success: function(data) {
                if (data.success) {
                    $($link).parent().parent().hide();
                }
            }
        });
});
like image 201
Mohamad Avatar asked Jun 04 '11 15:06

Mohamad


People also ask

Can you add event listener to document?

The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.

Why are my event listeners not working?

If your event listener not working is dependent on some logic, whether it's about which element it'll listen on or if it's registered at all, the first step is to check that the listener is indeed added to the element. Using a breakpoint in the developer tools , a logpoint or console.

How do you get all event listeners on an element?

Right-click on the search icon button and choose “inspect” to open the Chrome developer tools. Once the dev tools are open, switch to the “Event Listeners” tab and you will see all the event listeners bound to the element. You can expand any event listener by clicking the right-pointing arrowhead.

How do I know if an event listener is working?

To check if an element has event listener on it with JavaScript, we can call the getEventListeners function in the Chrome developer console. getEventListeners(document. querySelector("your-element-selector")); in the Chrome developer console to select the element we want to check with querySelector .


2 Answers

You're looking for live http://api.jquery.com/live/

like image 40
James Montagne Avatar answered Oct 10 '22 11:10

James Montagne


Updated Answer

Today, the appropriate way to do this is to use the on method with an additional selector. For instance, if we wanted to listen for any click on images we could do this:

$("img").on("click", function () {
    alert( "You clicked on " + this.src );
});

This will not work for any image elements added to the DOM after this code was ran. Instead, we need to use event delegation, meaning we handle the event further up the DOM in its bubbling phase:

$(document).on("click", "img", function () {
    alert( "You clicked on " + this.src );
});

In this case, we handle the event at the document level, but only if the element it proceeded from matches our second "img" selector. So any image, whether it was on the page initially, or dynamically loaded in at a later time, will now be handled.

Original Answer (Written in 2011)

$.live() and $.delegate() are the two methods you should be looking to. The first will listen to the document for any new elements matching your selector, and the second will provide a more granular scope for where it ought to be listening.

$(".comment-delete").live("click", function(){
  // handle delete logic
});

Or, the more specific:

$(".comments").delegate(".comment-delete", "click", function(){
  // handle delete logic
});
like image 61
Sampson Avatar answered Oct 10 '22 11:10

Sampson