Calculate the pixel distance between various divs by measuring the horizontal distance from the left border to the right

I am trying to find the precise distance between :

  1. #main div left edge to the first div with class="b"
  2. between the first div with class="b" to the second div with class="b"

It's worth noting that the divs may be arranged randomly and could have fixed positions, leading to gaps between them. Simply calculating the width of all the divs with class="a" won't provide a solution in this scenario.

<div class="main">
    <div class="a"></div>
    <div class="b"></div>
    <div class="a"></div>
    <div class="a"></div>
    <div class="a"></div>
    <div class="b"></div>
    <div class="a"></div>
    <div class="a"></div>
    <div class="b"></div>
</div>

My current approach:

    $(".main").children(".a").each(function() {
        $(this).nextUntil(".b").length  /* I believe this gives me the required distance */
        console.log($(this).siblings(".b").prev(".a").html());
        var diff  = $(this).offset().top - $(this).nextUntil(".b").offset().top
        // in this case, the two values are the same, resulting in zero 
        console.log('diff' + diff);   
    });

Answer №1

Utilize the offsetTop property within the DOM element.

The code snippet should be as follows:

$(".main b")[0].offsetTop

Alternatively, you can use pure jQuery like this:

$(".main b").offset().top // This will provide the top offset of the first matching element

To calculate the distance between consecutive divs, you can implement a simple for loop over the elements in $(".main b"):

var elements = $(".main .b");
var offsets = []; // An array to store the offsets of elements
var distance = []; // An array to store the distance between each element
for (var i = 0; i < elements.length; i++) {
  var offset = $(elements[i]).offset().top;
  offsets.push(offset);
  if (i == 0) {
    distance.push(offset);
  } else {
    distance.push(offset - distance[i - 1]);
  }
}

console.log(offsets);
console.log(distance);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <div class="a">some</div>
  <div class="b">some</div>
  <div class="a">some</div>
  <div class="a">some</div>
  <div class="a">some</div>
  <div class="b">some</div>
  <div class="a">some</div>
  <div class="a">some</div>
  <div class="b">some</div>
</div>

Check out the JSFiddle link as well.

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

What is causing the spinner with CSS rotation transform to bounce rhythmically?

In my design, I have created a simple Spinner icon in Figma. It's meant to be perfectly aligned at the center of an enclosing frame that has dimensions of 64x64. To achieve the rotating effect, I applied CSS rotation as shown below: let rotation = ...

What is the correct way to use setInterval in a React component's constructor?

I'm trying to set an interval when the main component renders. I attempted to do this in the constructor like so: constructor(props) { super(props); this.props.fetchUserInfo(); this.props.fetchProducts(); setInterval(console.log(&a ...

Get the @html.dropdownlistfor filtered for me

Currently, I am working on a project that requires me to filter the options in my second dropdown list based on the selection made in the first dropdown list. While the concept is clear, implementing it becomes tricky as I lack expertise in jQuery or JavaS ...

Tips on searching for an entry in a database with TypeScript union types when the type is either a string or an array of strings

When calling the sendEmail method, emails can be sent to either a single user or multiple users (with the variable type string | string[]). I'm trying to find a more efficient and cleaner way to distinguish between the two in order to search for them ...

Adjusting the height of an Angular CDK virtual scroll viewport based on dynamic needs

Currently, I am developing an Angular table with the cdk Virtual Scroll feature. Is there a method to adjust the scroll viewport's height dynamically? While the standard style property works, I am encountering difficulties setting the value using ngSt ...

What is the best way to specify jQuery scroll preferences?

I need to make a simple adjustment to an existing jQuery code where I have to add a callback function that will be executed after the scrollTo action is complete. The challenge lies in passing additional settings while calling this method. After some rese ...

The Angular component is failing to display the template

After following a tutorial on UI-Router () I have implemented the following states in my Angular application: angular .module('appRoutes', ["ui.router"]) .config(['$stateProvider', '$urlRouterProvider', function($sta ...

Another option for handling a series of conditional statements instead of a bulky

Can someone help me with a coding issue I'm facing? I have an application that contains a large number of buttons which I need to trigger using keyboard presses. Currently, I am using a switch statement for this purpose. However, as the number of butt ...

Eliminate unnecessary white space on your webpage using CSS with the 960.gs grid system

As I work on building my portfolio website from scratch, I came across a CSS framework known as "960.gs". While I have experience with similar tools, this is my first time delving into a pure CSS framework, so I'm feeling a bit out of practice. Here ...

Verify the presence of a GET parameter in the URL

Working on a simple log in form for my website using Jade and ExpressJS. Everything is functioning correctly, except for one issue - handling incorrect log in details. When users input wrong information, they are redirected back to the log in page with a p ...

Progressing through the Material UI LinearProgress bar in steps

How can I split a progress bar into more steps to achieve a design like this? https://i.stack.imgur.com/lRMj6.png I attempted using this code but couldn't find an option for splitting: <LinearProgress variant="determinate" classes={{ ...

convert HTML string into a React component using a customized parser

I received an HTML string from the server that looks like this: <h1>Title</h1>\n<img class="cover" src="someimg.jpg">\n<p>Introduction</p> My goal is to modify the HTML by replacing the <img class="cover" src="s ...

What causes the disappearance of the figure under slider control?

One of the functionalities I am working on involves using three.js to dynamically adjust the rotation speed of a cube by utilizing a slider control. After setting up the scene, camera, and cube, the JavaScript code that controls the rotation speed looks li ...

Navigating links with Jinja using jQuery and AJAX

A series of items from the workshop variable are being shown by iterating through each item in a sequence. {% for car in workshop %} <div id="newDiv" > <a class="carsInWorkshop" title="{{car.carId}}" href="./getPriceforCar/{{car.carId}}"& ...

Tips for capturing audio on a smartphone browser?

Looking to capture audio in the browser on both iOS and Android devices. What solutions are currently available (as of October 2013)? What is the rate of acceptance of WebRTC by various browser developers? ...

Styling input[type='date'] for non-Chrome browsers with CSS

Looking for the css equivalent of: ::-webkit-datetime-edit ::-webkit-datetime-edit-fields-wrapper ::-webkit-datetime-edit-text ::-webkit-datetime-edit-month-field ::-webkit-datetime-edit-day-field ::-webkit-datetime-edit-year-field ::-webkit-inner-spin-bu ...

Utilizing UIWebView for dynamic HTML templating

Greetings! I am seeking to develop an HTML template (either internal or external) for the data received from an XML request. The following code has been functioning smoothly thus far: NSString* desc = [screenData.jsonVars objectForKey:@"descriptionTXT ...

Exploring the Lifecycle Methods in ReactJS / Issue Resurfacing in the Code Snippet

I recently started learning ReactJS and discovered the concept of lifecycles. However, I have a question about how componentDidUpdate() works and why it behaves in a certain way. To illustrate this, I am sharing a simple code snippet below that calculates ...

Unable to retrieve the chosen option from the datalist

I am encountering an issue with a datalist where I can't seem to retrieve the value that is currently selected when a button is clicked. Despite following recommendations from various posts on Stack Overflow, my code still returns undefined. Interesti ...

Troubleshooting a glitch in AngularJS involving the interaction of multiple controllers and Gr

Struggling to make multiple controllers work with Grunt. It's not just a Grunt issue - even combining the files manually doesn't solve the problem. My goal is to use Grunt to build the application, with one controller per file to gradually expand ...