views:

238

answers:

7

Hey Guys,

I am pretty new to JS - so just wondering whether you know how to solve this problem.

Current I have in my code

<a href='#' class="closeLink">close</a>

Which runs some JS to close a box. The problem I have is that when the user clicks on the link - the href="#" takes the user to the top of page when this happens.

How to solve this so it doesn't do this ? i.e. I cant use someting like onclick="return false" as I imagine that will stop the JS from working ?

Thanks

+14  A: 

Just return false from your javascript click handler.

jQuery example:

$('.closeLink').click( function() {
      ...do the close action...
      return false;
});
tvanfosson
+1 - note if you're not using jQuery, make sure to check if window.event exists and if so, set window.event.returnValue = false before returning false - IE doesn't always stop bubbling unless you do this.
Rex M
cool thanks a lot - learning as i go! :)
+1  A: 

you can use onclick="return false" because it wont stop all of your scripts it will just prevent default action. In this case getting on top.

Eldar Djafarov
hey this works too :)
A: 

Try calling the javascript directly from the href, rather than linking to #:

<a href="javascript:CloseBox();" class="closeLink">close</a>

Assuming you have a javascript function called CloseBox() defined.

jrista
This breaks the event model, doesn't degrade gracefully. Practically useless 99% of the time.
Rex M
+1  A: 

If you code is getting passed the eventObject you could use preventDefault(); returning false also helps.

mylink.onclick = funtion(e){
 e.preventDefault();
 // stuff
 return false;
}
Ballsacian1
+1  A: 
<a href="javascript:void(0);" class="closeLink">Close</a>

I've never been a fan of # for links you don't want to go anywhere. Plus this way you don't have modify your javascript method.

Sam Wessel
A: 

return false is the answer, but I usually do this instead:

$('.closeLink').click( function(event) {
      event.preventDefault();
      ...do the close action...
});

Stops the action from happening before you run your code.

Martin
+1  A: 

Although it seems to be very popular, href='#' is not a magic keyword for JavaScript, it's just a regular link to an empty anchor and as such it's pretty pointless. You basically have two options:

  1. Implement an alternative for JavaScript-unaware user agents, use the href parameter to point to it and cancel the link with JavaScript. E.g.:

    <a href="close.php" onclick="close(); return false">

  2. When the noscript alternative is not available or relevant, you don't need a link at all:

    <span onclick="close(); return false">Close</span>

Álvaro G. Vicario
+1 for '#" is just an empty anchor without special meaning ... thanks.
Faisal Vali