Javascript seems to be disabled in all jQuery UI tabs that are loaded through ajax. I am testing this with jQuery tooltips and .click() alerts. Javascript works fine in tabs that aren’t loaded through ajax (IDs present on the page).
Here is how I am calling the tabs:
$(function() {
$('#foo-tabs').tabs(
{
heightStyle: 'content',
// Callback run when selecting a tab
beforeLoad: function(event, ui) {
// If the panel is already populated do nothing
if (ui.panel.children().size() > 0)
return false;
//load specific ID within target page
ui.panel.load($('a', ui.tab).attr('href') + $('a', ui.tab).attr('data-target'));
// stop the default process (default ajax call should not be launched)
return false;
}
}
);
});
Here’s the javascript I’m trying to activate:
$(function() {
$( '.activate-tooltip' ).tooltip();
});
And a test:
$(function() {
$("h1").click(function() {
alert("zomg javascript works!");
});
});
Any ideas on how to get javascript working in all ajax loaded tabs? Thank you for taking the time to go through this!
When you call a method such as
.click(), it adds the event handler directly to all of the elements in the jQuery object (i.e. those that matched the selector at the time it was run). When you add new elements to the page they don’t have the associated event handlers, because they didn’t exist when that code was executed.The solution is event delegation; the general principle is that you set the event handler on an element higher up the DOM tree – one that contains all of the elements you wish to match. Then, when an event of that type is triggered on an element inside it and bubbles up to the element with the handler, it checks to see if the triggering element meets the conditions; if it does, it executes the callback function.
However, this only works for event handlers, it won’t work for plugins. I don’t know of a way to delegate plugin initialisation, so you’ll likely just have to execute the code again. Thankfully the
.load()function takes a callback function which will run when the new tabs content has finished being loaded via AJAX.