Stop a Link from Going Anywhere – CSS/JavaScript

Hey everyone,

Another quick one – how to stop a link from doing anything. I’ve just come across a need to use a link that acts as a button. A slight UI issue with this is that clicking a hyperlink will with an href value of ‘#’ will push scroll to the top of the page.

There are a couple of ways to go about fixing this. Note the href value in the following:

  1. <a href='javascript:void(0)' class='btn_show_reply' data-comment_id="<%= comment.id %>">Reply</a>

The second option is probably already familiar to anyone using ajax forms, simply have your function return false:

  1. <a href='javascript:void(0)' onClick='myFunction()' id='my_awesome_link' data-comment_id="<%= comment.id %>">Reply</a>
    
  2.  
  3. <script type='text/javascript'>
    
  4. function myFunction(){
    
  5.  
  6.    //Do some awesome stuff
    
  7.    // ...
    
  8.  
  9.    //Return false to prevent link from affecting anything
    
  10.    return false;
    
  11. }
    
  12. </script>

The third option is simply a jQuery-ish rehash of number 2:

  1. <script type='text/javascript'>
  2.  
  3. /* Does some awesome stuff while preventing the calling link from directing the user */
  4. $('#my_awesome_link').click(function(e) {
  5.  
  6.    //Do some awesome stuff and then prevent the link from directing user
  7.    e.preventDefault();
  8. });

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.