Perform a function while holding button, stop when release

Asked

Viewed 2,844 times

5

How to perform a function when the user holds a button and stop executing when the user releases the button. As happens in the Whatsapp when you will record an audio...

  • Show the code you have already developed using a button to start recording and one to stop so we can adapt it to your need

3 answers

5


You can do it like this:

var intervalId = 0;

// Define o evento de clicar com o botão do mouse no #click
$('#click').on('mousedown', function() {
    intervalId = setInterval(hold, 500); // Define um intervalo que a função será chamanda em 0.5 segundos
});

// Define o evento de soltar ao documento
$(document).on('mouseup', release);

// Função que será chamada com delay de 0.5 segundos
function hold() {
    console.log('Pressionando...');
}

// Função que será chamada quando soltar o botão
function release() {
    if(intervalId != 0) {
        clearInterval(intervalId); // Limpa o intervalo registrado anteriormente
        intervalId = 0;
        
        console.log('Soltou!');
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<button id="click">Clique e segure</button>

0

I believe the necessary actions are below, missing is to implement the code of your recording, see if it helps you:

$(function() {

  $("button").mouseup(function() {
    $("#gravando").text('Não');
    // Sua lógica para parar a gravação
  }).mouseout(function() {
    $("#gravando").text('Não');
    // Sua lógica para parar a gravação
  }).mousedown(function() {
    $("#gravando").text('Sim');
    // Sua lógica para iniciar a gravação    
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>Está Gravando?</p>
<div id="gravando">Não</div>

<button>Gravar</button>

I believe you’ll grant your request.

  • It didn’t work, actually I want to do exactly what Whatsapp does to record the audios, I can already record the audios but using a button to start recording and one to stop. I want you to record while I’m holding the button and stop recording when I release the button;

  • I changed the code to better match what you need, see if that’s it.

  • That’s exactly what I’m trying to do, the problem is that I’m using Phonegap, and these events : mouseup mouseout and mousedown, they don’t work.

  • I got it: I just changed the mousedown event by touchstart and mouseout by touchend'..

0

I got it from Bruno Rigolon, I just switched the events 'mousedown' and 'mouseup' for touchstart and touchend because I’m using phonegap.

The code stays that way:

$('#btn_gravar').on('touchstart',function(){
    //Inicia o processo de gravação
});

 $('#btn_gravar').on('touchend',function(){
    //Para o processo de gravação
 });

Browser other questions tagged

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