user1207524
user1207524

Reputation: 369

show/hide div using scrollTop

I'm trying to create a script which would show div if 500px < scrollTop < 800px otherwise it would be hidden. So if my scroll is from 0 to 500 and from 800 and more it is hidden and between 500 and 800 it is shown. I'm new to javascript but this is what I have tried:

$(document).ready(function(){ 

$(window).scroll(function(){
    if ($(this).scrollTop() > 500) {
        $('.myDiv').fadeIn();
    } else {
        $('.myDiv').fadeOut();
    }
    if ($(this).scrollTop() > 800) {
        $('.myDiv').fadeOut();
    }
});

However after scrolling to 800 it bugs and starts endlessly hiding and showing. Any way to fix it please?

Upvotes: 1

Views: 8357

Answers (1)

SSH This
SSH This

Reputation: 1929

$(window).scroll(function(){

    if ($(this).scrollTop() > 800) {
        $('.myDiv').fadeOut();
    }
    else {
       if ($(this).scrollTop() > 500) {
           $('.myDiv').fadeIn();
       } else {
           $('.myDiv').fadeOut();
       }
    }

});

Upvotes: 6

Related Questions