JavaScript / 3 MIN READ
Buttons from JSON
Generate buttons dynamically from JSON data
From the original Fervor library. Examples may use older package versions.
Dynamic Webpage: Creating Buttons and Output from JSON
Introduction
Welcome to FrOnt3nd Tutorials! In this tutorial, we’ll explore how to create a dynamic webpage that generates buttons based on JSON data and displays corresponding output when buttons are clicked. This interactive functionality enhances user experience and is commonly used in web applications where dynamic interfaces are essential.
HTML Structure
Before diving into the JavaScript code, let’s set up the HTML structure needed for our dynamic webpage. We’ll assume that the CSS part is straightforward and involves the creation of classes to style the elements. Here’s the basic HTML structure:
<div id="button-container"></div>
<button id="submit-button">Submit</button>
<div id="output"></div>
This structure includes a container for buttons, a “Submit” button, and an area to display output.
Loading JSON Data
To create dynamic content, we need to load JSON data from an external file. Here’s an asynchronous function that uses fetch() to load the JSON data:
async function loadData() {
try {
const response = await fetch('data.json');
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching data:', error);
}
}
The loadData() function fetches the data from data.json, and the try...catch block handles any errors that may occur during the loading process.
Creating Buttons
Now, let’s create buttons based on the loaded JSON data using another asynchronous function:
async function createButtons() {
const data = await loadData();
const buttonContainer = document.getElementById('button-container');
data.forEach(item => {
const button = document.createElement('button');
button.textContent = item.name;
button.dataset.output = item.output;
button.addEventListener('click', event => {
event.target.classList.toggle('selected');
});
buttonContainer.appendChild(button);
});
}
The createButtons() function first waits for the data to load using await loadData(). Then, it loops through the data array, creating a button for each item. Each button’s text content is set to the name value, and a dataset.output attribute is assigned the output value from the item.
Handling Button Clicks
To handle button clicks and generate the corresponding output, we’ll use a synchronous function:
function handleSubmission() {
const selectedButtons = document.querySelectorAll('.selected');
const outputDiv = document.getElementById('output');
let outputText = '';
selectedButtons.forEach(button => {
outputText += button.dataset.output + ' ';
button.classList.remove('selected');
});
outputDiv.textContent = outputText.trim();
}
The handleSubmission() function selects all buttons with the .selected class, collects their output values, and displays them in the output area. The selected class is toggled on and off to manage button selection.
Conclusion
Congratulations! You’ve learned how to create a dynamic webpage that generates buttons from JSON data and displays output based on user interactions. This interactive functionality opens up a world of possibilities for engaging user experiences in various web applications.
For more insights and advanced techniques, check out additional resources on JavaScript, asynchronous programming, and front-end development.
Feel free to enhance and expand upon this tutorial content with additional explanations, examples, and practical use cases to create a comprehensive guide on creating dynamic webpages using JSON data and JavaScript.