Event when you press the button

0

Would there be any way to detect the tap at the push of a button? The code works fine on the desktop , but when I test in mobile does not fire.

Using JqueryMobile is not an option.

var timeout = 0;

$('button').mousedown(function() {
    timeout = setTimeout(menu_toggle, 2000);
}).bind('mouseup mouseleave', function() {
    clearTimeout(timeout);
});

function menu_toggle() {
  alert('ok');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>pressionar</button>
    
asked by anonymous 04.05.2018 / 03:04

5 answers

2
  

You will need timers, set one when the mouse is pressed, clear it when the mouse is released.

$( "#target" ).on({
mousedown: function() {
    $(this).data('timer', setTimeout(function() {
          foo();
    }, 4000));
},
mouseup: function() {
    clearTimeout( $(this).data('timer') );
}
});


function foo() {
//alert('Diego Vieira, obrigado por me pressionar por 4 segundos !')
 console.log('Diego Vieira, obrigado por me pressionar por 4 segundos !')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="target">Diego Vieira, pressione-me por 4 segundos</button>
    
04.05.2018 / 04:05
0

Try:

$('button').on('click touchstart', function() {
    
04.05.2018 / 03:09
0

Try this, then:

<script type="text/javascript">
var timeout = 0;

$('button').mousedown(function() {
    timeout = setTimeout(menu_toggle, 2000);
});

function menu_toggle() {
  alert('ok');
  clearTimeout(timeout);
}
</script>
    
04.05.2018 / 03:27
0

Try this way, it can help you solve the problem without dependence on libs. In that script was kept his initial idea how it would work, however written otherwise.

Two event listeners are added to the button, one that performs the function when the button is pressed ' mousedown ' and another when the button is no longer being triggered by user ' mouseup '. Hope it helps.

const button =  document.querySelector('#btn');

let timeout = 0;

const menu_toggle = function() {
  alert('ok');
};

button.addEventListener('mousedown', function(){
  timeout = setTimeout(menu_toggle, 2000);
}, false);

button.addEventListener('mouseup', function(){
  clearTimeout(timeout);
}, false);
    
04.05.2018 / 22:13
0

Unfortunately none of the answers ended up working in mobile .

The only thing that solved it was to use the plugin Finger , which is specially made for this.

I'll leave the link in case someone goes through this same problem:

link

    
05.05.2018 / 01:30