Search code examples
jqueryonclicklistenerjquery-eventssimplify

jQuery.on('click', 'element', function) simplifying doesn't work


I'm trying to make my jQuery code simpler - .on('click', function), I usually replace by .click(function) and things like that. However, I have a code looking like this:

jQuery(document).on('click', '#lightbox', function() {
    //do something
});

And I don't really understand the structure. I've tried reading on it on jQuery.com and such, but it's explained in a complicated way. My problem is, why isn't that line looking like this..:

jQuery('#lightbox').on('click', function() {
    //do something
});

... so that I could simplify it to this?:

jQuery('#lightbox').click(function() {
    //do something
});

When I try that, it won't work. Why is the selector document instead of the actual element ('#lightbox') to be clicked, and then it's referenced later in another argument?

Can anyone explain this to me? Just a simple question - I'm not an expert in jQuery (as you may have understood by now), and this isn't a major error either, it's just bugging me a little that I can't have the same click code everywhere (because the simplified code works other places).

(I can upload the whole code and make a Fiddle if necessary, it's only 70 lines, so should be easy)


Solution

  • You'll want to use this :

    jQuery(document).on('click', '#lightbox', function() {
        //do something
    });
    

    only if #lightbox element is loaded after the event listener was set (e.g: if you create the #lightbox element using AJAX after the page was loaded).

    If #lightbox exist from the start on your page, then use this :

    jQuery("#lightbox").click(function() {
        //do something
    });
    

    As charlietfl said : Note that click() is just a shorthand for on('click')