Erase every class within one second using only Pure Javascript

After trying to remove all classes after a second with no success, I attempted the code below:

function copyLink() {
  var text = document.getElementsByClassName("text"),
      len = text.length;
  for(i = 0; i < len; i++) {
      text[i].classList.add("copied");
      setTimeout(function() {
        text[1].classList.remove("copied");
      },1000);
  }
}
.copied {color: red;}
<p class="link text">Text</p>

<p class="demo text">Some text</p>

<button onclick="copyLink(location.href)">Click me</button>

Answer №1

Solution

The issue arises when the loop finishes executing before the timeouts callbacks have begun, resulting in all callbacks having the same value of i as len - 1.

Using ES6

For those working with ES6, a simple switch from var to let can resolve this problem:

for(let i = 0; i < len; i++) {
    setTimeout(function() {
        text[i].classList.remove("copied");
    }, 1000);
}

Utilizing ES5

If your project is restricted to ES5, you will need to create a new scope to correctly handle the timeouts like so:

Implementing a New Scope with a Try-Catch Block

for(var i = 0; i < len; i++) {
    try { throw i; } catch(i) {
        setTimeout(function() {
            text[i].classList.remove("copied");
        }, 1000);
    }
}

Creating a New Scope with an IIFE

for(var i = 0; i < len; i++) {
    (function(i) {
        setTimeout(function() {
            text[i].classList.remove("copied");
        }, 1000);
    })();
}

Establishing a New Scope via Function Call

for(var i = 0; i < len; i++) {
    loopCallBack(i);
}

function loopCallBack(i) {
    setTimeout(function() {
        text[i].classList.remove("copied");
    }, 1000);
}

Full Example using ES5 Syntax

function copyLink() {
  var text = document.getElementsByClassName("text"),
    len = text.length;
  for (var i = 0; i < len; i++) {
    (function(i) {
      text[i].classList.add("copied");
      setTimeout(function() {
        text[i].classList.remove("copied");
      }, 1000);
    })(i);
  }
}
.copied {
  color: red;
}
<p class="link text">Text</p>

<p class="demo text">Some text</p>

<a href="javascript:copyLink()">Click me</a>

An Alternative Approach

Rather than introducing a fresh scope for each iteration, consider placing the for loop inside the setTimeout callback function itself:

function copyLink() {
  var text = document.getElementsByClassName("text"),
    len = text.length;
  for (var i = 0; i < len; i++) {
    text[i].classList.add("copied");
  }
  setTimeout(function() {
    for (var i = 0; i < len; i++) {
      text[i].classList.remove("copied");
    }
  }, 1000);
}
.copied {
  color: red;
}
<p class="link text">Text</p>

<p class="demo text">Some text</p>

<a href="javascript:copyLink()">Click me</a>

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

Building a stylish bootstrap button within the cell rows of a table using jquery

I need to insert a button in the "Details" column. <button class="btn btn-primary btn-fab btn-icon btn-round"> Here is my code: var tableRef = document.getElementById('ticker_table').getElementsByTagName('tbody')[0]; var ti ...

What is the best way to format specific text as bold within an input text field?

I am attempting to make certain text bold within an input text field. However, I'm uncertain about how to achieve this because HTML code is not recognized inside a text field. Therefore, using <b> will not be effective. Is there a way to bold sp ...

I keep encountering the issue where I receive the message "Unable to access property 'innerText' of an undefined element" when running the Array forEach function. This problem seems to be happening within the HTMLInputElement section of the code

I am facing an issue where the error occurs because "cardTxt" is not recognized as a string. I verified this using typeof syntax, but I'm unable to understand why it can't be a string. This code snippet includes the use of bootstrap for styling. ...

Tool for controlling the layout of the viewport with Javascript

I have experience using ExtJS in the past to create dashboards, and one of my favorite features is the full-screen viewport with a border layout. This allows for easy splitting of a dashboard into panels on different sides without creating excessive scroll ...

What is the best method for automatically closing the modal window?

I implemented a modal window on my website. Within the modal, there is a green button labeled "Visit" which triggers the "Bootstrap Tour". I aim for the modal to automatically close when the tour starts. To access this feature on my site, users need to ...

