Href="#" Don't Scroll

Viewed 46079

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

11 Answers

The usual way to do this is to return false from your javascript click handler. This will both prevent the event from bubbling up and cancel the normal action of the event. It's been my experience that this is typically the behavior you want.

jQuery example:

$('.closeLink').click( function() {
      ...do the close action...
      return false;
});

If you want to simply prevent the normal action you can, instead, simply use preventDefault.

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

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.

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>

Like ROFLwTIME example, one easy way is put two ## in the href. It's not common, but worked for me.

  <a href='##' >close</a>

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

mylink.onclick = function(e){
 e.preventDefault();
 // stuff
 return false;
}

I like to use jQuery. That's so simple.

$('a').on('click',function(e){
 if($(this).attr('href')=='#')
  return e.preventDefault();
});
Related