Issue
I added 5 buttons in js to html and I want them to be defined with a one second delay, and because of this js, when it reaches the addEventListener line, those buttons are not defined and gives an error.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<title>Document</title>
</head>
<body>
<div id="btn-adder"></div>
<script src="./script.js"></script>
</body>
</html>
CSS:
*{
padding: 0;
margin: 0;
box-sizing: border-box;
font-size: 20px;
}
body{
background: rgb(61, 61, 61);
}
#btn-adder{
margin-top: 40px;
text-align: center;
}
#btn-adder button{
padding: 5px;
margin: 5px;
}
JavaScript:
const btnAdder = document.getElementById("btn-adder");
for (let i = 0; i < 5; i++) {
setTimeout(function () {
btnAdder.innerHTML += `<button id="btn${i}">Button ${i}</button>`;
}, 1000);
}
for (let i = 0; i < 5; i++) {
document.getElementById(`btn${i}`).addEventListener("click", function () {
console.log(`Button ${i} clicked`);
});
}
Is there a way to make the addEventListener recognize the new variables?
Solution
To address the issue where the addEventListener encounters undefined variables due to the delayed creation of buttons, can modify code to ensure that the buttons are created before attempting to add event listeners.
One way to achieve this is by wrapping the button creation and event listener attachment in a function and calling that function after all the buttons have been added. Here's an updated version of code:
const btnAdder = document.getElementById("btn-adder");
// Function to create buttons
function createButtons() {
for (let i = 0; i < 5; i++) {
btnAdder.innerHTML += `<button id="btn${i}">Button ${i}</button>`;
}
// Add event listeners after buttons are created
for (let i = 0; i < 5; i++) {
document.getElementById(`btn${i}`).addEventListener("click", function () {
console.log(`Button ${i} clicked`);
});
}
}
// Call the function after a delay
setTimeout(createButtons, 1000);
In this modification, the createButtons function is responsible for both creating buttons and adding event listeners. By calling this function after a one-second delay, you ensure that the buttons are defined when the event listeners are attached, resolving the issue of undefined variables during the event listener registration.
Answered By - Ali_Sdg90
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.