Rewrite and refactor getVisibleElements() to make it more generic

This PR makes a number of changes to `getVisibleElements`, to make it more generic.
The changes in this patch was prompted by #2660, since that PR won't work as intended with the current implementation of `getVisibleElements`.
This PR also fixes an issue in the current implementation, where the visibility percentage of an element would be negative in some instances.

/cc @brendandahl, since he suggested rewriting `getVisibleElements`.