determine the distance between two elements in motion

I am attempting to calculate the distance between two dynamically moving HTML elements. Currently, I have them moving on hover, but the result does not change as they move.

What could be causing this issue?

Below is my code:

var lFirst = $("#x").offset().left;
var lSecond = $("#y").offset().left;
var ldist = parseInt(lFirst - lSecond);

var tFirst = $("#x").offset().top;
var tSecond = $("#y").offset().top;
var tdist = parseInt(tFirst - tSecond);

$('#result').append(parseInt(tdist + ldist));
html, body{
  margin:0;
  padding:0;
}
*{
  transition:all 1s;
}
#x, #y{
  width:50px;
  height:50px;
  margin-left:0;
  margin-top:0;
  background:black;
}
#container{
  height:100vh;
  width:100vw;
  background:lightgrey;
}
#container:hover #x{
  margin-left:50vw;
}
#container:hover #y{
  margin-top:50vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div id="result"></div>
  <div id="x"></div>
  <div id="y"></div>
</div>

View on JSFiddle

Answer №1

Ensure the result is constantly updated as objects shift positions.
A method to achieve this is by using a timer in JavaScript, specifically setInterval().
In this demonstration, the result is refreshed every 100 milliseconds.

var $x=$('#x');
var $y=$('#y');
var $result=$('#result');

function updateDistance() {

  var lFirst = $x.offset().left;
  var lSecond = $y.offset().left;
  var ldist = parseInt(lFirst - lSecond);

  var tFirst = $x.offset().top;
  var tSecond = $y.offset().top;
  var tdist = parseInt(tFirst - tSecond);

 $result.text(parseInt(tdist + ldist));

}

setInterval(updateDistance, 100);
html,
body {
  margin: 0;
  padding: 0;
}

* {
  transition: all 1s;
}

#x,
#y {
  width: 50px;
  height: 50px;
  margin-left: 0;
  margin-top: 0;
  background: black;
}

#container {
  height: 100vh;
  width: 100vw;
  background: lightgrey;
}

#container:hover #x {
  margin-left: 50vw;
}

#container:hover #y {
  margin-top: 50vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div id="result"></div>
  <div id="x"></div>
  <div id="y"></div>
</div>

Answer №2

If you're looking to find the (X,Y) coordinates of an HTML element, check out this useful resource:

Finding the Position (X,Y) of an HTML Element

Once you've obtained the (x,Y) coordinates, calculating the distance simply requires some basic math:

distance = sqrt((x2-x1)^2 + (y2-y1)^2)

Answer №3

In order to update the information in your result div, you have two options: either implement a JavaScript Timing Event that triggers at a specific time interval and updates the content, or set an event handler on the HTML element so it updates the result every time it moves.

setInterval(function, milliseconds)

//This function repeats the execution continuously.

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

Is there a way to replace the default Laravel pagination CSS class with a custom theme CSS class?

Is there a way to update my Laravel pagination CSS to match my theme's CSS? I need help with this adjustment. Here is the HTML for the theme's CSS: <div class="row mt-5"> <div class="col text-center"> ...

The video tag displaying input from the camera functions properly in Safari on iOS, however it does not work in Chrome or any in-app browser

While the video streaming on Android and Safari in iOS is functioning perfectly, issues arise when attempting to use Chrome on iOS or an In-app Browser. The implementation involves Vue as a Single File Component. The HTML code utilized is as shown below: ...

Counting occurrences of characters in a string: A simple guide

I'm working on a function to identify characters from an array within a given string and count how many of them are present. I've attempted to cover every possible pattern, but the task seems overwhelming. I also experimented with the alternativ ...

The width property in CSS is not having any impact when expressed in percentage

I've encountered a peculiar issue while attempting to specify the width for my search bar. Below is a snippet of my HTML code. <header class="header-main"> <div class="header-main-logo"> <a href=" ...

The behavior of the Bootstrap toggle with a chevron varies between the production environment and the local

