How to make a button clickable after a certain time on Hover?

Asked

Viewed 156 times

2

For the button to be clicked the user needs to keep the mouse on it for 2 seconds.

1 answer

2


Solution

Since the disabled button cannot register the event, I left the active button more with the appearance of a disabled button with css.

.disabled{
  color: grey;
}

To prevent the click event from being triggered I use a flag, if it is true it releases the click of the button, if it does not return false, thus avoiding the click.

b.addEventListener('click', function(){
  if(!botaoAtivo) return false;
  alert("O botão esta funcionando!");
});

If the user hovers the mouse over the button, a 2-second count begins, when passing this period, the text of the button is changed and the style that leaves the button looking disabled is removed and the flag is set to inform that the button is available.

b.addEventListener('mouseover', function(){
  executaFuncao = setTimeout(function(){    
    b.removeAttribute("class");
    b.innerHTML = "Botão liberado!";
    botaoAtivo = true;
  }, 2000)
});

If the user exits with the cursor before two seconds the function is canceled.

b.addEventListener('mouseout', function(){
  clearTimeout(executaFuncao);
});

Upshot

Code this comment to better understand the solution.

//Seleciono o botão
var b = document.querySelector("button");

//Criei um flag para saber se o botão esta liberado
var botaoAtivo = false;

//Variável o timeout
var executaFuncao;

//Se o mouse passa no botão ele inicia a contagem e libera o botão ao final dos 2 segundos e altera o seu texto
b.addEventListener('mouseover', function(){
  executaFuncao = setTimeout(function(){    
    b.removeAttribute("class");
    b.innerHTML = "Botão liberado!";
    botaoAtivo = true;
  }, 2000)
});

//Caso o usuário remova o mouse antes do termino dos 2 segundo a função para liberar o botão e cancelada
b.addEventListener('mouseout', function(){
  clearTimeout(executaFuncao);
});

//Bloqueia o click caso o botão não esteja liberado
b.addEventListener('click', function(){
  if(!botaoAtivo) return false;
  alert("O botão esta funcionando!");
});
.disabled{
  color: grey;
}
<button class="disabled">Coloque o mouse por 2 segundos aqui</button>

Browser other questions tagged

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