nateM
nateM

Reputation: 662

Rails link_to with params and anchor

I have the following link_to on my products index page, which essentially reloads the current page with a :tag parameter. This works just fine. However, when I include an anchor attribute, the page no longer reloads, the user is just taken to the anchor within the page (the page does not reload with the given :tag param)

<%=  link_to('Foo',
          products_path(:tag => 'bar', anchor: 'foo-anchor'),
          class: 'btn black-btn')
%>

When I inspect the link, the href looks like domain.com/products?tag=bar#foo-anchor. This seems fine, however because I think I'm already on domain.com/products the page does not refresh, it only takes you to the anchor. How can I get the page to reload with the given param, and THEN take the user to the anchor?

Upvotes: 1

Views: 1059

Answers (1)

michalvalasek
michalvalasek

Reputation: 1573

This is how HTML links work. If you have a link that leads to an anchor on the current page, the page won't reload, just scroll to the anchor position. If you want to force the page to reload, you may call window.location.reload(); when the link is clicked - e.g. add some class to the link and add a click handler like this:

$('a.force-reload').on('click', function(){ 
  window.location.href = $(this).attr('href');
  window.location.reload();
});

Upvotes: 1

Related Questions