Calculating the Distance Between Elements within a Flex Container Using JavaScript

I am looking to calculate the margin left and right for children of a flex item

<div class="sec images" style="display:flex;justify-content:space-between">
  <img src="images/en_mb-mega-01.png" alt="">
  <img src="images/en_mb-mega-03.png" alt="">
  <img src="images/en_mb-mega-04.png" alt="">
</div>

While attempting to loop through the children, I found that it only provides me with the width of the child element. I actually need both the width and margins.

Note:

$(element).width()

did not work as expected

main.js file :
  var current_item_children = current_item.children();

$.each(current_item_children, function () {
  var this_item = $(this);
  children.push(
    {
      width: this_item.width(),
      outerWidth:this_item.outerWidth(false),
      height: this_item.height(),

    }
  );
});

Answer №1

Calculate the distance between the first and second elements in pixels:

window.addEventListener('load', () => {

  console.log(document.querySelectorAll('.containt')[1].getBoundingClientRect().left - document.querySelectorAll('.containt')[0].clientWidth);

})
.container {

  width: 400px;
  height: 200px;
  background-color: orange;
  display: flex;
  justify-content: space-between;
}

.containt {

  width: 50px;
  height: 50px;
  background-color: blue;
}
<div class=container>
<div class="containt">

</div>
<div class="containt">

</div>
<div class="containt">

</div>
</div>

Answer №2

This is the perfect resource for learning how to calculate the distance between HTML elements. Calculate the distance between two centers of HTML elements

 function getCenterCoordinates(element) {
   const {top, left, width, height} = element.getBoundingClientRect();
   return {
     x: left + width / 2,
     y: top + height / 2
   };
 }

function findDistanceBetweenElements(a, b) {
  const aPosition = getCenterCoordinates(a);
  const bPosition = getCenterCoordinates(b);

  return Math.hypot(aPosition.x - bPosition.x, aPosition.y - bPosition.y);  
}

const distance = findDistanceBetweenElements(
  document.getElementById("x"),
  document.getElementById("y")
);
console.log(distance)
<div id="x"></div>

<div id="y" style="margin-left:100px;"></div>

Answer №3

$(document).ready(()=>{
            let current_images = $("div.sec").find('img');
            let image_dimensions = [];
            $.each(current_images, function () {
                var this_image = $(this);
                image_dimensions.push(
                    {
                    width: this_image.width(),
                    outerWidth:this_image.outerWidth(false),
                    height: this_image.height(),

                    }
                );
                console.log(image_dimensions);
                });
        });

Try out this new method!

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

Sending Objects Array in POSTMAN using Hapijs: A Step-by-Step Guide

