How do I check if an element is visible using JavaScript without jQuery?
Davide S
davide s profile pic

To check if an element is visible on the page using JavaScript without relying on jQuery, you can use a combination of methods and properties to determine its visibility based on its dimensions and positioning. Here's a step-by-step approach: 1. Get a reference to the element: Use JavaScript methods likegetElementById(),querySelector(), or any other appropriate method to retrieve the element you want to check for visibility. 2. Check if the element exists and is visible: - Verify if the element is not null or undefined. - Use thegetComputedStyle() method to get the computed style of the element. - Check if thedisplay property is set to'none', which indicates that the element is hidden. - Also, check if thevisibility property is set to'hidden', as this also indicates that the element is not visible. Here's an example code snippet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

   function isElementVisible(elementId) {
     const element = document.getElementById(elementId);
     if (!element) {
       return false; // Element does not exist
     }

     const computedStyle = window.getComputedStyle(element);
     if (computedStyle.display === 'none' || computedStyle.visibility === 'hidden') {
       return false; // Element is hidden
     }

     return true; // Element is visible
   }

   // Usage example:
   console.log(isElementVisible('myElementId')); // Output: true or false
   

In the example above, theisElementVisible() function takes anelementId parameter, retrieves the element usinggetElementById(), and checks its computed style properties to determine visibility. If the element exists and is not hidden, the function returnstrue; otherwise, it returnsfalse. 3. Additional considerations: - If the element has zero dimensions (width and height), it may not be visible even if its CSS properties indicate visibility. You may need to check for non-zero dimensions using theoffsetWidth andoffsetHeight properties. - If the element is contained within a parent element with its own visibility settings, you may need to recursively check the visibility of both the element and its ancestors. Remember that this approach checks if the element is visible based on CSS properties and dimensions, but it doesn't take into account the element's position in relation to the viewport. If you need to check if the element is currently in the visible area of the viewport, you may need to consider additional logic involving the element's position and scroll events.