How to show a div between the scroll height of 900-1200?

Viewed 101

I am trying to make one CTA as a image, which will appear on some certain height and will disappear once a users crosses that scroll amount.

my codes-

$(document).scroll(function() {
  var y = $(this).scrollTop();
  if (y > 900) {
    $('.cta-bg').fadeIn();
  } else {
    $('.cta-bg').fadeOut();
  }

});
.wrapper {
  height: 3000px;
}

.cta-bg {
  display: none;
  position: sticky;
  bottom: 10%;
  top: 60%;
  width: 60%;
  height: auto;
  z-index: 1;
}

@media only screen and (max-width: 767px) {
  .cta-bg {
    display: none !important;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="cta-bg"><img src="https://via.placeholder.com/150" class="img-fluid"></div>
</div>

It's coming after a scroll amount of 900 but I want to make it disappear again at scroll amount of 1200, please guide me.

1 Answers

I see in your question you said it's coming after 900 but don't disappear after 1200. Basically you only need to use and operator && in your if statement, if your y is between 900 and 1200 your image will fadeIn else will fadeOut, also you can change that limit ( 1200 ) by your preference.

$(document).scroll(function () {
    var y = $(this).scrollTop();
    if (y > 900 && y < 1200) {
        $('.cta-bg').fadeIn();
    } else {
        $('.cta-bg').fadeOut();
    }

});
.wrapper {
  height: 3000px;
}

.cta-bg {
  display: none;
  position: sticky;
  bottom: 10%;
  top: 60%;
  width: 60%;
  height: auto;
  z-index: 1;
}

@media only screen and (max-width: 767px) {
  .cta-bg {
    display: none !important;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="cta-bg"><img src="https://via.placeholder.com/150" class="img-fluid"></div>
</div>

Related