Could you please assist me on how to send a POST request in POSTMAN for the given array of objects and then validate it using Joi in a hapi server? var payload = [{ name: 'TEST Name 1', answer: 'TEST Answer 1', category: &a ...

How can jQuery select an element by its id attribute by referencing the href attribute of a different element?

Whenever the user interacts with a div.nav element, jQuery switches its class to active. Presently, it applies display: block to all three of the div.content elements. I aim for jQuery to only apply the display: block property to the div.content elements t ...

Transferring information from one webpage to another using AJAX or embedding it with an iframe

I recently received an address with a basic HTML structure containing numbers. I attempted to display it using an iframe, which worked when tested separately but encountered a connection refusal error when embedded in my page. Alternatively, I tried AJAX ...

What is the process for setting an object's property as a href in an AJAX call?

I've got a quick query. How can I assign an object's property to the href attribute? I've indicated the line with a comment. success: function (listOfTags) { let tagData = ''; $.each(listOfTags, function (i, tag) { ...

Numerous slideshows using identical scripts

I am facing an issue with my code for multiple slideshows. Currently, it works fine for a single slideshow but when I have multiple slideshows and mouse over any of them, all the slideshows start running due to sharing the same class. However, if I try to ...

Adjusting the image placement within a modal window (using bootstrap 3)

Behold, an example modal: <!-- Large Modal --> <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"> <div class="modal-dialog modal-lg"> <div class="modal-content"> ...

Get the value of a CSS property in Python by parsing the rendered HTML

Currently, I am using Selenium and PhantomJS in conjunction with Python for the purpose of crawling rendered web pages. While it is a straightforward process to identify the presence of specific words within the HTML content (e.g. if "example" in html...), ...

What steps can I take to streamline this code and enhance its elegance in writing?

Working on some practice problems involving higher-order functions, I managed to solve this particular problem. However, the code I used feels somewhat messy and not as elegant as it could be. Is there a better way to combine map and reduce for a cleaner s ...

Tips to avoid conflicts between endpoints when building a REST API in an Express application

I am currently working with a REST API in an Express application to retrieve orders. http://localhost:2000/api/orders/chemists?orderBy=date&startDate=date1&endDate=date2 http://localhost:2000/api/orders/chemists?orderBy=chemist&startDate=date ...

Executing a JavaScript function within PHP code

I am working on a foreach loop that creates a series of checkboxes with items from a database. Currently, none of the checkboxes are pre-checked and each time a user checks one, a JavaScript function is called. Now, my clients want the first checkbox to b ...

Guide on building a Dynamic factory in AngularJS

For my project, I need to implement a dynamic factory in AngularJS with a unique name. Here is an example of what I am trying to achieve: function createDynamicFactory(modId) { return myModule.factory(modId + '-existingService', function ...

Utilize an icon within an input box using content and the :before pseudo-element instead of relying on

My problem is that I have a great font set up and I use it to add custom icons next to my buttons. (for example: check here) Now, I want to create an input box and place an icon before it like in this guide HERE Instead of using a background image, I wou ...

"Hidden panels in Sencha Touch only respond to show() and hide() methods after a resize event

Check out this demonstration of a Sencha Touch app by visiting this link. The button located in the bottom-left corner is supposed to show or hide the menu panel on top of the "Location info goes here" bar, but it seems to be functioning in an unexpected m ...

Troublesome CSS conflicts arise when using minified assets with AngularJS and Webpack

After transitioning my Angular project to the Webpack build system, I encountered issues with Angular Dependency Injection in the JS source code. Surprisingly, now I am facing JS errors that are targeting CSS files, leaving me completely bewildered about w ...

Choose an image to be displayed at either full width or full height, depending on which dimension is reached first

I have a query regarding resizing an image within a div to either 100% width or 100% height of the containing div. Despite setting max-height and max-width to 100% as recommended here, I still encounter overflow issues without wanting to crop the image usi ...

Troubleshooting a JSON response issue in CodeIgniter

As a beginner in the codeigniter framework and json, I am attempting to retrieve data from the database upon user clicking on a specific URL. However, I'm encountering an error. This is my script: function fetchUserData(i) { if(i == 1) { ...

Is there a way for me to determine the quality of a video and learn how to adjust it?

(function(){ var url = "http://dash.edgesuite.net/envivio/Envivio-dash2/manifest.mpd"; var player = dashjs.MediaPlayer().create(); player.initialize(document.querySelector("#videoPlayer"), url, })(); var bitrates = player.getBitrateInfoListFor("vid ...

Trouble arises with the chrome extension code for retrieving tweets from Twitter

I'm currently working on developing a Chrome extension that will display tweets featuring the hashtag perkytweets within the extension's popup. However, I'm facing an issue where nothing is being displayed. Let's take a look at the cod ...

Updating Angular 5 Views Dynamically Using a While Loop

I am facing an issue in my app where I have a progress bar that updates using a while loop. The problem is that the view only updates after the entire while loop has finished running, even though I am successfully changing the update progress value with ea ...

jQuery animation not executing as expected due to transition issues

I'm looking to create a cool effect where the previous quote disappears and a new one appears when I click on a button, all with a smooth transition effect. In my attempt below using jQuery .animate and opacity property, I'm struggling to make i ...