David Sawatske
David Sawatske

Reputation: 111

jQuery `.click` handler not working after return to page with browser back button

I was able to find the answer before posting. Thought I would share the post anyway for future ref.

The issue was the turbolinks gem preventing the JS to be loaded without refreshing the page.

To fix, Remove:

gem 'turbolinks' from Gemfile &

//= require turbolinks from application.js

start of initial question (skip, unless interested in what didn't work)

Rails app using CoffeeScript

I have a page that displays the .project-container div along side of a .profile-click. When .profile-click is clicked the .project-container slides out of the way to show the '.profile-container' div.

This all works perfectly on the initial load or refresh of this page. The .click handlers do not function when the page is 'revisited' after a click of the browser's back button. (the divs targeted by .click are not on the page from which the browser back button is clicked)

Also, this is only an issue if I visit another page within the same app (ie main.com/sub -> browser back clicked -> main.com). Not a problem if the page is 'revisited' after going to another domain.

Hoping to gain some insight in to why this is happening.

$(document).ready ->
  $('.project-overlay').click ->
    $('.project-container').animate 'right': '8.5vw'
    $('.project-overlay').animate 'right': '8.5vw'
    $('.project-overlay').css 'z-index': '0'
    $('.profile-container').fadeOut()
    $('.profile-click').fadeIn()
    return
    
  $('.profile-click').click ->
    $('.project-container').animate 'right': '65vw'
    $('.project-overlay').animate 'right': '65vw'
    $('.project-overlay').css 'z-index': '1'
    $('.profile-container').fadeIn()
    $('.profile-click').fadeOut()
    return
  return

I understand that $(document).ready isn't being fired on the reload (browser caching). This was confirmed by calling alert('ready') which only popped up on the initial load.

what didn't work

I tried to call .ready on a different div container that only exists on the initial page but it gave the same results.

.onpageshow is not working either

Tried to prevent caching in application_controller with no luck.

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :prevent_caching

  protected

  def prevent_caching
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "0"
  end
end

Upvotes: 1

Views: 367

Answers (1)

David Sawatske
David Sawatske

Reputation: 111

The issue was the turbolinks gem preventing the JS to be loaded without refreshing the page.

To fix, Remove:

gem 'turbolinks' from Gemfile &

//= require turbolinks from application.js

Upvotes: 1

Related Questions