Calculating the distance of a child element from the top-left corner of its parent element in JavaScript

Can you determine the offset of a ChildElement in relation to a specific parent element?

For instance, if a DIV is nested inside a parent DIV with the ID "xyz"

Is there a method to achieve this using jQuery?

let parent = $("#xyz");
let child = $("#abc");

child.offset(parent);

Appreciate your help

Answer №1

One easy way to get the position of an element is by using Element.getPositionedOffset(), but this method only works if the parent element has a position style property.

var offset = $('abc').positionedOffset();
offset.left;
offset.top;

If the parent element does not have a position style property, you'll need to do a bit more work:

var parent = $('xyz',
    child = $('abc'),
    offset = child.viewportOffset().relativeTo(parent.viewportOffset());

The benefit of this approach is that the two elements do not have to be directly related; any pair of elements on the page can be used.

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

The AngularJS error message [$rootScope:infdig] is triggered when the number of $digest() iterations exceeds 10 due to a window

It's evident that changing window.location.href/reload to $location.path() resolves the issue. However, using $location.path breaks the app in IE but works in Chrome with window. The purpose behind this is to update a site when a user logs in or out, ...

Combining multiple pipe collections in a single Gulp task for both CoffeeScript and JavaScript files

I've been working on creating a single scripts task that can handle both .coffee and .js files effectively: Coffee files need to go through coffee(), coffeelint() and coffeelint.reporter() JS files should run through jshint() All files then need to ...

How to access specific values from a deserialized JSON string using Javascript

Within the nested for loops, I have the following row: document.getElementById("sm" + i + "b" + j).innerHTML = jsonval.values.sm1b1; ^^^^^^ In order to change the va ...

Developing a user-friendly widget for a website that is not optimized for mobile devices

Here's the backstory: I'm currently in the process of creating a mobile-friendly widget for my clients. Unfortunately, they have web pages that are not optimized for mobile devices, and it doesn't seem like that will change anytime soon. Th ...

Is it possible to transform an arrow function into a regular function?

Currently, I am working my way through the AJAX type ahead course in Javascript 30 by Wes Bos. As I progress through this course, I have made a conscious effort to minimize my use of ES6 features for the sake of honing my skills. If you want to see the fi ...

Use the regex tag in a React component to find a specific tag by name within two different possible

Looking for a regex that can identify <Field ...name="document"> or <FieldArray ...name="document"> within a multiline text string so they can be replaced with an empty string. The text string is not formatted as HTML or XHTML, it simply conta ...

What is the best way to obtain the SearchIDs for various searchNames using JavaScript?

Who can assist me in resolving this issue? I am trying to retrieve the id of a searchName whenever a user selects the checkbox. Ideally, I would like to assign the value of the PHP line $search_row->searchid to the id attribute in the input field. Apolo ...

How should white space be managed in Bootstrap 4 cards when incorporating responsive column classes - wrap elements inside divs or apply classes directly?

In Bootstrap 4, when applying a responsive column class like "col-sm-8" directly to a "div" with the class "card", whitespace is added between the card border and content. This can be seen in the highlighted yellow area in the image below. https://i.sstat ...

utilizing jQuery to deliver a $.post request to a .aspx file

Recently, I started following a jQuery tutorial on the phpAcademy channel hosted on thenewboston. In this tutorial, they demonstrate how to create an email validation form using ASP.net instead of PHP. However, despite following all the steps in the tutor ...

What is the best way to pass a dynamically updated value to the controller?

<form id="participantsForGd"> <span id="GroupID"></span> //example: group id 2 will be displayed here <button id="GdStartTest">Start test</button> </form> I need to pass the value of GroupID to the controller through an ...

Is there a way to use a specific keyboard input to alter the characteristics of shapes on my webpage?

Is there a way to change certain attributes of a shape onscreen when a specific key is pressed by the user? For example, can I make it so that pressing "a" changes the color of the shape? I attempted to modify a mouse rollover event to work with the desir ...

Using the Vue.js Spread Operator in place of Vue.set or Vue.delete

I'm exploring ways to utilize the spread operator for adding or removing object properties in a manner that preserves reactivity. Within a Vuex mutation, this code snippet is successful: Vue.set(state.sportTypes.sports, sportName, sportProperties) H ...

What is the best way to extract specific values from a JSON array of objects using JavaScript?

I am facing some challenges in displaying values from the AJAX objects. My goal is to populate a select box with names using AJAX, but I seem to have made an error somewhere in my code. Can someone please assist me in identifying and correcting the mistake ...

Count up with HTML like a progressive jackpot's increasing value

I am interested in developing a progressive jackpot feature similar to the sample image provided. I would like the numbers to loop periodically. Can anyone advise me on how to achieve this effect? Any suggestions or examples, preferably using JavaScript o ...

Embed the contents from a URL within an HTML document

I am currently in the process of developing an application using Node.JS and Express v4. My chosen template engine is Nunjucks. One of the routes I have set up for my app is the (widget) route, which is being rendered through Express with this code: app.g ...

hiding form fields using javascript

As a beginner in javascript, I am facing a challenge with a set of checkboxes in an HTML form. These checkboxes are generated dynamically from a python script. Among them, there is a checkbox labeled "N/A" that I want to hide automatically when any other c ...

What is the purpose of including an express server instance as an argument for the http module in Node.JS?

Currently delving into the realms of Node.JS, Express.JS, and Socket.IO. The tutorials I've come across so far showcase a complex series of code to kickstart each of these modules: var express = require("express"); var app = express(); var server = ...

Finding the Right Path: Unraveling the Ember Way

Within my application, I have a requirement for the user to refrain from using the browser's back button once they reach the last page. To address this, I have implemented a method to update the existing url with the current page's url, thereby e ...

Next.JS - What is the reason behind data fetching occurring on both the server and client side?

When I call a regular fetch function in the index.js component and then log the response to the console, something unexpected happens. Despite the fetch being inside the component function, the response is also logged on the server side: it shows up in the ...

The toggle password visibility eye is experiencing an error with an Uncaught ReferenceError: An invalid assignment is being attempted in the code

Here's a code I wrote for toggling password visibility, but I encountered an error: HTML: <!--Hide/Show password--> <button class="form-password__visibility" type="button" onclick="$('#inp ...