Explain Codes LogoExplain Codes Logo

Detect if an element is visible with jQuery

javascript
performance
best-practices
promises
Nikita BarsukovbyNikita Barsukov·Jan 21, 2025
TLDR

To check an element’s visibility swiftly, $(element).is(':visible') is our knight in shining armor. This jQuery function checks if the element occupies space on the page, not considering it's opacity or visibility styles.

let isVisible = $('#element').is(':visible'); // Visible or not? That is the question.

true signifies visibility; false indicates hidden, display: none, or an element tucked away inside a hidden parent.

Ensuring performance while checking visibility

Careful while working with :visible or :hidden selectors! These seemingly innocuous selectors can trigger substantial recalculation of CSS styles and page layouts and may affect your page's performance, particularly with a complex DOM structure.

  • Leverage these selectors judiciously and don't hesitate to cache results when used in loops or repeatedly.
  • Always use performance measurement tools (eg. Chrome DevTools) to ensure that the use of :visible isn't hindering your site's speed.
  • With jQuery 3, these checks are significantly faster, but it's still sage advice to be mindful of potential performance blips.

Toggle element visibility like a magician

Sometimes you might want to abracadabra the visibility of an element. That's when .fadeToggle() comes to your rescue. This method gracefully shows or hides elements with a fading effect.

$('#toggleButton').on('click', function() { $('#elementToToggle').fadeToggle(); // Now you see it, now you don't! });

The method doesn't only alter the visibility of your element but also provides a smooth transition, thus enhancing your user's experience.

Beware of the invisibility cloak

A common trap to look out for is that an element will be deemed invisible if it or any of its parent elements possess a display: none style. Thus, when using $(element).is(':visible'), remember this ancestral check:

$('#childElement').is(':visible'); // Returns false if the child or parent has a knack for hide-and-seek

For fuzzier cases where parents can be toggled independently, traverse up the DOM hill using .parents() or .closest(selector) to check each ancestor's visibility.

Various methods to check visibility

Besides .is(':visible'), there exist other routes to check visibility. Here are a few alternatives you might find useful:

Using getBoundingClientRect()

This method is a part of vanilla JavaScript and lets you know if an element is within the viewport.

function isInViewport(element) { var rect = element.getBoundingClientRect(); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth) ); } // Usage isInViewport(document.getElementById('element')); // Returns true or false based on the element's stage presence

Taking a peek at specific CSS properties

There could be times when you want to determine if an element's display or visibility properties are set to specific values.

let isDisplayNone = $('#element').css('display') === 'none'; // Is it a hideaway? let isVisibilityHidden = $('#element').css('visibility') === 'hidden'; // Or just shy?

These checks are direct and explicit, avoiding the implicit layers of :visible and :hidden selectors.

Toggling classes for visibility

A popular approach is to toggle classes that control visibility via CSS.

// CSS .hidden-class { display: none; } // Hide me! .visible-class { display: block; } // Show me! // JS $('#element').toggleClass('hidden-class visible-class'); // Hide-and-seek with classes!

This leverages CSS to manage visibility, potentially improving performance and keeping style rules simplified.