I'm trying to write a code that displays several boxes one after the other, but only after the previous one has been closed. This can be done in two ways. Either the box closes automatically after 10 seconds, or it stays up indefinitely until it is closed by clicking "X".
I am trying to use a for loop to iterate over an array (mandatory) of these boxes, but I cannot work out how to 'pause' the loop to wait for user action. The loop must stop when all boxes have been displayed. Does anyone know how this could be done (without jQuery)? I've tried using setTimeout, but then realized it cannot be done this way. I'm new to programming, so it's all a bit confusing, if anyone could help I'd really appreciate it! It may be worth mentioning that I'd prefer not to use id's.
I've tried to simplify my code to be easier to read:
HTML:
// Simplified - every element has this structure, only the class changes for the parent div
<div class=" box 'type' "> // type -> can be '"success" or "warning"
// BOX BODY
<div class="box-close" onClick="removeBox()"> X </div>
</div>
CSS
.box{display="none";}
JavaScript
// Simplified - each box div present in page is stored in array allBoxes
allBoxes = array of boxes
//Show boxes 1 by 1
for (j = 0; j < allBoxes.length; j++) {
showBox(allBoxes[j]);
}
function showBox() {
box=allBoxes[j];
box.style.display= "block";
if (box.classList.contains("success")==true){
setTimeout(removeBox, 10000); //PROBLEM: only executes after for loop is done, meaning it 'removes' the last div in the array being looped, regardless of type class
//alternative
setTimeout(removeBox(box), 10000); //Problem: executes remove immediately, without waiting the 10s
}
else{
//something to make the For Loop pause until the user clicks on X
box.querySelector(".box-close").addEventListener("click",removeBox); //doesn't do anything, loop continues
//alternative
box.querySelector(".box-close").addEventListener("click",removeBox(box)); //simply removes box immediately (not in response to click or anything), loop continues
}
}
function removeBox() {
box.style.display = "none";
}