fuyiii
fuyiii

Reputation: 33

JS - how to remove setTimeOut for my code

I am trying to use vertical scroll to display an object A. The idea is that if my scroll height is greater than scrollHeight (15), then after 1.2 second, A will show up. Then when I scroll back to top, A will hide.

The problem right now is that if I dont use clearTimeout, the setTimeout will ignore the condition: if ( scroll >= scrollHeight )

When I use clearTimeout, it seems it only works when I scroll very quickly or it just doesnt work.

Here is my code.

var scrollHeight = 15;

$(window).scroll(function() {
    var scroll = getCurrentScroll();
    var delayThis;

    if ( scroll >= scrollHeight ) {
        delayThis = setTimeout(function(){

        //Display **A**... 

        }, 1200);

       }
       else{
        // Hide **A** ...
        clearTimeout(delayThis);
        }
  }

Thank you very much for helping!!

Upvotes: 3

Views: 387

Answers (2)

Ricardo Nuñez
Ricardo Nuñez

Reputation: 989

You have to tell the script if the message is already showing or not, that way you avoid the multiple delays. Below is a working version of what I'm talking about. I hope that helps.

var scrollHeight = 15;
var message = $( ".message" ); 
var messagestatus = false;
var scrollposition;

$(window).scroll(function() { 
    scrollposition = $(document).scrollTop();
    
    if ( scrollposition >= scrollHeight ) {
        if ( messagestatus == false ) {
            setTimeout(function(){

                message.show();
                messagestatus = true;
                
            }, 1200);
        }

    } else{
        message.hide();
        messagestatus = false;
    } 
});
.message {
    display: none;
    position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>top</p>
<div class="message">
    Show!
</div>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> <br /><br /><br /><br /><br />
<p>bottom</p>

Upvotes: 1

Jason Byrne
Jason Byrne

Reputation: 1619

You need to put delayThis outside of the event, up with scrollHeight. Because otherwise it no longer exists. Right now you have it where it is only local to that one scroll event... not the proceeding ones.

Also... you would be setting the timeout over and over as you scroll. So before setting it you probably want to be make sure that delayThis is not already set.

Upvotes: 0

Related Questions