patternjavascriptMinor
Check what items are on-screen
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:
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:
This is better:
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 0This is better:
0 < bounds.bottom - margin && bounds.top + margin < window.innerHeightCode Snippets
if (elements.constructor !== Array) {
elements = [elements];
}bounds.top+margin < window.innerHeight && bounds.bottom-margin > 00 < bounds.bottom - margin && bounds.top + margin < window.innerHeightContext
StackExchange Code Review Q#97295, answer score: 3
Revisions (0)
No revisions yet.