title: jQuery - Detecting if element is in viewport
body: <p>I am writing a script that gives different elements some animations when they appear in the screen.</p>
  
  <p>Step one would be to detect when they come in the screen. But that doesn't seem to work.</p>
  
  <p>What I tried:</p>
  
  <p>-The <code>.visible()</code> selector, I quickly found out this does something else in jQuery.</p>
  
  <p>-Different plugins, but I found that they do way more then I need, therefore I decided to write/ find something myself.</p>
  
  <p>-My current script (I found it somewhere in a forum and decided to edit it to my needs) But It works a little strange.</p>
  
  <pre><code>$.fn.isInViewport = function () {
      let elementTop = $(this).offset().top;
      let elementBottom = elementTop + $(this).outerHeight();
  
      let viewportTop = $(window).scrollTop();
      let viewportBottom = viewportTop + $(window).height();
  
      return elementBottom &gt; viewportTop &amp;&amp; elementTop &lt; viewportBottom;
  };
  
  $(window).scroll(function () {
      if ($('.blogcard ').isInViewport()) {
          $(this).addClass("test");
          console.log('success.')
      } else {
          console.log('No success.')
      }
  });
  </code></pre>
  
  <p>Unfortunately this doesn't seem to add a class to my <code>&lt;div class='blogcard'&gt;</code>.</p>