Find out whether the object is located behind another item

Is there a method to determine if elementA is "obscured" by another element, meaning it is not visible to the user?

We could potentially achieve this using stacking context, but the challenge lies in identifying which elements to compare. This would require iterating through all DOM elements and verifying stacking context for each one, leading to performance issues.

Could someone provide insight on how to ascertain whether #hidden-element is hidden due to being covered by another element? Here's a jsfiddle for reference.

HTML:

<div id="covering-element"></div>
<div>
  <div id="hidden-element"></div>
</div>

Styles:

#covering-element {
  position: absolute;
  width: 100px;
  height: 100px;
  background: darksalmon;
  text-align: center;
}

#hidden-element {
  width: 25px;
  height: 25px;
  background: deeppink;
}

Answer №1

In order to determine the visibility of an element and ensure it is not obscured by other elements, we implemented a solution using several methods. Here are the approaches we employed:

  1. Utilized window.getComputedStyle to inspect for visibility:hidden and display:none
  2. Employed document.elementFromPoint from various positions, including all corners, to handle common scenarios and enhance accuracy. Corner coordinates were easily obtained via Element.getBoundingClientRect()

Link to Demonstration

HTML

<div id="covering-element"></div>
<div>
  <div id="hidden-element"></div>
</div>

<button style="margin-top:100px">Check visibility</button>

CSS

#covering-element {
  position: absolute;
  width: 100px;
  height: 100px;
  background: darksalmon;
  text-align: center;
}

#hidden-element {
  width: 25px;
  height: 25px;
  background: deeppink;
}

JavaScript

document.querySelector('button').addEventListener('click', function() {
    const element = document.getElementById('hidden-element')
  alert('Visible = '+isVisible(element))
})

function isVisible(element) {
  if(!isVisibleByStyles(element)) return false
  if(isBehindOtherElement(element)) return false
  return true
}

function isVisibleByStyles(element) {
    const styles = window.getComputedStyle(element)
  return styles.visibility !== 'hidden' && styles.display !== 'none'
}

function isBehindOtherElement(element) {
  const boundingRect = element.getBoundingClientRect()
  // adjust coordinates to get more accurate results
  const left = boundingRect.left + 1
  const right = boundingRect.right - 1
  const top = boundingRect.top + 1
  const bottom = boundingRect.bottom - 1
  
  if(!element.contains(document.elementFromPoint(left, top))) return true
  if(!element.contains(document.elementFromPoint(right, top))) return true
  if(!element.contains(document.elementFromPoint(left, bottom))) return true
  if(!element.contains(document.elementFromPoint(right, bottom))) return true
  
  return false
}

Note: Node.contains returns true if the given element is the node itself or a descendant of it. To solely check for the exact element without including its descendants, utilize

document.elementFromPoint(...) !== element
in the conditional statements within isBehindOtherElement

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering the "test exited without ending" error while using asynchronous forEach loops with tape

My Current Project Edit: I created a repository with a simplified version of the issue I am facing. Currently, my focus is on setting up automated frontend testing using tools like browserstack, selenium-webdriver, and tape. More information about tape ...

A new long polling AJAX request is triggered whenever there is a change in the parameter

