title: Which event to check if element is outside viewport on scroll?
body: <p>I am trying to check if an element is inside my viewport when scrolling.
  If it is outside my viewport, I add a class that fixes the element to the top.</p>
  
  <p>The function I use to determine if the element is outside the viewport is:</p>
  
  <pre><code>isElementInViewport : function(el) {
      //special bonus for those using jQuery
      if (typeof jQuery === "function" &amp;&amp; el instanceof jQuery) {
          el = el[0];
      }
  
      var rect = el.getBoundingClientRect();
  
      return (
          rect.top &gt;= 0 &amp;&amp;
          rect.left &gt;= 0 &amp;&amp;
          rect.bottom &lt;= (window.innerHeight || document.documentElement.clientHeight) &amp;&amp; /*or $(window).height() */
          rect.right &lt;= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
      );
  }
  </code></pre>
  
  <p>I added a scroll event which fires this function :</p>
  
  <pre><code>$(window).on('scroll', function(event){
     testObject.isElementInViewport(event.target);
  }
  </code></pre>
  
  <hr>
  
  <p>The problem here is that while scrolling, my Lenovo Yoga's CPU goes crazy.
  I have tried:</p>
  
  <ul>
  <li><code>polling</code> with an interval</li>
  <li>using a <code>timeout function</code> and a <code>variable outside the event function scope</code> to toggle on a certain interval</li>
  </ul>
  
  <p>Both methods work, but I need a way to minimize performance impacts, because the page I use this in already has LOADS of JS working.
  I also need to fix the bar to top as soon as it gets outside the viewport and not a few milliseconds later.</p>
  
  <p>Are there any low-performance solutions for this?
  Can this be done in CSS only?</p>
  
  <h2>Edit</h2>
  
  <p>I've noticed that I didn't asked my question right.
  The current answers below are working, but give the same HUGE performance impact when I scroll up and down a bit:</p>
  
  <p><a href="https://i.stack.imgur.com/xbAKB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xbAKB.jpg" alt="First answer"></a>
  <a href="https://i.stack.imgur.com/gmJUM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gmJUM.jpg" alt="Second answer"></a></p>
  
  <p>I need to prevent the script from needing so much CPU power!</p>