Use a 'for' loop to delete the class name from the element only if it already exists, if not, then leave it as is

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%;
}

Answer №1

To fix the loop, simply eliminate the else section.

for (i = 0; i < button.length; i++) {
  if (button[i].classList.contains('second_pos')) {
    button[i].classList.remove('second_pos');
  } // else {
    // return;
  // }
}

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

Activate the front camera on an Android device using HTML5 or JavaScript

I'm currently working on a web app that needs to access the front camera of Android phones running version 4.0 or higher. After taking a picture, the app should then upload the captured image to my own server. Is there a way to launch the front camer ...

Influencing various classes when :active is triggered

I encountered a challenge while working on an HTML project. I included a checkbox that should highlight all text input fields when checked. However, I'm facing an issue where some of the input fields within tables are not being affected by my code. An ...

Curvature Factor equals Overflow of Color

After trying various solutions like "background-clip: padding-box;" to address the issue of background color bleeding outside of the border, I'm still not completely satisfied with the result. Is there a more effective fix for this problem? Check out ...

Eliminating Old Markers Effortlessly with Leaflet

Here is some JavaScript code that allows for the creation of markers on a map when clicked, both locally and globally in real-time using node.js / socket.io. Everything works smoothly but there is an issue where each added marker remains visible. For refe ...

Discovering the correct index of the optgroup element within selected options

When the "obj" object receives the "optgroup" elements as parameters and their corresponding options as values, an issue arises when options from both optgroups are selected. In this case, all option values are returned from the first optgroup and the prev ...

If you utilize a span element with the attribute role="textbox" and contenteditable set to true, the copying and pasting of text within it may not function correctly

Consider the following span: <span class="comment-box2" role="textbox" contentEditable=true></span> Using the following CSS: .comment-box2 { display: block; width: 100%; overflow: hidden; outline: none; ...

``When the screen size is reduced, the Bootstrap columns will resize and appear next to

Struggling to create a responsive web design similar to: https://i.sstatic.net/scRyw.png When resizing, I want the skills section to appear side by side under the introduction: https://i.sstatic.net/SLzsx.png The issue lies with the layout of the introdu ...

JS The clipboardData in ClipboardEvent is perpetually void

I am trying to retrieve files using CTRL+V from the ClipboardEvent in Angular6, but I am encountering an issue where the clipboardData is always empty regardless of whether I test images or text. This problem persists even when tested on the latest release ...

What is the best method for creating a fade effect on a div background?

I am trying to animate a div with the id #test from a 0 opacity background to an opacity of 0.7 using CSS rgba values, but for some reason, the .animate function is not working as expected. Here is my CSS: #test { background-color: rgba(0, 0, 0, 0); ...

Below is the JavaScript and AJAX code I've written to successfully transmit a JSON object

After clicking the submit button, the sendJSON function will run to send data from input fields to the server as a JSON object. The input field can have various types such as username, email, radio buttons, checkboxes, text areas, etc. Text inputs work pe ...

Endlessly executing Grunt tasks

I have configured grunt and am using the grunt-react along with grunt-contrib-imagemin tasks. The setup in my Gruntfile.js looks like this: module.exports = function(grunt) { grunt.initConfig ({ imagemin: { dynamic: { files: [{ ...

Odd behaviour when using JSON in CouchDB

I have developed an updates handler in CouchDB with test code like this (before inserting into Couch I am removing newlines): function (doc, req) { if (req['userCtx']['roles'].indexOf('editor') < 0) { return [ ...

I am interested in integrating drawing functionality (utilizing html5 canvas) into a video component within a react

In my basic React application, I have incorporated two features: a video tag for playing video content and a pen tool created with HTML5 canvas. My goal is to enable drawing on the video using the pen tool. Please review my code snippet below: const App = ...

Solving the issue of overflowing menus by expanding them beyond the container

Hey there! I'm wondering if there's a way to display the menus completely in a format like this. I've noticed that adjusting the overflow property seems to fix the issue, but I specifically need the menu to have overflow-x enabled. <h ...

Create a never-ending jQuery script that is simple and straightforward

My WordPress website features an accordion element that usually functions well by toggling classes when tabs are clicked. However, there is one issue where clicking on a tab does not automatically close other opened tabs. To address this, I added the follo ...

Using jQuery to check the value of a Kendo UI checkbox

I'm looking to extract the checkbox values, and if they are true, I want to calculate their total sum in the Total column. Here's my code: <%: Html.Kendo().Grid<SSTS.Models.ServiceUsedViewModel>() .Name("grid") .Columns(columns =& ...

The jquery click function fails to trigger, resulting in no action taken

I've been attempting to update the behavior of a button using jQuery, but for some reason it's not functioning as expected. When I click on the modal button, nothing seems to happen. The code within the script tag is still in progress and is bein ...

Guide for triggering an exception when the format of one object does not match another object

When reading user input objects, it is important that they are well-formed. This means that the input objects may not have any key or sub-structure that is not defined in the interface. What is the best way to handle an exception if a user provides an in ...

Adjusting the background color of <tr> depending on the number of <tr> elements in the HTML using CSS

When working on my HTML page, I have utilized multiple <tr> tags with different bgcolor values such as: <tr bgcolor="#000000"> <tr bgcolor="#E5F1CC"> <tr bgcolor="#D30A0A"> <tr bgcolor="#656766"> I am aiming to assign unique ...

Guide to merging two JSON objects

I have two JavaScript objects as shown below: const objOne = { "firstname": "xzxz", "lastname": "xzxzxzx" }; const objTwo = { "title": [ { "name": "foo", "ta ...