1

I want to hide my sticky button when the slider or footer is being in view when scrolled upon.

I tried this code:

$(window).scroll(function() {
    if ($(this).scrollTop() < 250) { 
        $("#sticky-button").css({
            'display': 'none'
        });
    }
});

So what this does is to hide my sticky button when it is below 250px scroll height.

But on mobile, I realise it doesn't work as 250px in mobile is quite a huge height.

So how to do this by making it work upon a certain div (like: #slider, #footer) instead of setting that 250 height?

Carsten Løvbo Andersen
  • 22,170
  • 9
  • 42
  • 67

1 Answers1

1

You should check the element for its position using .offset().top

$(window).scroll(function() {
        var elemOffsetTop = $('#slider').offset().top;
        if ($(this).scrollTop() > elemOffsetTop ) { 
            $("#sticky-button").css({
                'display': 'none'
            });
        }else{
          $("#sticky-button").css({
                'display': 'block'
            });
        }
        
    });
#sticky-button{
  position: fixed;
  top:0;
  left:0;
  width: 100px;
  height: 100px;
  background-color: blue;
}
.section{
  width: 100%;
  height: 200px;
  border: 2px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="sticky-button"></div>
<div class="section"></div>
<div class="section"></div>
<div id="slider" class="section">slider</div>
<div class="section"></div>
<div class="section"></div>
<div class="section"></div>
Ram Segev
  • 2,321
  • 2
  • 9
  • 23