bevanb
bevanb

Reputation: 8511

Rails: using link_to to make a link without href

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

Answers (8)

niels
niels

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

Andrey
Andrey

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

stephenmurdoch
stephenmurdoch

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

Artur INTECH
Artur INTECH

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").

  • The disadvantage of href=# is that the browser will scroll to the top when clicked by default
  • javascript:; looks ugly

Upvotes: 0

tordoch
tordoch

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

Aaron Gray
Aaron Gray

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

Cody Caughlan
Cody Caughlan

Reputation: 32748

I use this approach:

= link_to('Click me', 'javascript:;', :id => :foo)

Its basically a Javascript no-op

Upvotes: 43

Solomon
Solomon

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

Related Questions