Jeff
Jeff

Reputation: 12163

jQuery Delegate not binding like I want it to

Using jQuery 1.7

I'm having trouble binding a Click event to some dynamically loaded content.

I've looked around, tried .live, .delegate and .on, and I just can't get it to work.

This is my code:

$(".fileexplorer_folderdlg").delegate(".delete", "click", function () {
        console.log("Hello world!");
    });

The thing is, .fileexplorer_folderdlg is dynamically loaded. If I use .fileexplorer (not dynamically loaded), it works, but I have more elements with the .delete class that I do not wish to bind to (and neither element classes can be renamed or changed for various reasons).

I also tried using .fileexplorer_folderdlg .delete as the .delegate selector, didnt work either!

Of course I could just add another unique class to the elements I wish to bind to, but this really should work, right?

Upvotes: 0

Views: 65

Answers (1)

Alnitak
Alnitak

Reputation: 339816

I believe this would work:

$(document).on('click', '.delete', function() {
    if ($(this).closest('.fileexplorer_folderdlg').length) {
         console.log('hello, world!');
    }
});

or even just:

$(document).on('click', '.fileexplorer_folderdlg .delete', function() {
     console.log('hello, world!');
});

As you've found, you can't bind on .fileexplorer_folderdlg because it's dynamic. You therefore need to bind on some static element that will contain that element at some point in the future.

Instead, this binds on the document (but will unfortunately fire for every single click on the document thereafter).

EDIT by Jeff

Although the code above did not work, modifying it a bit did the job, although not the most desirable solution.

$(document).on('click', '.delete', function () {
        if($(this).closest(".fileexplorer") != null)
          console.log("Thanks for your help!");
    });

It works, but this event is fired for all other .delete classes, of which there are many. What I do not understand though, is why using .fileexplorer_folderdlg .delete did not work!

Upvotes: 2

Related Questions