1
\$\begingroup\$

This function receives an HTMLElement as an argument and returns true if the tag is on the screen and false otherwise.

function isTagVisible(tag) {
    var box;

    box = tag.getBoundingClientRect();

    if (box.left > 0) {
        if (box.left >= window.innerWidth) {
            return false;
        }
    }

    if (box.right <= 0) {
        return false;
    }

    if (box.top > 0) {
        if (box.top >= window.innerHeight) {
            return false;
        }
    }

    if (box.bottom <= 0) {
        return false;
    }

    return true;
}
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$
if (box.left > 0) {
    if (box.left >= window.innerWidth) {
        return false;
    }
}

This seems a little redundant: the innerWidth is going to be greater than 0, so why do you need to conditionals?

Simply remove the outer one.


Your conditions are fairly short. Consider combining them:

if (box.right <= 0 || box.bottom <= 0) {
    return false;
}

if (box.left >= window.innerWidth || box.top >= window.innerHeight) {
    return false;
}

There isn't much more to say about your code, but I have an idea for future improvement: right now, your code will say true even if the element is partially hidden on the screen. How do you plan on handling this?

\$\endgroup\$
1
  • \$\begingroup\$ I intended to return true even when the element is partially hidden. Thanks for your feedback. \$\endgroup\$ Commented Nov 28, 2015 at 10:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.