Search code examples
ruby-on-railsruby

Rails link_to: click but stay in place, do not jump to top of page


I have a link_to in my rails app. It functions as a tooltip. When the user hovers over the link: It displays some helper text.

If the user accidentally clicks the tooltip: I do not want the default behavior of jumping to the top of the page. I know with javascript I could preventDefault, but is there an easy rails way to get this same behavior?

I was thinking of remote: true but it still jumps to the top of the page.

Code:

<%= link_to "#", title: 'my helper text', remote: true do %>
  <i class="fa fa-question-circle"></i>
<% end %>

Solution

  • Using an empty anchor will result in scrolling to the document start, as you've experienced. Specifying a non-existent anchor, however, will result in no change in scroll position. For example:

    <a href="#doesnotexist">Stay Here</a>
    

    This will still change the document URL and the browser history, though, which is a worse user experience.

    For links that shouldn't change the page, such as those handled via JS, you should absolutely use progressive enhancement and prevent the browser action in JS with the most appropriate method (e.g., return false or e.preventDefault).

    If you have tooltips that should not actually link anywhere, perhaps it would be best to change them into another inline element, such as span.