I am using jQuery UI tabs in my web application, and I am loading each of the tab’s content dynamically via Ajax. This way, I can keep each tab’s content in separate HTML pages:
<div id="tabs">
<ul>
<li><a href="ajax/content1.html">Tab 1</a></li>
<li><a href="ajax/content2.html">Tab 2</a></li>
<li><a href="ajax/content3.html">Tab 3</a></li>
<li><a href="ajax/content4.html">Tab 4</a></li>
</ul>
</div>
The JavaScript to instantiate the tabs is in my index.js, with the HTML being in index.html.
Now, I want to create an addTabs() function in index.js that can be called from any of the tab content pages (content1.html, content2.html, etc.).
How can I do this? I tried creating the function in index.js and simply calling it with var id = addTab();. This did not work, though, as I recevieved an error: “Uncaught ReferenceError: addTab is not defined“. Here is the function:
function addTab(tabTitle) {
// Add tab code
return id;
}
I also tried to use $.getScript() which will call the function, but I cannot access var id with what is returned outside of the $.getScript() function (I can only access it within the function).
I’d appreciate any help on the matter.
Here is the index.js file:
$(document).ready(
function () {
var tabs = $("#tabs").tabs();
tabs.tabs('option', 'selected', 2);
var tabTemplate = "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>";
var tabCounter = 4;
function addTab(tabTitle) {
var label = tabTitle;
var id = "tabs-" + tabCounter;
var li = $(tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label));
// 3 fixed tabs + 5 dynamic tabs
if (tabCounter > 8) {
$("#dialog").html(
'You have reached the maximum number of tabs allowed.').dialog(
"open");
return -1;
}
$("#tabId").replaceWith(
'<input type="hidden" name="tabId" id="tabId" value="' + id
+ '" />');
tabs.find(".ui-tabs-nav").append(li);
tabs.append("<div id='" + id + "'></div>");
tabs.tabs("refresh");
tabCounter++;
return id;
}
});
the addTab function should be outside of document.ready so other files can access it