0
\$\begingroup\$

I have two .on() functions for separate dynamically added elements, they are:

$('body').on('click', 'img', function() {
   modal(content[$('li.active a').attr("href")].images[$("img").index(this)]);
});
$('body').on('click', 'img', function() {
   closeM();
});

The second function, I have shortened to

$("body").on("click", "#close", closeM);

In looking at the jQuery documentation for .on(), I saw that I can do something like:

$("body").on({
  click: function(){
  },
  mouseenter: function() {
  }
});

I was wondering if I could either do something like that with my previous two functions, or if there was any other way of shortening/combining them.

\$\endgroup\$
1
\$\begingroup\$

You could just do both operations inside the anonymous function (that you are sending as third parameter).

$('body').on('click', 'img', function() {
   modal(content[$('li.active a').attr("href")].images[$("img").index(this)]);
   closeM();
});

Also, I would consider simplifying the first instruction by breaking it down into smaller pieces.
All compressed together as it is, it is some serious black magic and should be quite tough to read or maintain by anyone else.


But $("body").on("click", "#close", closeM); is very simple, and also much more contained because it applies to the only element with id #close in the HTML, instead of to all the images. So I would prefer to leave it separate.

\$\endgroup\$
  • \$\begingroup\$ The only problem with putting the both events in the same .on() is that closeM() is called when a div with #close is called, instead of an image. So short of breaking up the parameters in the modal() call, there isn't much I can do? \$\endgroup\$ – ayyp Jun 15 '12 at 16:27
  • \$\begingroup\$ I believe so. But then, if they apply to two different things I find it better that they are explicitly separate. \$\endgroup\$ – ANeves Jun 18 '12 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.