I found a great resource for creating tabs using JavaScript: The code provided in the link creates tabs based on the number of 'tab-content' divs within the 'tab-container'. In my current project, I am dynamically generating the 'tab-content' divs based on data fetched from an XMLHttpRequest:
window.onload = function() {
var doSomethingAJAX = function (el, url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function () {
var data = JSON.parse(xhr.responseText);
var tasks = data.data;
var aTags = document.getElementsByTagName("A");
for(var h = 0; h < tasks.length; h++){
var tabContainer = document.getElementById("tab-container");
var divElement = document.createElement("div");
divElement.className = 'tab-content';
tabContainer.appendChild(divElement);
var hOneElement = document.createElement("h1");
hOneElement.className = 'tab';
hOneElement.setAttribute('title', 'task' + h);
hOneElement.innerHTML = tasks[h].name;
divElement.appendChild(hOneElement);
var formElement = document.createElement("form");
formElement.className = 'taskForm';
formElement.setAttribute('action', 'CompleteTask');
formElement.setAttribute('method', 'post');
divElement.appendChild(formElement);
var taskId = tasks[h].id
getFormProperties(taskId, h);
}
};
xhr.onerror = function () { alert("error") };
xhr.send();
};
The 'tab-content' divs are being created successfully, but the tabs are not being generated. The script that builds the tabs seems to stop at this point:
tabContents = getChildElementsByClassName(tabContainer, 'tab-content');
if(tabContents.length == 0)
return;
I suspect that it might be related to the AJAX request. How can I ensure that the BuildTabs() function is only called once all the divs have been created?
Here's the HTML structure:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="js/apitest.js"></script>
<style type="text/css" media="screen">@import "css/tabs.css";</style>
<title>Tabs and REST</title>
</head>
<body>
<div id='tab-container'>
</div>
<script type="text/javascript" src="js/tabs.js"></script>
</body>
</html>
Just a heads up, the getFormProperties() function also involves an XMLHttpRequest. Maybe that's worth considering.