Determining the precise location of the div element

I am seeking to determine the precise positions of a div based on its class name. In the screenshot provided, my script for finding the div's position is highlighted in yellow, while the div I am targeting is highlighted in red at the bottom. Currently, my script locates the parent div of the document and compares it with the desired div class to obtain the positions. However, the positions obtained are not exact, as they may slightly vary from the actual values. For instance, if the div's top and left positions are 50,150, my script might return something like 55,155.

function getPosition(element) {
            var xPosition = 0;
            var yPosition = 0;
            var left = 0;
            var top = 0;
            var i = 0;
            while (element) {
                xPosition = (element.offsetLeft);
                yPosition = (element.offsetTop);
                console.log("TOP Pos: "+yPosition+"Left Pos: "+xPosition);
                if (i == 1) {
                    left = xPosition;
                    top = yPosition;
               }
                element = element.offsetParent;
                i++;
            }
            return {
                x: left,
                y: top
            };
        }

This method is how I am using this process:

 function ReadDivPos(selector) {
            var _divPos = "";
            var parentDoc = window;
            while (parentDoc !== parentDoc.parent) {
                parentDoc = parentDoc.parent;
            }
            parentDoc = parentDoc.document;
            var parentDiv = parentDoc.getElementsByTagName('div');
            var divs = [];
            for (var i = 0; i < parentDiv.length; i++) {
                if (parentDiv[i].className == "content") {
                    var pos = getPosition(parentDiv[i]);
                    var x = pos["x"];
                    var y = pos["y"];
                    console.log("Values+ Top: " + y + " Left: " + x);
                    var w = parentDiv[i].offsetWidth;
                    _divPos += x + "," + w + "," + y + "," + (x + w) + ","+window.screen.availWidth+"\\n";
                }
            }
            console.log("Values+ x: " + _divPos);
            return _divPos;
        }

While this solution works adequately, I am curious if there exists a more efficient approach using jQuery or any other method. Thank you in advance!

Answer №1

Take a look at this:

$(function() {
  var x = $(".target").offset().left,
      y = $(".target").offset().top;
  
  $(".target").html("x: " + x + " y: " + y);
});
body
{
  padding: 0;
}

.target
{
  background-color: lightgreen;
  width: 7em;
  height: 7em;
  line-height: 7em;
  text-align: center;
  left: 100px;
  top: 20px;
  font-family: Calibri;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="target"></div>

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

Exploring the method to deactivate and verify a checkbox by searching within an array of values in my TypeScript file

I am working on a project where I have a select field with checkboxes. My goal is to disable and check the checkboxes based on values from a string array. I am using Angular in my .ts file. this.claimNames = any[]; <div class="row container"> ...

Troubleshooting a malfunctioning PHP form that uses jQuery and AJAX

Snippet of HTML code: <form class="contact_form" action="" name="contact_form"> <ul><li> <input type="email" name="email" placeholder="Please enter your email here" required /> </li><li> <button class="submit" type=" ...

Is it possible to use nodemailer locally with NodeJS? The issue is that the greeting emails are not being received

Every time I attempt to send an email using nodemailer within my local network, I encounter the following error: *Greeting never received at SMTPConnection._formatError (C:\Users\PI_TEAM\Desktop\node_modules\nodemailer\lib ...

Disable the function when the mouse is moved off or released

My custom scrolling implementation in a ticker using Jquery is due to the fact that standard scrolling doesn't function well with existing CSS animations. The goal is to enable movement of the ticker when clicking and dragging on the controller, a div ...

Issue with HTTP headers not being effective in $.AJAX request

Regardless of the method I attempt to use for setting headers in an AJAX call, and no matter which header I set, every time there is a header present, the AJAX call is aborted and does not go through. However, if I try to make the call without setting any ...

Creating a paragraph from text inputs using React

I'm currently working on code that retrieves input from two textboxes - one for a string value and one for a number value. I want this data to be displayed in real-time within a paragraph without the need for a submit button. I've been struggling ...

Tips for importing an external JavaScript file and accessing its data within a ReactJS project?

Currently, I am working on a React project using create-react-app. My objective is to load an external JavaScript file (hosted in IIS) and utilize the data it contains. To fetch this file, I am including a script in my index.html like so: <script type ...

Is it possible to merge node modules that have similar functionalities?

When utilizing node.js, you may encounter module dependencies containing functions with similar functionalities, such as underscore, lodash, and lazy (potentially in different versions). Is there a way to specify which module from a group of similar metho ...

CSS styling doesn't take effect until the page is reloaded due to the failure of cssText

After generating a new list item, it appears that the CSS styling is not being inherited until the page is reloaded. Even though I have added styling using cssText dynamically, it doesn't seem to be working as expected. I've attempted using cssT ...

Is there a solution to resolve the Firestore issue stating: "FieldPath.documentId is not a recognized function"?

In my function, I am retrieving data from two collections in Firestore: Media and Users. Inside the Users collection, there is a subcollection containing a list of all the user's movies. The Media collection includes details about each movie. My goal ...

Using JQuery to swap out all URLs on a webpage?

Seeking guidance and examples on replacing all the links in the head of a document using jQuery. I am currently working with an app that requires my site to have SSL. To address this requirement without purchasing an SSL certificate or a static IP, I am a ...

Exploring the use of Angular with tables: applying classes dynamically using ngClass and repeating items using

My table is generated from a Web Service JSON, each row has a button to mark it for deletion. When you click the button, a JS alert displays the ID of the row element, and I also need to add the 'danger' bootstrap class to the row. Now, I can cap ...

Determine the width of a dynamically generated div element in JavaScript using the createElement method

Currently, I am utilizing the JavaScript function createElement to generate a new div element and then assigning its innerHTML. Following that action, I am attempting to determine the necessary width required to display the div with all of its content. var ...

header color scheme and dimensions

Hello, I've managed to get the menu working correctly on my website at www.g-evo.com/header.php. However, I'm now facing an issue with the size of the header. I'd like to shrink the grey area slightly so it aligns better with the logo, while ...

Ways to create a full-window image cover starting from the center point and extending to the right by 50

Seeking assistance from anyone who can help me with my current issue. I am currently utilizing bootsrap 4 and I need to come up with a solution for the following scenario: I have one element that is situated within the standard six columns, while the secon ...

In order to ensure proper alignment, adjust the width of the select element to match the width of the

Is there a way for the select element to adjust its width based on the length of the selected option? I want the default option value's width to be shorter, but once another option is selected, I'd like the select element to resize itself so that ...

Building on the Vuejs3 and Vuex4 framework, create a conditional rendering feature that triggers upon

I have a unique setup where custom objects are used to hold child objects full of data. The child objects start with null values for all properties, allowing them to be filled with data from remote sources when referenced. This results in a lazy-loading sy ...

How to showcase base64 encoded images in pug (jade) with node.js

Can anyone help with decoding this mysterious data and displaying the image? I'm using pug as my template engine. Below is the questionable data that needs to be shown as an image: /9j/4AAQSkZJRgABAQEAYABgAAD/4QBaRXhpZgAATU0AKgAAAAgABQ ...and so f ...

execute a setTimeout function in ReactJs to render a component after a specified amount of time

Is there a way to render a component inside my App.Js after a certain amount of time using setTimeout? I've tried, but nothing seems to be happening... This is my code: function App() { return ( <Router> <GlobalStyle /> ...

Having trouble binding form data to a React component with the onChange() method?

I've been working on developing an email platform exclusively for myself and encountered a roadblock with this React form not updating state when data is entered. After identifying the issue, it appears that the main problem lies in the React form not ...