简体   繁体   中英

Page Specific Javascript Not Working

I am building a rails app and in order to have page specific app.

I have added this to the bottom of my index.html.erb for my PagesController :

<script> </script>

The code sets the navbar opacity to 0 if it is at the top, but somehow this also shows up in the new.html.erb for my contactcontroller .

Any idea on how this is happening?

$(document).ready(function() {

    $(window).scroll(function() { /* run on load */

        if ($('.nav-fixed-top').css("opacity") == 0) {
            $('.nav-fixed-top').fadeTo(500, 1); /* fadeIn if not visible */
        } else {
            if ($(window).scrollTop() === 0) {
                $(".nav-fixed-top").fadeTo(500, 0);
            }

        };
    });
});

This is at the bottom of my index.html.erb for my PagesController . But it also seems to be getting called in new.html.erb for my ContactController .

I can't speak as to why exactly that's happening within a script tag, but I do know that it is a best practice to use as few tags as you possible can in a Rails application. What I would do to resolve this issue is to put that in the pages.js file and use this -

var new_page_regex = new RegExp(/pages\/new/);

if(new_page_regex.test(window.location.pathname) {
  /* your code here*/
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM