How can I change the behavior of an active button according to time or clock?

Asked

Viewed 32 times

-2

Minha dúvida é como automatizar esse processo. Os botões ativarem de maneira automática de acordo com o time ou relógio do computador.

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
/* Style the buttons */
.btn {
  border: none;
  outline: none;
  padding: 50px 50px;
  background-color: #f1f1f1;
  cursor: pointer;
  font-size: 18px;
}

/* Style the active class, and buttons on mouse-over */
.active, .btn:hover {
  background-color: #666;
  color: white;
}
</style>
</head>
<body>
  
<div id="myDIV">
  <button class="btn active">12:00</button>
  <button class="btn ">12:01</button>
  <button class="btn ">12:02</button>
  <button class="btn ">12:03</button>
  <button class="btn">12:04</button>
</div>

<script>
// Add active class to the current button (highlight it)
var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
  var current = document.getElementsByClassName("active");
  current[0].className = current[0].className.replace(" active", "");

  this.className += " active";
  });
}
</script>

</body>
</html>

1 answer

1

Hello, I do not know if I understand very well, in your code currently you are adding the behavior with the click, and I would like it to be automatic with the passage of time, it would be this?

In case could use an interval, to manipulate the buttons with time interval, example:

    const header = document.getElementById("myDIV");
    let timeout = 0; // aqui setamos um tempo limite, caso queira que depois de certo tempo pare de manipular os botões

    // (function() {})(); é uma syntaxe para função auto executável

    // aqui nessa promisse, a cada 1000 milisegundos (1 segundo) ele retira a classe active do elemento que ja tem, 
    // com método find nativo do javascript verificamos qual é o botão que tem o texto igual ao horario atual, e adicionamos a classe a ele
    (async function () {
        await new Promise((resolve, reject) => {
            let interval = setInterval(() => {
                let date = new Date();
                let activeBtn = header.querySelector('.btn.active');
                if (activeBtn) {
                    activeBtn.classList.remove('active');
                    const currentBtn = [...header.children].find(btn => btn.textContent === `${date.getHours()}:${date.getMinutes()}`);
                    currentBtn && currentBtn.classList.add('active')
                }

                if (++timeout > 100) {
                    console.log('timeout atingido!');
                    clearInterval(interval);
                    resolve();
                }
            }, 1000);
        })
    })();
  • That’s just what I needed, it worked perfectly. I appreciate the collaboration!

Browser other questions tagged

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