简体   繁体   中英

jQuery ready not fired after rails link_to is clicked

im using the javascript below to make an image "fade in" triggered by a scroll event. But the .hide im using to initially hide the image only works when the page loads initially, typing localhost:3000.

Once i'm in the site if i try to click a link to go back to the main page,

<%= link_to 'Main', root_path %>

the main page loads with out the .hide working

Why does the .hide work when the page initially loads but if i click a link to the same page the .hide does not work. the rest of the Javascript works no matter what, i can scroll and the image fades in and out depending on the scroll position, but i need it to start hidden, and that only works when the page loads initially help

function isElementVisible(elementToBeChecked) {
    var TopView = $(window).scrollTop();
    var BotView = TopView + $(window).height();
    var TopElement = $(elementToBeChecked).offset().top + 100;
    var BotElement = TopElement + $(elementToBeChecked).height();
    return ((BotElement <= BotView) && (TopElement >= TopView));
}

$(document).ready(function(){
    $("#ghost_logo").hide();// hide it initially
});    

$(window).scroll(function(){
    isOnView = isElementVisible("#logoDiv");

    if (isOnView) {
        //fade out small image once main logo is in view
        $('#ghost_logo').fadeOut();
    } else {
        //fade in small image once main logo is out of view
        $('#ghost_logo').fadeIn();
    }        
});

You are having a tipical problem with turbolinks, turbolinks make that DOM doesn't change when you navigate through a links, for this reason, the ready event from jQuery is never fired, you can solve this in three ways.

You can try something like:

document.addEventListener('page:load', function(){
    $("#ghost_logo").hide();
});

or if this doesn't work either, try navigate with out turbolinks change a parameter of link:

 <%= link_to 'Main', root_path ,{ :'data-no-turbolink' =>  "true" } %>

or if you want you can use this jQuery-turbolinks gem is a gem provided for solving this kind of issues.

For more information refer to turbolinks repository on github

document.addEventListener('page:load', function(){
    $("#ghost_logo").hide();
});

Is not always working. Better use:

document.addEventListener('turbolinks:load', function(){
    $("#ghost_logo").hide();
});

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