Determine the precise location of a screen element with jQuery

Can anyone help me determine the precise position of an element on the current visible screen using jQuery?

My element has a relative position, so the offset() function only gives me the offset within the parent.

Unfortunately, I have hierarchical divs, making it difficult to calculate the absolute position using $("#me").parent().offset() + $("#me").offset()

I need the position in the window that changes as the document is scrolled.

While adding up all the parent offsets is one solution, I prefer a cleaner alternative.

var top = $("#map").offset().top + 
    $("#map").parent().offset().top + 
    $("#map").parent().parent().offset().top +
    $("#map").parent().parent().parent().offset().top;

Any suggestions?

Update: I require the exact gap in pixels between my div's top and the document's top, factoring in padding, margins, and offset.

This is my code:

HTML

<div id="map_frame" class="frame" hidden="hidden">
    <div id="map_wrapper">
        <div id="map"></div>
    </div>
</div>

CSS

#map_frame{
    border:1px solid #800008;
}

#map_wrapper {
    position:relative;
    left:2%;
    top:1%;
    width:95%;
    max-height:80%;
    display:block;
}

#map {
    position:relative;
    height:100%;
    width:100%;
    display:block;
    border:3px solid #fff;
}

jQuery to resize the map to fill the screen*

var t = $("#map").offset().top + 
    $("#map").parent().offset().top + 
    $("#map").parent().parent().offset().top + 
    $("#map").parent().parent().parent().offset().top;

$("#map").height($(window).height() - t - ($(window).height() * 8 / 100));

Thank you for your assistance...

Answer №1

Check out the information on .offset() in the jQuery documentation. It provides the element's position relative to the document, not its parent. If you are mixing up .offset() and .position(), remember that the former gives the global position while the latter gives the position relative to the offset parent. To get the window's position instead of the document's, you can adjust by subtracting the .scrollTop() and .scrollLeft() values for the scrolled position.

Here's a snippet from the documentation:

The .offset() method lets us get the current position of an element relative to the document. This is different from .position(), which gets the current position relative to the offset parent. When placing a new element over an existing one for systemwide manipulations (like drag-and-drop), .offset() is more beneficial.

To put it all together:

var offset = $("selector").offset();
var posY = offset.top - $(window).scrollTop();
var posX = offset.left - $(window).scrollLeft(); 

You can experiment with it here (scroll to see the changes): http://jsfiddle.net/jfriend00/hxRPQ/

Answer №2

If you're looking to find the absolute coordinates of any jQuery element, I've crafted a function that may be of use to you. While it may not work perfectly for all CSS position types, it can certainly serve as a solid starting point..

function FindAbsoluteCoordinates($element) {
    var sTop = $(window).scrollTop();
    var sLeft = $(window).scrollLeft();
    var w = $element.width();
    var h = $element.height();
    var offset = $element.offset(); 
    var $p = $element;
    while(typeof $p == 'object') {
        var pOffset = $p.parent().offset();
        if(typeof pOffset == 'undefined') break;
        offset.left = offset.left + (pOffset.left);
        offset.top = offset.top + (pOffset.top);
        $p = $p.parent();
    }

    var pos = {
          left: offset.left + sLeft,
          right: offset.left + w + sLeft,
          top:  offset.top + sTop,
          bottom: offset.top + h + sTop,
    }
    pos.tl = { x: pos.left, y: pos.top };
    pos.tr = { x: pos.right, y: pos.top };
    pos.bl = { x: pos.left, y: pos.bottom };
    pos.br = { x: pos.right, y: pos.bottom };
    //console.log( 'left: ' + pos.left + ' - right: ' + pos.right +' - top: ' + pos.top +' - bottom: ' + pos.bottom  );
    return pos;
}

Answer №3

By the way, for those interested in obtaining the coordinates of an element on the screen without using jQuery, you can give this code a try:

function calculateElementTopOffset (element) {
    if (element.offsetParent) return element.offsetTop + calculateElementTopOffset(element.offsetParent)
    return element.offsetTop || 0
}
function calculateElementLeftOffset (element) {
    if (element.offsetParent) return element.offsetLeft + calculateElementLeftOffset(element.offsetParent)
    return element.offsetleft || 0
}
function determineCoordinates(element) {
    var y1 = calculateElementTopOffset(element) - window.scrollY;
    var x1 = calculateElementLeftOffset(element) - window.scrollX; 
    var y2 = y1 + element.offsetHeight;
    var x2 = x1 + element.offsetWidth;
    return {
        x1: x1, x2: x2, y1: y1, y2: y2
    }
}

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

Incapable of retrieving data from MongoDB due to a failure in fetching results using streams in Highland.js

