Home » Jquery » jquery – How to fade text in and out on scroll when using offsetTop?-Exceptionshub

jquery – How to fade text in and out on scroll when using offsetTop?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

This may seem straight forward but have tried so many things to get this working! I tried to implement this plugin https://michalsnik.github.io/aos/ but doesn’t work when the parent element has an overflow: hidden. Also, I would prefer not to use a plugin. It is more of an issue with syntax and how to add the fade in / fade out on the divs as they enter the viewport.

What I need to work out is what is the correct code i.e

$('.parent-div').stop().animate({
   scrollTop: sections[i].offsetTop, opacity: 1 - $('.parent-div').scrollTop - 50
}, 2000);

The option to add a class / remove a class would also be fine. I have tried a lot of the other similar questions on here but can not find an example with offsetTop. Really would appreciate some help on this. Thank you in advance.

var sections = $('.child');
var i = 0;

function next() {

  if (i < sections.length - 1) {
    i++;

    $('.parent-div').stop().animate({
      scrollTop: sections[i].offsetTop
    }, 2000);

    $('#' + sections[i].id).addClass('fadein_content');
  } else {
    
    $('.child').removeClass('fadein_content');
  }
}

function prev() {

  if (i > 0) {
    i--;
    $('.parent-div').stop().animate({
      scrollTop: sections[i].offsetTop
    }, 2000);

    $('#' + sections[i].id).addClass('fadein_content');
  }
}

$('.parent-div').bind('mousewheel', function(e) {
  if (e.originalEvent.wheelDelta / 120 > 0) {
    
    prev();
  } else {
    
    next();
  }
});
section {
  position: relative;
  height: 900px;
  overflow: hidden;
}

.parent-div {
  height: 500px;
  overscroll-behavior: contain;
  overflow-y: scroll;
  scrollbar-width: none;
  -ms-overflow-style: none;
  position: relative;
  margin-top: 7%;
  width: 100%;
}

.child {
  position: relative;
  height: 100%;
  opacity: 1;
  text-align: center;
  padding: 5%;
}

.fadein_content {
  -webkit-animation: fadein 2s;
  -moz-animation: fadein 2s;
  -ms-animation: fadein 2s;
  -o-animation: fadein 2s;
  animation: fadein 2s;
}
::-webkit-scrollbar { 
     width: 0px !important; 
     background: transparent;
     height: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<section>
  <div class="parent-div">
    <div id="one" class="child">Some content to fade in and out on scroll</div>
    <div id="two" class="child">Some content to fade in and out on scroll</div>
    <div id="three" class="child">Some content to fade in and out on scroll</div>
    <div id="four" class="child">Some content to fade in and out on scroll</div>
    <div id="five" class="child">Some content to fade in and out on scroll</div>
  </div>
</section>
How to&Answer: