retrieve the position of a descendant element in relation to its ancestor element

I'm encountering a challenge while attempting to solve this issue. I have elements representing a child, parent, and grandparent. My goal is to determine the offset position of the child (positioned absolutely) in relation to the grandparent. However, here lies the complexity - the parent element must be positioned relatively as it functions as an accordion, causing the child elements to collapse along with it. If the parent is not left with a relative position, the absolute children will not collapse and remain static.

Currently, I am able to obtain the child's position in relation to the parent using jQuery:

// simple accordion
$('.accordion').on('click',function(){
  $(this).next().slideToggle();
})
// get child offset
var childPos = $('.child').position();
console.log(childPos.top) // top position from granparent

CSS

.grandparent{
  position:relative;
}
.parent{
  position: relative;
  padding:20px;
}
.child{
 position: absolute
}

HTML

<div class="grandparent">
  <div class="parent">
    <div class="accordion">accordion</div>
    <div class="child">
      child content
    </div>
  </div>
  <div class="parent">
    <div class="accordion">accordion</div>
    <div class="child">
      child content
    </div>
  </div>
  <div class="parent">
    <div class="accordion">accordion</div>
    <div class="child">
      child content
    </div>
  </div>
</div>

Please provide any assistance you can offer!

Answer №1

From what I gather, it seems like you can implement the same approach to determine the location of the parent within the grandparent element.

let childPosition = $('.child').position();
console.log(childPosition.top) // vertical position of child relative to parent
let parentPosition = $('.parent').position();
console.log(parentPosition.top) // vertical position of parent relative to grandparent
let childGrandparentPositionTop = childPosition.top + parentPosition.top;
console.log(childGrandparentPositionTop); // vertical position of child relative to grandparent

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

Hidden warning to React-select for being uncontrolled

I've integrated react-select into my code: import React, {Component} from 'react'; import Select, {createFilter} from 'react-select'; let _ = require('underscore') class Test extends Component { constructor(props) ...

What is the best method for extracting attribute values from multiple child elements using puppeteer?

When using this code, I can retrieve the attribute value of the first element selected. By adding /html/body/section/div[3]/img<2> or img<3> in the xpath, I am able to retrieve data for subsequent img elements. However, the parent element on t ...

The failover process for PayPal involves seamless transitions to backup systems in the

I am currently assisting a client with a unique architecture setup: Back End Running on Java Server Front End Powered by Proxy (Node JS + Express application) For security reasons, all requests made to the server must pass through the Proxy. We ar ...

Invoke the function when you finish typing in React.js

After I finish typing, I want to execute some code. I attempted to use the following script but it didn't work as expected const stopTypingHandler=(e)=>{ let time; clearTimeout(time); time = setTimeout(() => { console.log("click& ...

Error: Uncaught TypeError - Unable to change value of 'innerHTML' for null object in VueJs

I have been encountering a similar problem to others, but despite trying the solutions provided in previous questions, I am unable to resolve it. In my <template>: <modal name="MyModal" > <span class="myClass" id="visible">visible< ...

Retrieve items from an array using indexes provided by a separate reference table

I am dealing with two different arrays. One array contains my data: var tab1 = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty"]; ...

Triggering an automatic pop-up window using JavaScript based on a PHP condition

I have developed a hidden pop-up box that becomes visible when targeted, with its opacity increasing to one. I am aiming for the pop-up to appear if the user is identified as a "firstTimeUser," a status saved in a PHP $_SESSION variable. However, I am stru ...

unable to retrieve the latest scope value following the completion of the ajax request

I attempted to use the code below, but despite searching for answers and solutions involving $apply and $timeout, nothing seemed to work in my case. I encountered several errors along the way. JS: var app = angular.module("test",[]) app.config(function($ ...

Breaking apart faces of a sphere using Three.js

I am currently working on creating a sphere geometry. geometry = new THREE.SphereGeometry( 200, 20, 10 ); material = new THREE.MeshLambertMaterial({ shading: THREE.FlatShading, color: 0xff0000 }); sphere = new THREE.Mesh(geometry, material); scene.add( sp ...

Press the jQuery button to reset all input fields

I have created a table with input fields where class teachers can store their students' data for the principal to review. Each row in the table contains an update and reset button, allowing teachers to save or clear the information entered in the fiel ...

Issue arised while trying to open Bootstrap modal window due to conflict with surrounding elements

I'm facing a challenge with getting the bootstrap modal window to pop up on my website. Despite trying various solutions and troubleshooting steps, I haven't been able to resolve the issue. Even after eliminating all scripts except for the boots ...

Retrieve the HTML content from the string that is returned

I have the string containing a list structure in my code-behind file: string xmlContents = "<ul><li>Installation<br /><ul><li>Startup</li><li>Getting there</li><li>Steps</li>" + ...

How to maintain the selected value in a Vue.js dropdown even after the page is refreshed

When a user selects a value from a dropdown, it is pushed to the URL. If the page is refreshed, the dropdown should default to the selected value in the URL. This functionality is being implemented in Laravel. I have attempted the following approach, but w ...

Methods to Maintain Consistent HTML Table Dimensions utilizing DOM

I am facing an issue with shuffling a table that contains images. The table has 4 columns and 2 rows. To shuffle the table, I use the following code: function sortTable() { // Conveniently getting the parent table let table = document.getElementById("i ...

Setting a CSS style for an ASP.NET button: What you need to know!

I am facing an issue with the styling of my asp:Button. I have applied CSS styles using the cssClass property, but they are not being applied correctly. Surprisingly, when I switch to using asp:LinkButton, the styles work perfectly fine. I prefer not to us ...

Filtering an array of <input> values in JavaScript based on the number of characters they contain

Can someone help me figure out why this JavaScript code isn't working as expected? The intention is to grab the input value from a text box (a string of words separated by spaces), convert it into an array, and then remove any words that are less than ...

Omitted Script within a Node.js JavaScript Code Segment

My code snippet is: function write_to_orchestrate(data_to_write) { console.log('more testing'); db.put('musician', '1', '{"test":"test1"}') .then(function (result) { res.send(result); ...

Retrieving CSV information from several files within a JavaScript directory

Currently, I am attempting to retrieve data from numerous CSV files using 'csvtojson'. Firstly, I gathered an array of file names in a specific directory. Then, I used a forEach loop to extract data from various CSV files and convert it to JSON ...

Sides of the BoxGeometry

I previously inquired about a particular issue on this post: Adding Thickness to Faces The main problem has been resolved, but now I have encountered a new issue. Initially, my walls were set to side:THREE.BackSide so they didn't display when facing ...

How can I resolve the issue of shadow.static in Three.js causing shadows to shift when the shadow.bias is adjusted? Suggestions on

So I've got a scene with some nice shadows being cast by a light, but there's this pesky static issue with the shadow. Check it out: https://i.sstatic.net/k3XIe.jpg When I try to fix it with a simple tweak like light.shadow.bias = -0.005;: htt ...