What causes the toggle to malfunction when clicked on, specifically when the element is assigned the JS class?

Currently, I am working on animating cards using CSS and JavaScript. Everything seems to be working fine except for one issue – the class does not get removed on the second click on the element when using

this.classList.toggle('is-active');
. Can you help me identify and fix this error? What am I doing wrong here? Why does the toggle method behave like add in this particular scenario?

window.addEventListener('load', function() {
  const cardsList = document.querySelectorAll(".card");
  for (let card of cardsList) {
    card.addEventListener("click", function() {
      for (let c of cardsList) {
        c.classList.remove('is-active');
      }
      this.classList.toggle('is-active');
    });

  }
})
.cards {
  display: grid;
  grid-template-columns: repeat(3, 33.33%);
  grid-auto-rows: 70vh;
}

.card {
  position: relative;
  overflow: hidden;
}

.card img {
  transition: 2s;
  width: 100%;
  height: 100%;
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
}

.card .card__title {
  color: #fff;
  position: relative;
  z-index: 2;
}

.card__text {
  position: absolute;
  padding: 50px 100px;
  font-size: 15px;
  transform: translate(0px, 70vh);
  transition: transform .5s ease 0s;
  z-index: 2;
  color: #fff;
}

.card:hover img {
  transform: scale(1.2);
}

.card.is-active .card__text {
  transform: translate(0px, 0px);
  transition: transform .5s ease .5s;
  top: 50%;
  transform: translate(0, -50%);
}

.card:after {
  content: "";
  margin: 0;
  background: red;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%);
  border-radius: 100%;
  width: 0;
  height: 0;
  transition: all 1.3s;
}

.card.is-active:after {
  width: max(100vh, 100vw);
  height: max(100vh, 100vw);
}
<div class="cards">
  <div class="card">
    <img src="https://d626yq9e83zk1.cloudfront.net/files/2017/12/26-770x425.jpg">
    <div class="card__title">Lorem </div>
    <div class="card__text">ipsum dolor sit, amet consectetur adipisicing elit. Itaque, nulla?</div>

  </div>
  <div class="card">
    <img src="https://d626yq9e83zk1.cloudfront.net/files/2017/12/26-770x425.jpg" alt="">
    <div class="card__title">Lorem </div>
    <div class="card__text">ipsum dolor sit, amet consectetur adipisicing elit. Itaque, nulla? </div>
  </div>
  <div class="card">
    <img src="https://d626yq9e83zk1.cloudfront.net/files/2017/12/26-770x425.jpg" alt="">
    <div class="card__title">Lorem </div>
    <div class="card__text">ipsum dolor sit, amet consectetur adipisicing elit. Itaque, nulla? </div>
  </div>
</div>

Answer №1

The is-active class has already been eliminated within the for loop. Therefore, the toggle function will restore it.

To remedy the situation, refrain from removing the class within the for loop.

for (let item of itemList) {
  if(item === this) { continue; }
  item.classList.remove('is-active');
}

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

Loop through a variable class name in JavaScript

When working with Javascript, I have a series of elements with identical divs: (....loop, where "count" is a unique number for each column) <other divs> <div class="pie"></div> </div> My goal is to be able to rotate each individ ...

Boundaries on Maps: A guide to verifying addresses within a boundary

User provides address on the website. If the address falls within the defined boundary, it is marked as "Eligible". If outside the boundary, labeled as "Ineligible". Are there any existing widgets or code snippets available to achieve this functio ...

Parsing URLs with Node.js

Currently, I am attempting to parse the URL within a Node.js environment. However, I am encountering issues with receiving null values from the following code. While the path value is being received successfully, the host and protocol values are returnin ...

