search

Home  >  Q&A  >  body text

The element must disappear when the page nears the end

I have this JS code for adding and removing classes when scrolling down from the top of the page, but what I want to do is disappear when you get near the end of the page or go back and revert to the old state after some scrolling (eg, From right: 7px to right: -150px). I copied the same JS code and changed scrollTop > rollBottom but it doesn't work.

jQuery(document).on('scroll', (e) => {
  if (document.body.scrollTop > 120 || document.documentElement.scrollTop > 350) {
    console.log('now');
    jQuery('.ast-below-header-bar').addClass('filterr');
  } else {
    console.log('no');
    jQuery('.ast-below-header-bar').removeClass('filterr');
  }
})
body {
  height: 500vh
}

.ast-below-header-bar {
  display: grid;
  position: fixed;
  right: -150px;
  top: 14%;
  background: red;
  height: 200px;
  width: 200px;
  transition: .3s;
}

.ast-below-header-bar.filterr {
  right: 7px!important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ast-below-header-bar"></div>

P粉463418483P粉463418483240 days ago364

reply all(1)I'll reply

  • P粉512526720

    P粉5125267202024-03-30 17:50:01

    You can use window.innerHeight to perform calculations at the bottom of the scroll.

    Adjust to your needs.

    jQuery(document).on('scroll', (e) => {
      if ((window.innerHeight + window.pageYOffset + 350) <= document.body.offsetHeight && document.documentElement.scrollTop > 350) {
        console.log('now');
        jQuery('.ast-below-header-bar').addClass('filterr');
      } else {
        console.log('no');
        jQuery('.ast-below-header-bar').removeClass('filterr');
      }
    })
    body {
      height: 500vh
    }
    
    .ast-below-header-bar {
      display: grid;
      position: fixed;
      right: -150px;
      top: 14%;
      background: red;
      height: 200px;
      width: 200px;
      transition: .3s;
    }
    
    .ast-below-header-bar.filterr {
      right: 7px!important;
    }
    sssccc
    

    reply
    0
  • Cancelreply