HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Check what items are on-screen

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
whatareitemsscreencheck

Problem

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 >= 0; i--) {
      var element = elements[i],
        bounds = element.getBoundingClientRect();
        if( bounds.top+margin  0 ){
          inViewport.push(element);
        }
    }
    return inViewport;
  }

Solution

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  0


This is better:

0 < bounds.bottom - margin && bounds.top + margin < window.innerHeight

Code Snippets

if (elements.constructor !== Array) { 
    elements = [elements]; 
}
bounds.top+margin < window.innerHeight && bounds.bottom-margin > 0
0 < bounds.bottom - margin && bounds.top + margin < window.innerHeight

Context

StackExchange Code Review Q#97295, answer score: 3

Revisions (0)

No revisions yet.