href jumps to top of page

While this isn’t a ruby on rails specific issue, I do tend to do this a lot, and never thought twice about it, until it starts bugging the crap out of me.
The issue is that you have a link that is used to do some type of javascript, instead of linking. So you add an onclick event, but you need something to link to. I usually put in a # sign:

<a href="#" onclick="dosomething();">Do Something</a>
<%= link_to 'Do Something', '#', :onclick=>'dosomething()' %>

This is great, except that it jumps you to the top of the page. Very annoying. Here is the solution:

<a href="#nogo" onclick="dosomething();">Do Something</a>
<%= link_to 'Do Something', '#nogo', :onclick=>'dosomething()' %>

Notice I added “nogo” to my #. This will help prevent from jumping to the top of the page. You can of course use any text you want there.

 

Tags: , , , ,

2 Responses to “href jumps to top of page”

  1. Ahmed El-Daly Says:

    I use href=”javascript:void(0)”. I think it’s neater.

  2. Randy Says:

    Thats cool too. Will that still work if the user has javascript turned off?

Leave a Reply