The Toggle Switch effectively removes the CSS class when set to false, but fails to reapply the class when set to true

Implementing a toggle switch using Bootstrap5 to control the visibility of grid lines. The setup includes adding a class to display grid lines when the toggle is true, and removing the class to hide the lines when the toggle is false. However, the issue arises when toggling the switch back on as the class does not reapply to show the lines. The coding includes using a forEach() loop to iterate through all the div elements.

Despite having console.log statements in place, triggering for each toggle, the lines do not toggle back on as expected. Below is the code snippet:

JavaScript:


let gridToggleSwitch = document.querySelector("#gridToggle")

gridToggleSwitch.addEventListener('change', () => {

    let boxList = document.querySelectorAll('.box')

    let toggleChoice = gridToggleSwitch.checked

    if(toggleChoice == true) {
        console.log("LINES")

        boxList.forEach((e) => {
            console.log(e)

            e.classList.add('box')
        })

    } else if (toggleChoice == false) {
        console.log('NO LINES')

        boxList.forEach((e) => {
            console.log(e)

            e.classList.remove('box')
        })

    } else {
        console.log('woops')
    }

})

CSS:


.box {
    border: 1px solid black;
}

Answer №1

Issue Resolved:

After realizing that the grid can be altered dynamically, I implemented a solution where I assigned dynamic IDs to the grid divs. Instead of using forEach() for the classes, I iterated through the IDs and applied/removed the border style as needed.

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

Cease all playback of audio immediately

My goal is to ensure that any audio that has been played previously stops before a new audio clip starts playing. This will prevent overlapping clips on elements that may trigger the audio file multiple times. I have attempted to pause and reset the curre ...

Creating a nested set of directives by iterating over an array within an AngularJS directive

When working inside an angularJS directive, I am attempting to iterate through an array and create a nested list of directives based on the values. The current version of the directive is as follows: Type Directive .directive("type", function($compil ...

Are HTML/CSS/JavaScript adjustments made after DOM loading taken into consideration in Google search results?

When searching on www.google.com, do the listings display content directly from the original HTML page load or do they also consider any front-end CSS / JavaScript stylings/adaptations? -- In a hypothetical scenario, let's examine the following ques ...

Differences in Spacing: Exploring Bootstrap v5.1.1 Compared to 4.0

After comparing two pages, one using Bootstrap v5.1.1 and the other with 4.0.0, I have observed differences in spacing. Bootstrap v5.1.1: .topspacer { padding-top: 70px; } .righticon { float: right; } .clear { clear: both; } a { text- ...

CSS code to modify background color upon mouse hover

I am currently working on creating a navigation menu. Check out the code snippet here: http://jsfiddle.net/genxcoders/ZLh3F/ /* Menu */ .menu { height: 100px; float: right; z-index: 100; } .menu ...

The use of Angular's ngClass directive does not work within the link function

I have a straightforward directive that renders an element, and this is the template: <div class="nav-item"></div> The .nav-item class looks like this: .nav-item { height: 50; } Here's the directive in action: angular.module('m ...

What is the best method for extracting string values from a JavaScript object?

I am working with JavaScript objects that look like this: {["186,2017"]} My goal is to extract and display only the values: 186, 2017 Initially, I attempted to use JSON.stringify thinking it was a JSON: console.log(JSON.stringify(data)); However, thi ...

Passing a JavaScript function as an argument

In the process of developing a JavaScript application, I am tasked with creating a handler that can accept a function as a parameter: Here is an example function: function myFunction() { alert("hello world"); } This is the handler implementation: func ...

What is the best way to showcase a Table and an Image side by side in HTML using inline

Can someone help me figure out how to align my image and table on the same level? I've been struggling to get "inline-block" to work. :( <p id="play"> hey </p> <div id="menu"> <table> <tr> <td>Models</td& ...

Effortlessly update value changes in ReactJs when Checkbox is checked

I've been stuck on this issue for a whole day now. I'm trying to make it so when the checkbox is checked, the value of 'Done' changes as intended. I've tried using useState but it's not working. The approach I used below is mu ...

When hovering, transition occurs unless the cursor is over a specific element

I have created a small box element with a close button that looks like this: ___ | X| ‾‾‾ In order to make it more interactive, I applied some CSS so that when hovered, the box expands like this: ___________________ | X| ‾ ...

Error: The locator I used with the ID getUserById did not find any elements

Here is the code snippet from my HTML file: <h1>User list</h1> <button class="btn btn-primary" [routerLink]="'/register'">Register</button> <br> <br> <table class="table& ...

Encountering an unanticipated DOMException after transitioning to Angular 13

My Angular project is utilizing Bootstrap 4.6.2. One of the components features a table with ngb-accordion, which was functioning properly until I upgraded the project to Angular 13. Upon accessing the page containing the accordion in Angular 13, I encount ...

PHP - contact form is live for just 2 hours daily

Hello, this is my first time here and I could really use some assistance. Please bear with me as English is not my strong suit compared to most people here, but I'll do my best to explain my query. So, I have a PHP script for a contact form on my web ...

Creating a cascade of falling balls with a single click: Here's how!

I'm currently working on a project where I have a ball dropping from the cursor location and redropping when the cursor moves to another position. However, I want to be able to create a new ball every time I click the mouse. I attempted the following ...

Overflow is causing interference with the scrollY value

I've been attempting to retrieve the scrollY value in my React app, but it seems to be affected by overflow-related issues. Below is the code snippet I used to access the scrollY value: import React from "react"; import { useEffect, use ...

Is there a way to target a button within an anchor tag without relying on a specific id attribute?

On my webpage, I have buttons that are generated dynamically using PHP from a MySQL table. Each button is wrapped in an anchor tag and when clicked, it triggers a Javascript function to carry out multiple tasks. One of these tasks requires extracting the ...

Learn how to integrate Bootstrap with Vue.js TreeView in this tutorial

If you're looking to create a treeview using Vue.js, the code structure would resemble something like this: HTML: <!-- item template --> <script type="text/x-template" id="item-template"> <li> <div ...

Transferring data to a child component through Route parameters

Although I have come across numerous questions and answers related to my query, I still seem unable to implement the solutions correctly. Every time I try, I end up with an 'undefined' error in my props. Let's take a look at my parent compo ...

Verify the password by checking each character as you type

Currently, I am trying to implement a real-time password matching feature. Is there anyone who can provide me with the code that verifies whether the entered passwords match character by character as they are being typed, and also checks the length upon ...