I have recently started working with streams and I am experimenting with fetching data from my collection using reactive-superglue/highland.js (https://github.com/santillaner/reactive-superglue). var sg = require("reactive-superglue") var query = sg.mong ...

Tips for forwarding an image uploaded using Flask Dropzone to a different page

I recently used Flask Dropzone to upload an image into the uploads folder. My goal is to pass this uploaded image to my makeMeme page so that I can display it using the html img tag. Despite my efforts, when I attempt to reference the file for displaying, ...

Running compiler-produced assembler code within the program

Recently, I came across an interesting presentation discussing inline ASM generation in Javascript optimization. The presentation can be found at the following link: . In another paper located here: https://sites.google.com/site/juliangamble/Home/Compiler ...

Identify matching values in objects and dynamically update them with a custom value

I have an array structured like this: var array = [ { dates: "2020-12-25", class: "first" }, { dates: "2020-12-26", class: "last" }, { dates: "2021-06-11", class: "first" }, ...

Oops! It looks like there was an error. Remember that AJAX events should be connected to the

I am completely new to the world of Ajax and unfortunately, I encountered an error message in my browser: "JQMIGRATE: AJAX events should be attached to document: ajaxComplete" After some research, it seems like I need to incorporate certain Ajax functi ...

Using http-proxy-middleware in a React application for browser proxy

I'm having trouble with setting up a proxy in my React app. Scenario: I have two React apps, one running on localhost:3000 and the other on localhost:3001. What I want to achieve is that when I click on: <a href="/app2"> <button> ...

What is the best method for retrieving an item from localstorage?

Seeking advice on how to retrieve an item from local storage in next.js without causing a page rerender. Here is the code snippet I am currently using: import { ThemeProvider } from "@material-ui/core"; import { FC, useEffect, useState } from "react"; i ...

There is a problem with my module where multiple files that require it are overriding its variables

Currently, I am working on developing a mongo connection pool factory that is capable of checking if a connection to mongo already exists. If a connection exists, it will return that connection. However, if there is no existing connection, it will create a ...

Troubleshooting problems with data binding in Angular Ionic

Just starting out with Angular and experimenting with building an app in Ionic. I have a screen with 2 input fields and I want to achieve the following. When a user inputs something in the price field, I want the weight field to update accordingly. Simil ...

Can dynamic data be loaded on page load and children on click without storing children in the parent's state?

I have a dilemma with loading dynamic data on my fiddle. You can check it out here: https://jsfiddle.net/61qxn7av/2/ The issue is that each parent should have different children and these children need to append to the correct parent based on which checkb ...

Efficiently Extracting Information from JSON Objects

Currently, I am in the process of parsing a JSON file. Let's assume that the JSON data looks like this: {"data" : [ {"ID":12, country: "UK"}, {"ID":13, country: "USA"}, {"ID":14, country: "BRA"}, ]} Instead of just having three entries as show ...

Dealing with Database Timeout in Express JS

I have been trying to extract SQL query execution into a separate file to prevent code repetition, but I am facing timeout issues during execution. var mysql = require('mysql'); const connectionData = { host: 'localhost', user: ...

Unable to attach the script to recently added DOM elements

After spending considerable time working on this, I'm still unable to figure it out. You can find the page I am referring to at: The "show more" button at the bottom triggers additional posts to be displayed on the page using the following script: ...

Obtaining a CSS element again to be utilized for boundary checking purposes

Is it possible to retrieve a CSS element? I recently found myself in a situation where I needed to add some code to an Adobe Edge project, specifically involving the manipulation of margin-top and margin-left properties. While experimenting with moving an ...

Express-session is failing to return a value in spite of my explicit declaration of the session

I've been working on my website for quite some time and everything was smooth sailing, until now. Here's the issue: after a user logs in, a session cookie named "user" is created to store their email. Upon console logging the cookie right after ...

Tips for utilizing a dropdown menu in Angular

<div> <label> Categories </label> <select> <option *ngFor = "let category of categories" [value] = "category" (click) = "onCategorySelected( category.name )"> ...

Using bluebird library for revoking promises

Recently, I've been diving into the bluebird promises library. To practice using it, I set up a basic express app with just one file and one route - a GET request to /test. The scenario I'm working on involves a promise with an interval that res ...

Guide on updating the default screen background color for all pages in React JS (Next JS) with the help of tailwind CSS

How can I change the default screen background color for all pages within my web application? Here are the technologies I've used: React JS Next JS Tailwind CSS I would like to set the screen background color of all pages to a light grey shade, as ...

Terminate the rethinkdb data stream

Currently delving into the world of RethinkDB and am eager to utilize the changes() method to fetch a changefeed. While I've figured out how to initiate them, the documentation doesn't quite explain how to halt a changefeed. Is it sufficient to ...

Notification system for managing recurring tasks

Situation I am currently working on an application where users are assigned daily tasks such as "wash the window, clean the floor," and so on. Each task has a specific recurrence interval and must be completed at least once within that time frame. For e ...