How to show a div with scrollTop after certain pixels?

0

I have a (fixed) div that appears when the page is scrolled down and reappears when the page is scrolled up. I need it to just disappear (when it scrolls down) from 45px of the body. That is, as long as the user only rolls 44.9px it does not add up and, from that, yes.

Here is 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><divclass="a"></div>
    
asked by anonymous 07.12.2018 / 04:32

2 answers

0

Based on your code, I did it 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><divclass="a"></div>
    
07.12.2018 / 05:24
1

It is possible to do what you want with just css, however, it will not work in very old browsers (but nobody connects, the important thing is to run in chrome).

Here's the tip if 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: link

  

link

    
07.12.2018 / 11:43