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

Implementing a collapsible full-width button that contains multiple elements (Bootstrap)

I am currently in the process of developing a responsive calendar that will display additional information in an expandable "well" when the user clicks on a specific event. My goal is to have the button, date, and icon all appear on the same line at full ...

Python.Selenium. Unable to locate current element. Techniques for switching frames

I am trying to collect feedback from a specific page at this URL. After waiting for the page to load, I attempted to locate elements using Google Chrome inspector. However, Selenium is unable to find these elements, and I also could not find them in the p ...

Refrain from using inline JavaScript code within your

Here is the basic structure of my code: <a href="javascript:void(0);" onClick="viewServices(1)">Services</a> <a href="javascript:void(0);" onClick="viewServices(43)">Services</a> <a href="javascript:void(0);" onClick="viewServic ...

The function res.send is unavailable and errors are not being properly managed

I encountered a peculiar error while using my function to create users in my mongoose database. Despite the user being successfully created, I am facing an issue where res.send is not functioning as expected, resulting in no response and instead, an error. ...

Conceal the scrollbar and enable horizontal swiping using CSS

I have set up a container where I want the content to scroll horizontally from left to right on mobile devices, and I would like to be able to swipe to navigate while hiding the scrollbar. You can view the implementation on this JSfiddle link Do you think ...

Guide to sending and receiving JSON data using XAMPP PHP

Currently, my XAMPP 7.1.10-0 server is up and running with the following index.php file: <?php if(isset($_POST["username"])) { echo $_POST; header("Location:getbooks.php"); exit; } else { echo file_get_conten ...

Php file not receiving data from ajax post method

forget.php PHP: if (! (empty($_POST['emailforget'])) ) { echo "here in the function"; } else { echo "here"; } AJAX: $("#passreset").on('click', function(e) { var emailforget = $("#tempemail").val(); alert(emailforget); ...

Navigating rows in a Kendo Grid using buttons (Starting, Previous, Next, Ending)

Looking for help with navigating rows on a Kendo-Grid. I have four Buttons - First, Previous, Next, and Last. The goal is to highlight the selected record on the grid when a button is clicked. However, I'm struggling with making the Kendo-Grid highlig ...

Currently seeking assistance in replacing an existing Wordpress object with a new one

I'm looking to swap out the current slider image with a new slider. Whenever I try to replace it with the TOP 5 Games, they disappear or don't show up at all. <?php if( function_exists('cyclone_slider') ) cyclone_slider('24&ap ...

What is the best way to share models across different node.js projects?

In my setup, I have two node.js projects - project A and project B. Project A serves as the main project, while project B is more of an "ad-hoc" project with a specific purpose. The challenge lies in the fact that project B requires access to project A&apo ...

What is the proper way to set up state with localStorage in Nuxt.js when using Universal Rendering?

Unique Situation In my unique setup, I have a specific flow that involves storing a token in localStorage, even though I know it's not the recommended practice. Every time my Nuxt App is launched, I need to retrieve the token from localStorage, valid ...

I'm facing a challenge with retrieving the controller's scope in my Angular directive

Having trouble accessing the settings I receive from the server in my app. The directives are set up correctly and the $http is used to fetch a js file with the app settings. However, despite being able to log the scope in the console, I am unable to acces ...

What is the process of importing a JSON file in JavaScript?

Is there a way to import a JSON file into my HTML form by calling $(document).ready(function (){});? The properties defined in the JSON file are crucial for the functionality of my form. Can anyone guide me on how to achieve this? ...

Execute a function when a selection option is chosen consecutively two times

I have a dynamic dropdown menu that uses AJAX to load options. I need the function to be triggered not only when an option is changed, but also when the same option is clicked multiple times in a row. In other words, I want the function to run every time a ...

Preventing Bootstrap modal from automatically closing in Laravel 5.1 when authentication fails

Whenever my bootstrap modal for login fails, it redirects to auth/login and closes the modal. How can I prevent the modal from closing when authentication fails and avoid the redirect back to auth/login? This is my login form: <form action="{{ URL::to ...

Using angularjs, populate a dropdown menu by enclosing the options in curly braces

Utilizing the curly braces syntax interpolation in AngularJS allows us to connect data from the model to the view. This technique is typically used for displaying text. Is there a way to populate a dropdown list using the {{}} syntax? ...

The Scottish flag isn't displaying on my website, but all other Emoji 5 symbols are working perfectly

When I build my website with PHP, I include header('Content-Type:text/html; charset=utf-8'); at the start. Interestingly, the Scottish flag emoji ...

Interactive rotating display with constantly updating information

Recently I started learning angularJS and I must say, I am already hooked. I have developed a website that pulls data from JSON files (created by external scripts) locally to show real-time information on various pages. Now, I want to include a sliding car ...

Enhance JSON nesting with knockoutJS

I am currently working on updating a JSON object in memory using the knockout.js user interface. However, I have encountered an issue where changes made in the UI do not seem to reflect on the JSON data itself. To troubleshoot this problem, I have added bu ...

Configuring the data source for an autocomplete feature in ReactJS Material UI

For one of my React components, I am utilizing the Material UI autocomplete feature. The data source is retrieved from the server asynchronously and has the following structure: const dataSource = [{ id: 001 firstName: 'fname', lastName: &apo ...