function AjaxRequest(params, url) { if (params) { this.params = params; this.type = "GET"; this.url = url; // this.contentType = "multipart/form-data"; this.contentLength = params.length;; } } AjaxRequ ...

Creating a synchronous loop in Node.js with Javascript

After exhausting various methods such as async/await, synchronous request libraries, promises, callbacks, and different looping techniques without success, I find myself seeking help. The task at hand involves calling the Zoom API to fetch a list of cloud ...

Error message encountered: "myData undefined while executing server in Node.js"

const express = require('express'); const app = express(); app.post('/', (req, res) => { let newData = new contact(req.body); newData.save() .then(() => { res.send("Data has been successfully saved to ...

What is the most effective method to retrieve the UserName using Javascript?

Can someone please explain to me the difference between using session["user"].name and session["user:name"]? // I don't understand why we have to put the user session into the JavaScript global space :( var session = { user: { "Id":"d675c ...

Utilizing Mongoose Schema Enums Alongside TypeScript Enums

In our Typescript-based NodeJs project utilizing Mongoose, we are seeking the right approach to define an enum field on a Mongoose schema that aligns with a Typescript enum. To illustrate, consider the following enum: enum StatusType { Approved = 1, ...

Tips for Implementing a Footer Component in ReactJS

My current setup includes: https://i.stack.imgur.com/2gvHk.png A navigation bar Nested content with a wizard and partial windows. A dynamic footer whose buttons and functionality need to change based on certain scenarios in the content. Currently, I ha ...

The Challenge of the Universe's Origin

While watching the latest episode of The Big Bang Theory (Season 11, Episode 20), I found myself intrigued by Dr. Wolcott's unusual encryption method. In a quirky twist, this nutty theoretical cosmologist wrote his notes backward and converted all let ...

The Node.js error message "Module not found"

Currently, I am working through the node.js tutorial on Lynda.com and encountering an issue with the "Error: Cannot find module". Despite having the flight module listed in the package.json file, the error persists. Up until this point, everything has bee ...

AngularJS: encountering an issue with undefined vm variable while implementing controllerAs syntax within a directive

I am having trouble accessing the vm.screensize property in the relevant controller. The error message states that vm is not defined. Below you can find the directive and controller code snippets. angular.module('app.ain.directives') .direct ...

There was an error during module build process: ReferenceError occurred due to an unrecognized plugin "import" specified in "base" at position 0

I have encountered an error while working on my ReactJS project using create-react-app. The error arose after I added and removed a package called "react-rte". Now, every time I try to start my project, I get the following error: Error in ./src/index.js Mo ...

Getting the value of a sibling select element when a button is clicked

Trying to retrieve the selected option value on button click has become a challenge due to multiple groups of buttons and select elements. The key seems to be using siblings somehow, but the exact method remains elusive... <div class="form-group" ng-re ...

The AJAX response shows a value of "undefined"

My HTML page contains these codes, which display a list of employees from the database. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script src="Scripts/jquery-1.10.2.js"></script> ...

What is the best way to deactivate buttons with AngularJS?

I have a situation where I need to disable the save button in one function and permanently disable both the save as draft and save buttons in another function using AngularJS. How can I accomplish this task with the disable functionality in AngularJS? Her ...

Problem with deleting or substituting symbols and character codes within a String

I am attempting to send an object called dataO from Node.js/Express/EJS to the client side. On the Node.js script side: var dataO = {"first":[20000, 14000, 12000, 15000, 18000, 19000, 22000], "second":[12000, 11000, 18000, 12000, 19000, 14000, 26000]}; var ...

Posting values using AJAX in PHP - A guide

test.html <html> <!-- To access the complete PHP-AJAX tutorial, please visit http://www.php-learn-it.com/tutorials/starting_with_php_and_ajax.html If you found this tutorial helpful, a backlink to it would be greatly appreciated. ...

One of the quirks of Angularjs is that the ng-enter animation will only be

The initial animation only occurs the first time. I am utilizing Angularjs version 1.2.22 Here is the CSS that I am using : .ng-enter { animation: bounceInUp 2s; } .ng-leave { animation: bounceOutUp 2s; } And this is the route configuration : ...

Error Encountered When Trying to Import BrowserAnimationsModule in Angular 5: Unexpected Token "<"

As I try to integrate the BrowserAnimationModule into my Angular 5 project, a rather foolish error keeps popping up. Error: (SystemJS) Unexpected token < SyntaxError: Unexpected token < at eval (<anonymous>) at Object.eval ...

Zebra lines overlooking unseen details

Imagine having a table where rows can be dynamically assigned classes such as .hidden, which hide those rows using CSS. The rows are styled with alternating colors, like this: tr:nth-child(even) { background-color: $light-grey; } But here's the ...

Add CSS styling to a section of a canvas

I want to use a specific cursor png for just a portion of a canvas. Currently, I have code that applies the cursor to the entire canvas like so: .myClass { cursor: url('../img/myCursor.png') 7 33, auto; /* img hotspot centred*/ } However, I ...