For my Bootstrap accordion menu, I used a trick where the chevron turns upside down when clicked on the toggle. You can check out the trick here. In the example, the chevron is pulled to the right. When I implemented this on my website locally, the chevr ...

Issue with Ref when used in a distinct HTML template

I have encountered a frustrating issue with my simple Vue project. When I separate the template and code into individual files, the ref stops working and I end up with an undefined value in the HTML template. This scenario works fine: map.component.vue ...

retrieve the selected option from the dropdown menu. (slightly challenging)

I am new to PHP and coding, so forgive any mistakes in advance. I have a web form that needs to retrieve information from a text file located in a server folder. I know how to fetch data from the file and create a dropdown list displaying all files in the ...

Unusual error message found in JavaScript console

Encountering a new type of error in the console: Received an object message from http://mysiteDotcome, but was expecting a string all.js:56 Received another object message from http://mysiteDOTcom, when a string was expected Although my app is functionin ...

Is there a way to redirect using jQuery and AJAX?

Well, this situation is a bit unique. I would have to consider approaching it in a different way as if we were working with MVC, even though we're not currently utilizing MVC. Here's the setup: I have an .aspx page that includes a user control ( ...

Adding a field conditionally in MongoDB based on matching a field with an array

Looking to create a pipeline for adding a field based on a condition: I have a field named helpful, which is an array containing a list of IDs. My goal is to add a field depending on whether a specific ID is included in that array. An example of the data ...

Using jQuery Datatables with Asp.Net

Having encountered an issue with displaying two jQuery datatables in separate menu tabs, I am seeking assistance to rectify the problem. The first datatable (id=gvSchedule) appends successfully while the second one (id=gvMySchedule) loses its formatting up ...

Dynamic Tooltip Design

I'm trying to figure out how to add a tooltip specifically on the first item in my li list. However, when I apply the "tooltip" class to the li element, the entire li seems to disappear. Here is an example of my HTML code: <li><span class="f ...

Autofill Text Input with React Material-UI

For my current project, I am utilizing Material UI and React. Each TextField in the project has a button next to it, and when the button is clicked, I want it to retrieve the value of its corresponding TextField and set that value as the input for another ...

Utilizing sessions in Node.js Express3 to verify user's authentication status

Here is the content of my app.js file: app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.enable('jsonp callback'); app.set('view engine&apo ...

Issue with modal window not appearing upon clicking the button

I've been searching for a solution to this issue all day with no luck. Currently, I am using BS 4.0 and attempting to display a modal window when a button is clicked. These buttons are created dynamically through an Ajax call and represent the status ...

Is there a way to efficiently return an array of object and nested object keys with their full paths through recursion

My grasp of JS is still in its early stages, so understanding how the stack and recursion function can be challenging for me at this point. The task at hand involves displaying an array of object keys, including the parent object name if the object is nest ...

Troubleshooting the malfunction of the CSS display property

I've created a div with a number displayed initially. When I hover over the div, the number disappears and a paragraph is revealed. Upon hovering out, the paragraph hides and the number reappears. My attempts to achieve this using CSS (display: none ...

Use PHP to dynamically adjust the number of form instances and then save them all as CSV files

Currently, I am developing a PHP script that will allow users to open an existing CSV file (referred to as the template) on a webpage. Users can then populate editable text fields with its data anywhere between 1 and 50 times, depending on their needs. Onc ...

Move on to the next iteration in the FOR loop in Node JS

Is there a way to skip item 3 in the loop without breaking it? for (var i = 1; i<= 9; i++) { if (i==3) break; console.log(i); } I had a tough time searching for an answer online because I am unsure of the exact terminology to use. Desired output: ...

Guide on triggering a jQuery accordion panel to expand through a link located in another accordion panel

Can anyone assist with a problem I'm encountering in implementing accordion panels? Specifically, I have 5 accordion panels and I'm having difficulty creating a link in panel 1 that will open panel 4. Any suggestions on how to achieve this? ...