简体   繁体   中英

How to make a jquery function run when a div is displayed on the screen

In Short: I am working on a project and I want to run a function when a particular div is displayed on the screen.

Detail: There is a scroll to top button fixed on the bottom right of the screen in my template. I want to hide that button when someone scroll down to the footer. Means when someone scroll down to the footer and the top border of the footer is displayed on the screen, I want a function to run which would hide the go to top button.

Please help me out of this problem...

$(document).ready(function() {
     var footer = $("footer");
     var f_top = footer.position().top;
      $(window).scroll(function() {
           if ($(window).scrollTop() + $(window).height() >= f_top ) {
                footer.hide();          
           }
           else{
              footer.show();          
           }
       });
    }); 

Initialize the window to monitoring its scrolling

$(document).ready(function () {
    $(window).scroll(function () {
        // get the element that you want check scrolling on it
        var off = $("your-selector").offset().top; 
        var top = $(window).scrollTop() + $(window).height();
        if (off <= top) {
            // do your job
            // for example you can call a function like:
            my_method_to_invoke();
        }
    });
});

The function you want to invoke it:

function my_method_to_invoke() {
    // TODO
}

I think you'll need to register a scroll listener on the body that checks to see if the footer is in view and perform the hide if so. Something like this...

$(body).scroll(function () {
scrollCheck();
});

var scrollCheck = function () {
    var docTop, docBot, elemTop, elemBot;

    docTop = $(window).scrollTop;
    docBot = docTop + $(window).height();
    elemTop = $(<footer element>).offset().top;
    elemBot = elemTop + $(<footer element>).height();

    if ((elemBottom >= docTop) && (elemTop <= docBot)) {
         $(<button element).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