lima
lima

Reputation: 113

jQuery.on() not working when used according to documentation?

I've been over all the documentation for live() (which is now gone from jQuery), delegate(), and on(). After eight hours of hitting myself over the head with this problem, I cannot figure out how to fix it. I want to add an anonymous function to a bunch of links that are created from data brought in via AJAJ. I've tried the following code:

$("#more_items_outer").on(
            'click',
            '.show_more',
            function(a){
                var target = a.parentElement;
                if (target.is(":visible")){
                    target.hide("slow");
                } else {
                    target.show();
                }
            }
        );

This code works fine when I run it in the JS console on my development browser after the page has loaded. But this code does nothing for these links if it runs before the actual links are created. As I understand it (and as multiple sources, including the official jQuery docs, describe it), the on() function as I've used it in the above code should make things so that any element of class "show_more" that is created as a descendant of any element with the id "more_items_outer" will execute the anonymous function when it is clicked. This should be true even if the new element's creation post-dates the execution of this code. That's not happening on my dev system here, and I'm all ears as to why this might be so. I'm running jQuery 1.9.1, if that helps.

Upvotes: 1

Views: 84

Answers (1)

jfriend00
jfriend00

Reputation: 707218

First, check out item 5 below. It looks to me like you have a couple javascript errors in your click event handler function.

In general, the dynamic form of .on() works like this:

$(static selector that exists).on('click', 'dynamic selector', function() {});

Since you haven't shown us your HTML or ajax, I can just enumerate the kinds of things that can go wrong:

  1. The object(s) represented by the static selector must exist at the time the .on() call is executed.
  2. The static selector objects must be parents of the dynamic objects.
  3. The dynamic selector must match children objects that either exist at the time of the original call or are added later.
  4. You could have a javascript error before the .on() call such that it is never exeucuting.
  5. You appear to have a javascript error in your handler function. Your code that references a.parentElement seems wrong. In that context, a is a jQuery event object and I don't believe it has a parentElement property. And, even if parentElement was an element, then the next line where you do target.is(":visible") would not work because target isn't a jQuery object. So, you at least have to fix the code in your handler function. If this is the only error, then you should be able to see these errors referenced in the javascript error console or the debug console.

Upvotes: 3

Related Questions