Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent href from opening link but still execute other bind events

I want to prevent links from opening pages. So I have written this :

$("a").click(function(e) {     e.preventDefault() } 

which is great! But this blocks my other event :

$(".toolbar a").click(function(e) {     ...action... } 

Sure I can add my action to the first event with some test, but is there an elegant way to prevent only href event from executing?

EDIT

In fact it works, sorry. See @raina77ow fiddle working here: http://jsfiddle.net/HeFS6/

like image 757
Benoit R Avatar asked Sep 06 '12 11:09

Benoit R


People also ask

Can you put a function in href?

In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).

How would you stop a link from causing navigation when clicked?

One way you can prevent navigation is to implement an click / onclick JavaScript event handler and return false from it. Alternately you can use event. preventDefault() inside the click event's event object passed into the handler too.

How do I stop Onclick from jumping to top?

Just use "#/" instead of "#" and the page won't jump. This need to be the best answer.


2 Answers

Use return false instead. You can see the code below working here.

​$("a").click(function() {     return false; });  $(".toolbar a").click(function() {     alert("Do something"); });​ 

As pointed by @raina77ow with this article, using return false is the same as calling event.preventDefault() and also event.stopPropagation(). As I had troubles without return false on some codes in the past, I always suggest it.

But the most importante thing here is the bind order: your last bind will be your first executed code. So, take care about it and go.

like image 74
Erick Petrucelli Avatar answered Oct 03 '22 12:10

Erick Petrucelli


In place of e.preventDefault(), have you tried return false? This should also prevent browser default behaviour.

like image 33
Matt C Avatar answered Oct 03 '22 14:10

Matt C