intargc
intargc

Reputation: 3111

Using jQuery.on() vs. loading script when content loads

When loading content inside of a modal box or lightbox, is it better to hook up needed events and scripts through the use of jQuery.on(), or have it load with the content by a script tag?

For example, with the .on() solution:

$('#blah').on('load', function() {
    $('#something').click(function() { alert('Hi'); });
});

And then when the modal box was loaded, it would call $('#blah').trigger('load')

Or, just simple have the the script loaded in with the HTML as in:

<div id="blah">
    <a href="#" id="something">Something</a>
</div>
<script src="/js/blah.js"></script>

With blah.js containing the javascript code above involving setting up the click event on #something. I've used the .on() method for a while, but I wasn't sure if this was the best way to handle this.

Upvotes: 1

Views: 65

Answers (2)

jfriend00
jfriend00

Reputation: 707386

The way .on() was designed, you would set up the event handler first like this:

$("#blah").on('click', "#something", function() { alert('Hi'); });

Then, when you load the content in #blah, your event handler will automatically work for the #something element and you don't need a .load() handler.

The way this works is jQuery sets up an event handler on #blah. That event handler examines any click events that bubble up to it and when it sees one that has a target that was on an object that matches the selector #something, it fires the event. The #something can come and go as much as it wants because the actual event handler is on the parent object that exists the whole time.

Using this method, you would not need the extra blah.js file.

Upvotes: 1

Domenic
Domenic

Reputation: 112827

Argument for the script inclusion solution

The on solution is ugly and involved. It requires more code than the simple script inclusion, and mixes up concerns between the load handling code (which is presumably somewhere else) and the lightbox contents. Why should that code know about the ids of elements inside the lightbox?

Argument for the on solution

It involves one less HTTP request and so will probably be faster.

Upvotes: 2

Related Questions