An issue has emerged: React cannot render objects as children. The culprit appears to be an object containing keys such as {

My sanity schema, named blogs, includes a reference field called author. I am trying to use blog.author in order to fetch the author's name for my blog, but I keep encountering an error. https://i.stack.imgur.com/haotL.png The code in my Sanity blo ...

Is there a node.js equivalent to Turbolinks available?

One of my favorite features in Rails is Turbolinks, as it enhances the user experience by making pages appear to load faster. Is there any alternative or similar functionality for node.js? ...

"Exploring the versatility of NextJS with dynamic route parameters

Can NextJS be configured to handle dynamic routes that match both /country and /country/city, while excluding matches like /country/city/whatever_content_here? The goal is to display the same content for either of the specified routes, regardless of whethe ...

Error Found: Syntax Error - 'if' statement not recognized

if (fname == null || fname == "") { Receiving an error message "uncaught syntax error:unexpected token if in line 13". The error indicates "SyntaxError: missing variable name" when using Javascript lint function validateRegistration() { var emailReg ...

Highlighted option selection in Material UI dropdown using Cypress

Can someone explain how to select Material-UI dropdown options using Cypress? I'm looking for a simple explanation, thanks! ...

Latest FF 35 showing alert for blank field in HTML5 email input box

My form includes an email input field with a default value. When the user focuses on the field, it clears out if the value matches the default one. Upon blurring the element, the default value is restored if the field remains empty. In Firefox 35, clickin ...

Changing global properties in VueCli

Recently, I integrated a component library into my Vue 3 project. All instances of the component require the same styles. Instead of manually adjusting each instance's props, I opted to utilize a global property: app.config.globalProperties.$tooltipS ...

Exploring the World of 2D Array Animation

I'm in the process of creating a Pacman ghost using visual 2D arrays. I would like the ghost to move similar to this: https://i.sstatic.net/KPmUt.gif I am considering implementing CSS transitions for the movement, but I'm unsure about how to do ...

Exploring the power of Vue.js by utilizing nested components within single file components

I have been attempting to implement nested single file components, but it's not working as expected. Below is a snippet of my main.js file : import Vue from 'vue' import BootstrapVue from "bootstrap-vue" import App from './App.vue&apos ...

NextRouter does not have a property called "refresh"

Here is the provided code snippet: "use client"; import { useRouter } from "next/router"; import { useState } from "react"; export default function CreatePrompt() { const [title, setTitle] = useState(""); const ...

Tips for passing the indexes of an array within nested ngFor loops in Angular

I have a 2D grid in my component that is created using nested ngFor loops, and I want to make certain grid elements clickable under specific conditions so they can call a function. Is there a way for me to pass the index of the clicked array element to the ...

The $scope.$watch function does not activate with each individual change

Yesterday, I realized that in my angularJS 1.4.8 application, the $scope.$watch doesn't trigger on every change causing a bug to occur. Is there a way to make it work on every change immediately? For example, in this code snippet, I want the function ...

Results From Trimming Data

There's a function in my code that fetches data from a database. The problem I'm facing is that the function is returning values with extra quotation marks. Before displaying these values on the user interface, I need to trim them. This is the f ...

Error: Unable to iterate through users due to a non-function error while attempting to retrieve the firestore document

I encountered an issue with my code, receiving the error message: TypeError: users.map is not a function. Can anyone help me identify what might be wrong? const [users, setUsers] = useState([]); const getData = async () => { try { const use ...

The onClick functionality for the IconComponent (dropdown-arrow) in React Material UI is not functioning properly when selecting

I have encountered a problem in my code snippet. The issue arises when I attempt to open the Select component by clicking on IconComponent(dropdown-arrow). <Select IconComponent={() => ( <ExpandMore className="dropdown-arrow" /> )} ...

Populate a bootstrap-select dropdown menu with an array of choices

After creating a table using datatables and adding an empty dropdown select on the footer with Bootstrap-select, here is the code snippet: <tfoot> <tr> <th><select class="selectpicker" multiple></select>< ...

Checking authorization with CognitoUser solely for "code" provided by CognitoUser (npm: amazon-cognito-identity-js)

Currently, I am in the process of implementing the "forget password" feature. However, I have encountered an issue where I would like to verify the "verification code" first before setting a new "password". Unfortunately, the system currently requires bo ...