Enable and disable action by clicking on JS

Asked

Viewed 59 times

0

I’m facing a problem. I’ll put in the code and explain what I can’t do.

const interval = setInterval(() => {
  const header = document.querySelector('._1QUKR');
  
  if(header) {
    clearInterval(interval);
    
    const button = document.createElement("button");
    button.innerHTML = "2.5x";
    button.classList.add("twoTimesButton");
    header.appendChild(button)
    
    //const teste = document.querySelector(".twoTimesButton");
    
    button.addEventListener("click", () => {
      const audios = document.querySelectorAll("audio")
      
      audios.forEach(audio => {
        console.log(audios)
        audio.playbackRate = 2.5
      });
    })
    header.appendChild(button);
  }
}, 1000)

This function makes the audio acceleration of Whatsapp. How could I make it turn on and off? That is, click the button and accelerate and then click and return to normal speed. I’ve tried some parole, but I didn’t succeed.

1 answer

0


You can store the values in variables. Suppose the initial state is false, on the first click it changes the state to true and updates the rate variable to 2.5 but it can be dynamic a value that the user chooses. and next click it updates the value of isActive to false and arrow the original value in the rate.

I’ll leave an example of how it can be done.

<button id="speed">Aumentar</button>

window.onload = function() {
  let isActive = false;
  let playSpeedRate = 1;
  const button = document.getElementById('speed');

  button.addEventListener('click, function() {
    if (isActive) {
      isActive = false;
      playSpeedRate = 1;
    } else {
      isActive = true;
      playSpeedRate = 2.5;
    }
      console.log(isActive);
      console.log(playSpeedRate);
  });
}
  • Sensational! That’s what you need, I thought about doing something similar, but I couldn’t structure it. Thank you very much!

  • Magic, all good. if you can evaluate the thread by voting positive can help more people with this same problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.