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:

<a href='javascript:void(0)' class='btn_show_reply' data-comment_id="">Reply

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

<a href='javascript:void(0)' onClick='myFunction()' id='my_awesome_link' data-comment_id="">Reply


function myFunction(){

   //Do some awesome stuff
   // ...

   //Return false to prevent link from affecting anything
   return false;
}

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



/* Does some awesome stuff while preventing the calling link from directing the user */
$('#my_awesome_link').click(function(e) {

   //Do some awesome stuff and then prevent the link from directing user
   e.preventDefault();
});
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s