Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the <a> tag as a button without following its link

Tags:

html

jquery

I use the <a> tag to build buttons. I use JavaScript (jQuery) to implement the behavior.

How can I prevent the browser from following a link, while continuing to execute all click() events?

This:

$("a.button").live("click", function(event) { return false; });

doesn't work, because, depending on the position of that handler it might prevent other .click() handlers from executing. For some buttons it works as I want it, but for some it prevents my other handlers from executing.

I know I could use a single click handler per button, but I would rather do it the AOP-way.

like image 629
THX-1138 Avatar asked Aug 04 '10 14:08

THX-1138


1 Answers

jQuery provides a method called preventDefault which will stop the default action of the event from occurring. With this the following code will stop the link from being follow but should not stop the propagation of the even to other handlers.

$("a.button").click(function(event){ event.preventDefault(); });
like image 172
Matthew Manela Avatar answered Oct 23 '22 04:10

Matthew Manela