What is the syntax for linking to a different file in the frontmatter of a markdown file?

Currently, I am in the process of setting up Astro's Content Collections. One particular task I would like to achieve is referencing a specific author from my `authorCollection` within an article. In attempting to accomplish this, I considered utiliz ...

Understanding Namespacing in Vuex with Vue.js

Trying to organize modules' getters, mutations, and actions with namespacing can be a bit challenging. I came across this document, but it didn't provide clear enough information for me. // types.js // Constants for namespacing getters, actio ...

What is the process of incorporating a lowercase normalizer into an Elasticsearch mapping object?

I'm attempting to incorporate a normalizer with a lowercase option into my mapping object, as detailed in the official Elasticsearch documentation Below is an example of my mapping object: const schema = { date: { type: 'date' ...

AngularJS enables the creation of multiselectable dropdown checkboxes

I am looking to create a dropdown list of checkboxes that allows for multiple selections. I have attempted to implement the code below, but I am facing an issue where the template refreshes each time a checkbox is clicked, preventing me from making multi ...

Is there a way to adjust a 5-minute countdown interval timer by 1 minute in a react JS application?

I am in need of creating a 5-minute interval timer using react JS, with a 1-minute offset. The current timer I have functions like this: 1:00 => 1:05 => 1:10 => 1:15 => 1:20. However, I require it to be adjusted to display: 1:01 => 1:0 ...

The lower section of the scrollbar is not visible

Whenever the vertical scroll bar appears on my website, the bottom half of it seems to be missing. For a live demonstration, you can visit the site HERE (navigate to the "FURTHER READING" tab). HTML: <!DOCTYPE html> <html lang="en"> <h ...

jQuery element with listener not triggering as expected

I'm facing some confusion while working on this issue. I am attempting to create a dynamic form where users can add descriptions, checkboxes, and number inputs as they please. Currently, I have developed a simple dynamic form using jQuery, which allow ...

Eliminating property while saving data to JSON file

I have retrieved data from an API in JSON format, saved it to a JSON file on a web server, and now I am displaying specific content from that file on a webpage using Angular.js. The NodeJS code I am using to save the API response to a file is as follows: ...

Increase the value of $index within the ng-repeat loop

Is there a way to increment the value of $index in ng-repeat by a specific amount? For example, if I want to display two values at a time, how can I ensure that the next iteration starts with the third value instead of the second value? <div ng-contr ...

How to send a JSON Object and a CSV file using FormData

I need to send a JSON Object and a CSV file in a fetch request from my frontend to my backend. The JSON object is stored in the headerIngestion variable, while the CSV file is saved in the csv state. let formData = new FormData(); formData.append('h ...

Encountering a runtime error in React while making an async call on a NextJS 13 page

I am currently working on implementing async calls using the new app layout in NextJS 13. I have been referring to the latest documentation page. However, I have encountered an error that I can't seem to resolve. https://i.sstatic.net/CpNmu.png Belo ...

Needing to utilize the provide() function individually for every service in RC4

In Beta, my bootstrapping code was running smoothly as shown below: bootstrap(App, [ provide(Http, { useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, helperService: HelperService, authProvider: AuthProvider) => new CustomHt ...

Creating a 3D textured sphere using Three.js

I am new to Three.js and have a basic question about loading a texture on a sphere. I am using the createEarthMaterial function in my code from the "Three.js Essentials" book but it is not working. The image file with the texture is named 'map2.png&ap ...

The apploading feature in my React Native is not functioning correctly, so I am unable to use it as intended

Every time I run my code, I encounter this error: error screenshot This is the code snippet I am using to import custom Google fonts: import React, { useState } from "react"; import Home from "./screens/home"; import { View } from &quo ...

Having trouble importing moment-range into your Angular 4.x application using ES6? Getting an error about incompatible call signatures?

In my Angular 4.x application, I encountered an issue while trying to import the moment-range package. The official documentation suggests using the following code: import Moment from 'moment'; import { extendMoment } from 'moment-range&apo ...