0

I'm styling something using the following code:

$( document ).ready(function(){
  $("div.event").closest('td').addClass('success');

This works great on first loading the page, but when I navigate back to the page or am redirected by a controller (this app is on Rails), the class has left the element.

For some context, this app renders events inside of a calendar styled table. The intention is to highlight the table td if there is an event inside of it.

Any insights how I can get it to persist would be appreciated.

  • Yes. What's up with that? –  Jan 20 '15 at 22:31
  • possible duplicate of [Cross-browser onload event and the Back button](http://stackoverflow.com/questions/158319/cross-browser-onload-event-and-the-back-button) – Travis J Jan 20 '15 at 22:33
  • according to the [documentation](https://github.com/rails/turbolinks): "With Turbolinks pages will change without a full reload, so you can't rely on DOMContentLoaded or jQuery.ready() to trigger your code. Instead Turbolinks fires events on document to provide hooks into the lifecycle of the page." – scrappedcola Jan 20 '15 at 22:33
  • 1
    The duplicate indicates that using `history.navigationMode = 'compatible';` should solve this problem. The reason that ready doesn't fire is because the page has been stored in the bfcache. – Travis J Jan 20 '15 at 22:34

1 Answers1

2

Using turbolinks, instead of:

$( document ).ready(function(){

Use:

$(document).on("ready page:change", function() {

But this should only contain idempotent code.

I encourage you to check all events on the github page.

apneadiving
  • 110,730
  • 25
  • 209
  • 207
  • When a page is loaded from the bfcache, the load event does not fire. – Travis J Jan 20 '15 at 22:34
  • @TravisJ this is intended, all non idempotent stuff should only be triggered once, and their result is cached – apneadiving Jan 20 '15 at 22:35
  • Which is to say that `.on("ready page:load"` will only fire once on the first page load, and not when the back button is pushed. – Travis J Jan 20 '15 at 22:38
  • This works, but @TravisJ Your suggestion above of using `history.navigationMode = 'compatible';` also works. –  Jan 20 '15 at 22:47