Creating tabs in JavaScript using REST API after div elements have been generated

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.

Answer №1

Revise this function:

 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);

        }
       BuildTabs();
    };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The word-break CSS property is ineffective in this situation

I've been experimenting with the word-break css property, but I just can't seem to get it to work even when using a simple example. Here's my code: React: render() { return ( <h5 className="word-break">A very very long line.... ...

Press the submit button after receiving the ajax response

Is there a way to manually or programmatically submit a specific page? The catch is that before the submission can happen, a function called create_impi_num(x) needs to be triggered in order to store data using $.post(). The issue at hand: If I set the s ...

Comparing the use of visibility: hidden with -webkit-transform: translate3d() within a PhoneGap application

Currently, I am creating a hybrid application using PhoneGap. As part of the design, I have several divs (each representing a page) that I toggle between by changing their visibility in CSS using "visibility: hidden" and "visible". However, I recently ca ...

Is there a way to retrieve all results from a ReactiveList?

My attempt to retrieve all data has been unsuccessful as I am only able to obtain the number of results specified in the 'size' parameter. Below is a snippet of my code. <ReactiveList componentId="results" dataField="original_title" siz ...

"Can you provide guidance on displaying a form for a specific element based on its unique ID

I am trying to display the edit form when clicking on a specific image, but it is currently showing for all tasks. I need help in figuring out how to make it show only for one task. I attempted to use useState to change the boolean value "active" to show ...

What is the best way to modify a state in nextjs?

Recently, I've been working on a next.js project that includes a shopping cart feature. Essentially, when you click on an item, its image is added to a list and displayed with all the other selected items. To remove an item, users can simply click on ...

Adjusting the z-axis rotation in a three.js animated scene

Is there a way to add a function that changes the Z rotation value of the teapot from within the updateTeapot function? I came across this helpful answer on Three.js camera tilt up or down and keep horizon level. However, I am unsure how to integrate a z ...

Store the current function in the cache, incorporate new features, and execute those additions upon calling another function

I have a pre-existing function that I am unable to directly access or modify. Due to this limitation, I have resorted to caching the function and incorporating additional functions alongside it. This function loads periodically, sometimes occurring on pag ...

Extract picture links from a JSON file and use them to create a dynamic slideshow in JavaScript

I am looking to integrate a JSON list of image URLs into a JavaScript slideshow function. Could someone provide guidance on how to dynamically replace the hardcoded list of image URLs with those from a JSON object? <script type="text/javascript> ...

Discover how to use your own search engine suggestions within the search bar of Google Chrome

I recently created a search engine on my website, and everything seems to be working perfectly when I visit the search page. However, I wanted to streamline the process by searching directly from the search box in Chrome. After adjusting the settings to ...

Incorporating PWA functionality into Next.js for seamless notifications and push notifications

I've been working on developing a Progressive Web App (PWA) using next.js and running into some challenges. My goal is to incorporate device motion, geolocation, and notifications into my users' accounts. I'm taking inspiration from this r ...

What's the best way to showcase array values in JavaScript?

I am facing an issue where I am trying to display all values from the array "categories", but I keep getting [object object] or undefined. The problem seems to be occurring in the code within the last lines of the if statement, specifically when I try to ...

Incorporating a YouTube channel into mobile websites

While it's relatively easy to embed single YouTube videos in mobile pages with the help of Google, I'm still struggling with embedding a whole channel. The issue seems to revolve around the screen width, and my attempts at using JavaScript have n ...

Display numeric data when hovering over circles in the Google Maps API using Javascript

I recently implemented the Google Maps example code that displays a circle hovering over a city, with the size of the circle representing the population. I'm looking to enhance this feature by including numeric data display on mouseover as well. Any a ...

Enhancing image clips using jQuery techniques

Could someone help me figure out why the image clip value isn't changing when I move the range slider in the code below? $('#myRange').on('input', function() { var nn = $(this).val(); $("img").css({ 'clip': ...

Ending an $.ajax request when the page is exited

Currently, I have a function set on a timer to retrieve data in the background: (function fetchSubPage() { setTimeout(function() { if (count++ < pagelist.length) { loadSubPage(pagelist[count]); fetchSubPage(); ...

What is the best way to utilize the oninput function in Jade?

input(type='range', id= 'inputSlider', min='0', max='255', value='50', step='1', oninput=showValue(this.value)) span#outputText 50 script. var socket = io.connect(); socket.on(& ...

Despite seeming false, my Javascript if statement still evaluates to true

On my webpage, I have a button and a form. The intended functionality is for the button to display the form when clicked, and hide it when clicked again. The issue I'm facing is that no matter if the statement is true or false, the first if statement ...

Create an input field dynamically by utilizing the append method in jQuery

Concern: As part of an edit page, I am working on appending an input field from a modal window to an existing panel while retaining the format of the rest of the fields. The user is currently able to create and add the new field using the code provided in ...

What is the best way to transfer my object along with its unique textures from Blender to ThreeJS?

I've been using the STL Loader in three.js to import objects from Blender, but I'm facing an issue where the textures are not appearing. I suspect it has something to do with the MeshBasicMaterial of the object. I attempted to switch it to Phong ...