Martin
Martin

Reputation: 305

How to use Ajax links with anchors in Rails

I'm trying to create a nav panel that uses AJAX to switch between pages, and can link to anchors on those pages in a Rails 5.1 app.

From what I've read, the following code should work, but doesn't.

<%= link_to @section.title, from_nav_path(@topic, anchor: @section.css_id), remote: true %>

(If it isn't clear already, Topic has_many sections, and Section belongs_to Topic)

I've read through, this stackoverflow post, as well as these two reference pages (api doc, and mix and go).

When it's not setup as remote: true it works fine through the show action, but I don't want to reload the page.

Currently, it does change to the correct page, but it just stays at the top of the page, rather than following the anchor. What am I missing to make this work?

I have also tried adding a javascript callback independently and jointly to the partial to be loaded and the from_nav.js.erb file. All to no avail.

Upvotes: 1

Views: 424

Answers (1)

Artem Dorodovskyi
Artem Dorodovskyi

Reputation: 679

You can not use anchor option with remote. An anchor is a piece of text which marks the beginning and/or the end of a hypertext link. But remote is a helper method in Rails that add to tag data-remote="true" attribute and then Rails know that need to send XHR request. Anchor not working with XHR requests. So, you can add javascript in your from_nav.js.erb to scroll to the element

var elmnt = document.getElementById("<%= @section.css_id %>");
elmnt.scrollIntoView();

Upvotes: 1

Related Questions