Search code examples
javascriptjqueryhtmljs-scrollintoview

Function scrollIntoView doesn't work


I have a little problem with my function scrollIntoView. Indeed, it doesn't work :(

This is my code:

  • HTML

    <section class="page_mission">
      <div class="page_mission_text">
        <div class="scroll-animations">
          <div class="animated fadeInLeft">
            <h2>Design <i class="fab fa-css3-alt"></i><i class="fab fa-html5"></i></h2>
            <p>Blablabla<br></p>
          </div><hr style="width: 75%;">
          <div class="animated">
            <h2>Modernité <i class="fas fa-dna"></i></h2>
            <p>Blablabla</p>
          </div><hr style="width: 75%;">
          <div class="animated">
            <h2>Coûts <a href="cost_popup.html" class="ajax-popup-link"><i class="far fa-credit-card"></i></a></h2>
            <p>Blablabla</p>
          </div>
        </div>
      </div>
    </section>
    
  • JS

    $(document).ready(function() {
       function isScrolledIntoView(elem) {
           var docViewTop = $(window).scrollTop();
           var docViewBottom = docViewTop + $(window).height();
    
           var elemTop = $(elem).offset().top;
           var elemBottom = elemTop + $(elem).height();
    
           return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
        }
    
        $(window).scroll(function() {
            $('.scroll-animations .animated').each(function() {
                if (isScrolledIntoView(this) === true) {
                    $(this).addClass('fadeInLeft');
    
                }
        });
    });
    

Does someone have an idea what's wrong? Thanks a lot!


Solution

  • It appears to me the fadeInLeft class is being added on scroll as expected. You do, however, need an additional closing curly brace and closing parentheses to close your document ready event handler:

    $(document).ready(function() {
    
      function isScrolledIntoView(elem) {
    
      var docViewTop = $(window).scrollTop();
    
      var docViewBottom = docViewTop + $(window).height();
    
      var elemTop = $(elem).offset().top;
    
      var elemBottom = elemTop + $(elem).height();
    
      return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
      }
    
      $(window).scroll(function() {
    
        $('.scroll-animations .animated').each(function() {
    
          if (isScrolledIntoView(this) === true) {
    
            $(this).addClass('fadeInLeft');
    
          }
    
        });
      });
    
    }); // This was missing
    

    JSFiddle

    You also need to make sure to load jQuery before your JavaScript executes. The easiest way is to place something like this in the page's <head> element:

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>