Reputation: 8511
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 it reloading the page or anything.
When I omit the url parameter, clicking the link reloads the page. Ditto for providing nil
in place of the url.
Upvotes: 43
Views: 31390
Reputation: 1729
You can also use a
content_tag("a","link text")
which gives you
<a>link text</a>
or, from the comment from @cesartalves, with a block:
content_tag("a") do
image_tag("src")
end
See: rails api
Upvotes: 50
Reputation: 371
<%= link_to '+ Add Make', 'javascript:void(0)', id: 'add-make', onclick: 'addMake()' %>
and then your jQuery:
function addMake() {
$.ajax({
url: '/dealers',
type: 'GET',
dataType: 'script',
success: function (data) {
console.log('it was successful')
$('.add-make').hide();
},
error: function (data) {
console.log('it was error')
}
});
}
Upvotes: 3
Reputation: 34603
I think you're better off using a button in situations where there is no href.
<button class='button'>Hello</button>
Upvotes: 2
Reputation: 7246
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 uglyUpvotes: 0
Reputation: 11
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
Upvotes: 1
Reputation: 11703
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.
Upvotes: 2
Reputation: 32748
I use this approach:
= link_to('Click me', 'javascript:;', :id => :foo)
Its basically a Javascript no-op
Upvotes: 43
Reputation: 7023
Set the href to:
javascript:void(0)
This will let you have a link that clicking it does nothing, doesn't reload the page, and doesn't move the page up to the top.
Upvotes: 12