Pregunta

My code is...

var timer;
var func = function () {
        $("body").append("1");
};

$(document).on('mousedown' , 'a' , function(e){
        timer = setTimeout(func, 1000);
}).on('mouseup mouseleave' , 'a' , function(e){
        clearTimeout(timer);
});

Everything working. But when I set this function to some link like <a href="http://google.com">text</a>

I need to set return false; (not redirect to the url or another onclick() functions)

Where return false; can I set in ? Or another solution ?

PS : And I will my link will work normally when click by normal clicking

Playground : http://jsbin.com/iwilop/1/edit


How can I listen for a click-and-hold in jQuery?

¿Fue útil?

Solución

You need to add a click handler and, if your func was called, prevent the default action of the click. Here I'm using timer as a flag:

var timer = 0;
var func = function () {
  $("body").append("1");
  timer = 0;
};

$(document).on('mousedown' , 'a' , function(e){
  timer = setTimeout(func, 1000);
}).on('mouseup mouseleave' , 'a' , function(e){
  if (timer) {
    clearTimeout(timer);
  }
}).on('click', 'a', function() {
  if (!timer) {
    return false;
  }
});

Updated JSBin

Otros consejos

You need a click handler (you don't actually need to call return false unless there are other handlers that could also fire):

$(document).on('mousedown' , 'a' , function(e){
        timer = setTimeout(func, 1000);
}).on('mouseup mouseleave' , 'a' , function(e){
        clearTimeout(timer);
}).on('click', 'a', function(e) {
        return false;
});

Bear in mind that the above will affect all links on the page - you may need to qualify the a selector to be more specific (e.g. a.blah).

Edit: in light of your revised question, I have nothing to offer over and above T.J. Crowder's answer. The only thing I'd say is to watch out for global variables - you might want to wrap the whole thing in an immediately invoked function expression or similar.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top