简体   繁体   中英

Make div appear while scrolling within a specific range on web page

I would like a div to appear when the user scrolls to a specific place on the page (900 pixels down) and then disappear at a specific place (1800 pixels down). I have a solution which works, however it breaks when the user scrolls back up, past the initial appear point (900 pixels from top).

At that point it does not go away again. So to summarize, I need assistance modifying my code to make the div disappear again after passing the original point it appeared at.

Here is a link to my test page: http://jltest.biz/test-1

Below is my code:

var startY = 900;
var stopY = 1800;

$(window).scroll(function(){
    checkY();
});

function checkY(){
    if( $(window).scrollTop() > startY ){
         if( $(window).scrollTop() > stopY ){
         $('.fixedDiv').fadeOut("slow");
   }
   else
   {  $('.fixedDiv').fadeIn("slow"); }
}
}

checkY();

Thank you for your time!

You have error with your login in the if statement and that caused it not to work check this out

var startY = 900;
var stopY = 1800;

$(window).scroll(function(){
    checkY();
});

function checkY()
{
    console.log($(window).scrollTop()); 
    if($(window).scrollTop() > startY && $(window).scrollTop() <= stopY)
    {    
         $('.fixedDiv').fadeOut("slow");
    }
    else
    {

         $('.fixedDiv').fadeOut("slow");
    }
}

checkY();

Check this too http://jsfiddle.net/gLWxF/

I hope this can help :)

instead of $(window).scrollTop() > startY use $(window).scrollTop() >= startY sometimes when you scroll fast it may skip a number.

This insures that if it is greater than or equal to startY

The fadeout method should be triggered when the scroll point is before the start position right? So I think you need to change your operator around as below.

function checkY(){
    if( $(window).scrollTop() < startY ){
         if( $(window).scrollTop() > stopY ){
         $('.fixedDiv').fadeOut("slow");
   }
   else
   {  $('.fixedDiv').fadeIn("slow"); }
}

just do that

 <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> var startY = 900; var stopY = 1800; $(window).scroll(function(){ checkY(); }); function checkY() { console.log($(window).scrollTop()); if($(window).scrollTop() > startY && $(window).scrollTop() <= stopY) { console.log("Show"); $('.foxedDiv').show(); } else { console.log("Hide"); $('.foxedDiv').hide(); } } checkY(); </script> <style> body { background:red; height:3000px; } .foxedDiv { display:none; position:fixed; top:50px; right:10px; } </style> </head> <body > <div class="foxedDiv" > {loadposition moving} <br> </div> </body> </html> 

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