Rogue
Rogue

Reputation: 83

Why does JS only load whenever the page is first time loaded or refreshed?

I have had this problem for a while whenever i builds Rails apps. Basically what happens is that every time you load the app and you have some sort of javascript code wether it's a tooltip or a datepicker it will only load it the first time you open the page or until you refresh the page

So lets say you decide to visit the Services pages and you want to choose a date with the following code

$(document).ready ->
   $("[data-behaviour~=datepicker]").datepicker(
   todayBtn: "linked", 
   todayHighlight: true, 
   startDate: "(Time.current, :format => :datepicker)"
   format: "yyyy/mm/dd"
)

This code will load fine on first page load or until the page is refreshed, however if you go back and forth between pages the code for some reason won't load. As in the datepicker won't appear again until you refresh the page.

This happens in both dev and production. Anyone know whats up and care to explain please? Am i doing something wrong?

And no, the code doesn't go in application.js but rather in a seperate .js file and then gets called from application.js via the require tree i presume.

Upvotes: 0

Views: 385

Answers (1)

EasyCo
EasyCo

Reputation: 2036

This is due to Turbolinks ajax'ifying your links so the ready event only gets triggered on first page load.

TL;DR

You can use $(document).on "page:change", -> instead of $(document).ready ->

How Turbolinks works

Turbolinks attaches a click handler to all on the page. If your browser supports PushState, Turbolinks will make an Ajax request for the page, parse the response, and replace the entire of the page with the of the response. It will then use PushState to change the URL to the correct one, preserving refresh semantics and giving you pretty URLs

Reference: http://guides.rubyonrails.org/working_with_javascript_in_rails.html

Upvotes: 1

Related Questions