I am facing an issue with a list of buttons where, upon clicking one button, it should move across the screen and bring in a 'back' button. The purpose of the 'back' button is to return the previously clicked button to its original position in the lineup of buttons before hiding again. However, the problem I am encountering is that the button clicked does not return to the list when the user clicks the 'back' button. I suspect there might be an error in the for loop logic, even though it seems logical to me. Below is the script:
//Variables
var back = document.getElementById('back');
var button = document.getElementsByTagName('li');
var i;
/* Moves the clicked button to center of the page
and changes the hidden back button's class to make it visible */
// This part works fine
function moveButton(e) {
'use strict';
var target = e.target;
target.classList.add('second_pos');
back.className = 'back';
}
// Removes the back button and returns the active button to its original position
// The back button gets removed but the loop doesn't work as expected on other buttons
function goBack() {
back.className = 'back_hidden';
for (i = 0; i < button.length; i++) {
if (button[i].classList.contains('second_pos')) {
button[i].classList.remove('second_pos');
} else {
return;
}
}
}
// Event Listener for main buttons
for (i = 0; i < button.length; i++) {
button[i].addEventListener('click', moveButton, false);
}
// Event listener for the back button
back.addEventListener('click', goBack, false);
Here is the corresponding CSS:
.demo_space {
display:table;
position:relative;
height:100vh;
width:90%;
margin:0 auto;
ul {
display:table-cell;
height:100vh;
width:100vw;
li {
display:inline-block;
}
}
}
.first_pos {
float:left;
font-size:2em;
padding:1em;
color:$green;
}
.second_pos {
position:absolute;
bottom:50%;
left:50%;
}