2

When my page loads for the first time the code in /assets/javascript/home.js executes, which positions my navbar using Bootstraps affix.

$('.navbar').affix({
  offset: {
    top: function() {
      return this.bottom = $('.hero').outerHeight(true);
    }
  }
});

When I go to another route such as /blog, I don't want this code to execute and want my static CSS to render which works great. The problem is when I got back to the home route(/), the JavaScript doesn't execute again and my navbar is using its natural CSS. If I refresh at this point, the page will reload fully and my navbar will be positioned correctly.

I think the problem is because of turbo-links but I am not experienced enough with Rails to resolve this issue. Hope somebody can shed some light!

Luca
  • 21
  • 4
  • Found solution from this stack overflow post http://stackoverflow.com/questions/18770517/rails-4-how-to-use-document-ready-with-turbo-links – Luca Jul 11 '15 at 20:48

1 Answers1

0

If you're using turbolinks, you can do something like this:


$(function() {
  if (window.location.pathname === '/') {
    // run your code
  }
});

Turbolinks changes the $(fn) (which is a shortcut to $(document).ready ) to run after changing to other path, so it'll run this code on each path change.

Roman
  • 13,100
  • 2
  • 47
  • 63
  • I'm not sure if I am using turbolinks. I just know when I created my homecontroller It made a home.js in my assets/javascripts folder. – Luca Jul 11 '15 at 20:28
  • I wrapped my code in your block and it still not executing when i go back to the route. – Luca Jul 11 '15 at 20:29
  • Found solution here http://stackoverflow.com/questions/18770517/rails-4-how-to-use-document-ready-with-turbo-links – Luca Jul 11 '15 at 20:48