views:

170

answers:

2

Hi,

Is it possible to implement "long press" in JavaScript (or jQuery)? How?

alt text

HTML

<a href="" title="">Long press</a>

JavaScript

$("a").mouseup(function(){
  // Clear timeout
  return false;
}).mousedown(function(){
  // Set timeout
  return false; 
});

Thank you!

+4  A: 

There is no 'jQuery' magic, just JavaScript timers.

var pressTimer

$("a").mouseup(function(){
  clearTimeout(pressTimer)
  // Clear timeout
  return false;
}).mousedown(function(){
  // Set timeout
  pressTimer = window.setTimeout(function() { ... your code ...},1000)
  return false; 
});
Diodeus
Couldn't have said it better myself.
mattbasta
Also... You need to specify $("a").click(function(){ return false; });
Randy Mayer
Otherwise, thank you!
Randy Mayer
What, you can use JavaScript without jQuery? Blasphemy!!! ;)
Shawn Steward
Yep, it amazes me that many people think jQuery can solve the problem without thinking of basic principles.
Diodeus
A: 

You could set the timeout for that element on mouse down and clear it on mouse up:

$("a").mousedown(function() {
    // set timeout for this element
    var timeout = window.setTimeout(function() { /* … */ }, 1234);
    $(this).mouseup(function() {
        // clear timeout for this element
        window.clearTimeout(timeout);
        // reset mouse up event handler
        $(this).unbind("mouseup");
        return false;
    });
    return false;
});

With this each element gets its own timeout.

Gumbo
`$(this).mouseup(function(){});` does not remove the event handler, it adds another one. Use `.unbind` instead.
Matti Virkkunen
@Matti Virkkunen: Thanks!
Gumbo