Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i event.preventDefault() when using jQuery's mousedown and mouseup methods?

I am using event.preventDefault() to prevent concatenation of # which is the href of an anchor to the URL. I am preforming events on the mousedown() and mouseup() parts of the click which is why i cant use click. But event.preventDefault() is not preventing the concatenation of # to the URL when envoking mouseup() or mousedown() methods. How can i get around this?

like image 881
Babiker Avatar asked Jan 29 '11 23:01

Babiker


1 Answers

If you're talking about clicking a link, it is probably because there isn't a default behavior to prevent for mousedown and mouseup.

The default behavior of clicking a link requires a combination of mousedown plus mouseup on the link. If you mousedown then drag off the link before you mouseup, the link is not followed. The same vice-versa.

Only when you mousedown then mouseup is the default behavior activated. That event is represented by the click event.


EDIT: I guess I forgot to answer the question.

How do you get around it? Add a click() event handler that does e.preventDefault().

$('a.myElement').click(function(e){e.preventDefault()});

If you also want to stop propagation of the event, and if you're using jQuery 1.4.3 or later, you can do this:

$('a.myElement').bind('click',false);

From the docs for the bind()(docs) method:

Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling.

Again, it requires jQuery 1.4.3 or later.

like image 58
user113716 Avatar answered Sep 25 '22 06:09

user113716