Check what items are on-screen This function takes an array of HTML objects and returns those currently on the screen. I try to optimize for readability and performance. I myself find this function a bit confusing.

function(elements, margin) {
    var inViewport = [];

    if(elements.constructor !== Array){ elements = [elements]; }
    margin = margin || 0;

    for (var i = elements.length - 1; i &gt;= 0; i--) {
      var element = elements[i],
        bounds = element.getBoundingClientRect();
        if( bounds.top+margin &lt; window.innerHeight &amp;&amp; bounds.bottom-margin &gt; 0 ){
          inViewport.push(element);
        }
    }
    return inViewport;
  }
For improved readability, this writing style is generally recommended:

if (elements.constructor !== Array) { 
    elements = [elements]; 
}


In conditions with range checks, it's a good practice to organize the elements of the condition by increasing numerical order. So instead of this:


bounds.top+margin &lt; window.innerHeight &amp;&amp; bounds.bottom-margin &gt; 0



This is better:

0 &lt; bounds.bottom - margin &amp;&amp; bounds.top + margin &lt; window.innerHeight