Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Code stops working when timeout is added

I am trying to add a class named pressed to an element with class named w. This will happen when user clicks on element containing class w. I then want to remove the class press after delay of 100.So this is the code I have writtten.

(In short: I am trying to add animation with js by adding(and then removing after 100ms) a CSS class pressed.)

But this is not working, it’s behavior is as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. When I un-comment this part setTimeout(foo(this.innerText), 100); even the document.querySelector("."+this.innerText).classList.add("pressed"); isn’t getting executed.
document.querySelector('.w').addEventListener("click",function () {
  document.querySelector("."+this.innerText).classList.add("pressed");
  // setTimeout(foo(this.innerText), 100);
});
function foo(stringclass) {
  document.querySelector("."+stringclass).classList.remove("pressed");
  console.log(stringclass);
}

Can anyone help me with this please?

HTML Code

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Drum Kit</title>
  <link rel="stylesheet" href="styles.css">
  <link href="https://fonts.googleapis.com/css?family=Arvo" rel="stylesheet">
</head>

<body>
  <h1 id="title">Drum 🥁 Kit</h1>
  <div class="set">
    <button class="w drum">w</button>
  </div>
  <script src="index.js" charset="utf-8"></script>
</body>

</html>

CSS Class

.pressed {
  box-shadow: 0 15px 40px 0 #DBEDF3;
  opacity: 0.5;
}

>Solution :

setTimeout(foo(this.innerText), 100); executes foo immediately. You need to pass the function itself.
I believe you want something closer to
document.querySelector('.w').addEventListener("click",function (e) { document.querySelector("."+e.target.innerText).classList.add("pressed"); setTimeout(function() {foo(e.target.innerText)}, 100); });

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading