How to show a div with scrollTop after certain pixels?

Asked

Viewed 205 times

0

I have a div (Fixed) that appears when the page is scrolled down and reappears when the page is scrolled up. I need it to just disappear (when rolling down) from the body’s 45px. That is, while the user only rolls 44.9px it does not disappear and, from that, yes.

Here my example:

var position = $(window).scrollTop(); 

// should start at 0

$(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if(scroll > position) {
        console.log('scrollDown');
        $('.a').addClass('mostra');
    } else {
         console.log('scrollUp');
         $('.a').removeClass('mostra');
    }
    position = scroll;
});
body {
    height: 2000px;  
    background: orange;
}
.a {
    height: 50px;
    width: 50px;
    background-color: green;
    position: fixed;
    top: 0;
    transition: 0.5s;
}
.mostra {
  top: -50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="a"></div>

2 answers

1

You can do what you want with css only, but it won’t work in very old browsers (but nobody cares, the important thing is to run on Chrome).

Here’s a tip in case someone needs it:

body {
    height: 2000px;  
    background: orange;
}
.a {
    height: 50px;
    width: 50px;
    background-color: green;
    /*Position Sticky é quem faz a mágica*/
    position: sticky;
    top: 0;
    transition: 0.5s;
}
.mostra {
  top: -50px;
}
<div class="a"></div>

Here is the list of compatible and incompatible browsers: https://caniuse.com/#feat=css-Sticky

https://www.w3schools.com/howto/howto_css_sticky_element.asp

  • Interesting, I didn’t know...

  • but I don’t understand how it works very well. how/where to determine which style changes when rolling?

  • Interesting. I didn’t know it either. But it doesn’t compete with the question: "I need it to just disappear (when rolling down) from the body’s 45px. That is, while the user only rolls 44.9px it does not disappear and, from that, yes."... That way she doesn’t "disappear"...

0


Based on your code, I did so and it worked:

var position = $(window).scrollTop();

// should start at 0

$(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if(scroll > position) {
        console.log('scrollDown');
        if(position > 45) {
            $('.a').addClass('mostra');
        }
    } else {
         console.log('scrollUp');
         $('.a').removeClass('mostra');
    }
    position = scroll;
});
body {
    height: 2000px;  
    background: orange;
}
.a {
    height: 50px;
    width: 50px;
    background-color: green;
    position: fixed;
    top: 0;
    transition: 0.5s;
}
.mostra {
  top: -50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div class="a"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.