0

How can I detect if I am currently on my home page?
For example, I only want this JS to execute if I am on my landing page, which is:

app/views/pages/home.html.erb

Is there a way to write this in rails like root_path?

Here's my Javascript:

var landingPage = root_path; // What should this variable here be?

function updateNavStyle() {
  if(landingPage.length == 0 || location.href.toLowerCase().indexOf(landingPage.toLowerCase()) >= 0) {
    var offset = $('#change_color').offset();
    var scroll_start = $(document).scrollTop();
    if (scroll_start > offset.top) {
      // the white normal navbar
      $(".navbar-add").removeClass("navbar-trans");
      $(".navbar-link-text").removeClass("navbar-link-white");
    } else {
      // what the users sees when he lands on the page
      $(".navbar-add").addClass("navbar-trans");
      $(".navbar-link-text").addClass("navbar-link-white");
    }
  }
}
WQ.Kevin
  • 319
  • 3
  • 13
  • 1
    Why not just have a `` located only on your landing page? Meaning the function could exist statically in your resources for all pages, but only on your landing page would it be invoked. – Taplar Jul 21 '17 at 17:27
  • Because I tried doing it this way but its not working like when I write this seperately – WQ.Kevin Jul 21 '17 at 17:42
  • Then I would think the question should be more revolving around figuring out why that didn't work. – Taplar Jul 21 '17 at 17:43

2 Answers2

1

if you using javascript you can check each page load by checking turbolinks:load event and check "class name" that generated automatically by rails constructed from controller and method

below is sample for example if rails load post controller with edit method

$(document).on("turbolinks:load", function() {
  if ($(".posts.edit")[0] == true) {
    return something;
  }
});

and here is if coffeescript sample

$(document).on "turbolinks:load", ->
  if $(".posts.edit")[0]
    # do something 
widjajayd
  • 6,090
  • 4
  • 30
  • 41
0

<%= javascript_include_tag "my_javascipt_file" %>

add this to bottom of your

app/views/pages/home.html.erb

more you can look here

or just put the script in

app/views/pages/home.html.erb

with script tag of course <script>your jquery code </script>

buncis
  • 2,148
  • 1
  • 23
  • 25