How can I use the link_to
helper to make a link without an href
attribute? I want to make a link exclusively for a javascript action, I don\'t want
I use this approach:
= link_to('Click me', 'javascript:;', :id => :foo)
Its basically a Javascript no-op
An example for rails 5 would be:
<%= content_tag("a", image_tag("/logo.png"), class: "navbar-brand") %>
This would render as:
<a class="navbar-brand"><img src="/logo.png" alt="Logo"></a>
This is similar to niels' answer but with a nested image_tag
and a class.
Source: Rails API
I prefer using plain HTML without href
attribute at all in such cases:
<a data-toggle="modal" data-target="#myModal">Open dialog</a>
IMHO it is more readable than content_tag("a","link text")
.
href=#
is that the browser will scroll to the top
when clicked by defaultjavascript:;
looks uglyI think you're better off using a button in situations where there is no href.
<button class='button'>Hello</button>
You can also use a
content_tag("a","link text")
which gives you
<a>link text</a>
See: rails api
An alternative is
= link_to("My hyperlink", "#")
This will give you a link that when clicked, does not reload the page like passing in nil. At the same time, it will set the mouse to pointer on mouseover, which you will not get with the content_tag approach.