Utilize the dimensions of one image to resize others using the JavaScript method .getBoundingClientRect

I am attempting to transfer the width and height measurements of the initial image to all subsequent images on the page.

Currently, I have successfully applied the dimensions of the first image to the second one, but I am facing difficulties with the third, fourth, and so on...

As a newcomer to JavaScript, I acknowledge that there may be a simple mistake in my approach.

You can view the current status here: https://codepen.io/GBol/pen/GRXWvJY

<div class="boxA">   
  <img class="landscape"src="http://placekitten.com/800/400">
</div>

<div class="boxB">   
  <img class="portrait"src="http://placekitten.com/400/800">
</div>

<div class="boxC">   
  <img class="portrait"src="http://placekitten.com/400/800">
</div>






.boxA {
  width: 20%;
  border: solid blue;
  display: block;
  float: left;
 }

.boxB {
 border: solid blue;
 display: block;
 float: left;
 }

.landscape {
width: 100%;
display: block;
} 

.portrait {
height: 100%;
/** to center horizontally **/
margin: auto;
display: block;
}






var boxA = document.querySelector(".boxA"),
boxB = document.querySelector(".boxB")

function copyHeight(from,to){
to.style.height = from.getBoundingClientRect().height + "px"
}
copyHeight(boxA,boxB)

function copyWidth(from,to){
to.style.width = from.getBoundingClientRect().width + "px"
}
copyWidth(boxA,boxB)

Answer №1

When using the querySelector method, it will only return the first matching element. If there are multiple elements that match the selector, only the first one will be selected.

To apply a function to all elements on the page with the class of boxB, you should use the querySelectorAll method to select them all.

You will then need to iterate over each selected element and run the function for each one. One way to do this is by using the forEach() method.

The forEach method takes a function as an argument, which will be executed for every element in the array or nodelist. This function will receive each element as a parameter, allowing you to reference it within the function. Here is an example of such a function:

(box) => {
  copyHeight(boxA, box)
  copyWidth(boxA, box)
}

Instead of writing the function in the traditional way, you can opt for the "fat arrow" syntax for better readability:

(box) => {
  copyHeight(boxA, box)
  copyWidth(boxA, box)
}

Putting it all together, your final code may look like this:

const boxA = document.querySelector(".boxA")
const boxB = document.querySelectorAll(".boxB")

boxB.forEach((box) => {
  copyHeight(boxA, box)
  copyWidth(boxA, box)
})
    
function copyHeight(from, to){
  to.style.height = from.getBoundingClientRect().height + "px"
}

function copyWidth(from, to){
  to.style.width = from.getBoundingClientRect().width + "px"
}

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

Achieving success was like uncovering a hidden treasure chest after a successful

Is there a way to address this JSON data issue? success{"data": [{"id":"1","name":"something1"},{"id":"2","name":"something2"},{"id":"3","name":"something3"}] } The success variable contains the JSON data. This is how the server script returns the data: ...

Developing a calendar with limited availability for selecting future dates and restricting the ability to choose past dates

I am currently working on creating a calendar in Vue.js that allows users to select dates only from the current day up to the next 30 days. Dates prior to the current date are disabled, as well as dates beyond the initial 30-day period. While I have exper ...

Tips for extracting HTML entities from a string without altering the HTML tags

I need assistance with removing HTML tags from a string while preserving html entities like &nbps; & é < etc.. Currently, I am using the following method: stringWithTag = "<i> I want to keep my ->&nbsp;<- element space, bu ...

Only certain fields are returned by JQuery's form serialize() method

Encountering an issue with the serialize() function in jQuery when attempting to submit a serialized form via AJAX. Some of the field values are not being retained. Suspecting a problem with either my HTML structure or jQuery code: <div id="register" ...

Integrate a post AJAX call into an Angular service for seamless functionality

I have come across an interesting scenario where I have to integrate old ajax code into a new Angular 10 application as per project requirements. Is it possible to directly run the existing ajax calls in the Angular service? Or, is there any node module ...

Submitting data with AJAX to a NodeJS server

I have experience creating basic web applications where data is transmitted via HTTP parameters. However, I am currently attempting to send data from the client-side that includes an array (a list of ingredients for a recipe) and potentially a user-uploade ...

if jade is being inconsistent

I am currently using expressjs in my app and have the following setup: app.get('/profile',index.profile); app.get('/',index.home); Within layout.jade, I have the following code: ... if typeof(username)!=='undefined' ...

Tips for accessing the 'index' variable in *ngFor directive and making modifications (restriction on deleting only one item at a time from a list)

Here is the code snippet I'm working with: HTML: <ion-item-sliding *ngFor="let object of objectList; let idx = index"> <ion-item> <ion-input type="text" text-left [(ngModel)]="objectList[idx].name" placeholder="Nam ...

Transferring User ID from Google Tag Manager to GA4 Problem

I'm currently working on a new project and adding some dummy data to the dataLayer of Google Tag Manager from the \_app.tsx file. <Script id="gtg" strategy="beforeInteractive"> { window.dataLayer = window.dataLayer || &b ...

Validation for a datepicker embedded within a table

I'm facing a challenge and need some assistance. I want to validate if the "FROM (DATE)" is greater than the "TO (DATE)" without disabling the date selection, but instead prompting the user if the condition is not met. Any insights or solutions would ...

When imported, Node / JS instantly generates a new instance

Is there a way to instantiate a class without importing it first and using new afterward? Instead of var mainClass = require('../dist/main'); // has "class Main { ... }" var mainInstance = new mainClass(); I am looking for something like var ...

What is the best way to organize products based on the proximity of users using MongoDB's Geospatial Queries

I'm currently working on a web application that connects users with neighbors to buy and sell products. The app is built using node.js, JavaScript, mongodb, and mongoose. My main issue lies in sorting the products. I want to display products from nea ...

Exclusively Bootstrap-Timepicker

Is there a way to create a textbox with a time picker only? I am looking for guidance on how to do this using the following example: http://jsfiddle.net/RR4hw/11/ jQuery("#startDate").on("dp.change",function (e) { jQuery('#endDate').data("DateTi ...

Extracting precise information from HTML documents

Looking to extract specific data from an HTML file using C# and HtmlAgilityPack. Here is a snippet of the HTML: <p class="heading"><span>Greeting!</span> <p class='verse'>Hi!<br> // Hello!</p>& ...

The button text in Bootstrap 5 is black instead of white as shown in their demo

During the installation of Bootstrap 5, I encountered an issue where many of my buttons are displaying a black font instead of the expected white font as shown in the Bootstrap 5 Documentation For instance, the .btn-primary button on the official Bootstra ...

I encountered a NextJS error while trying to implement getStaticProps(). Can someone help identify the issue at hand?

I'm encountering an issue while using getStaticProps(). I am working with nextjs and passing the returned value as props to a component. Despite trying various methods such as await and JSON.stringify(), nothing seems to be effective in resolving the ...

Best practices for integrating JavaScript with PHP and MySQL

When it comes to inserting data into a MySQL database from JavaScript, I typically use AJAX with jQuery's $.POST function and PHP's mysqli function. This allows me to send the data to a PHP script which then inserts it into the database. Here is ...

Utilize identical selectbox across various tabs

Using jQuery, I have implemented multiple tabs with different appearances. The challenge I am facing is related to a selectbox that is shared across all tabs. My goal is to synchronize the values and selected option of this selectbox among all tabs. In oth ...

My Node JS program becomes unresponsive when reaching the resolve() method

I encountered a problem with my Node.js application when trying to list AWS Cognito users. The issue arises only when the number of Cognito users exceeds 60. API Reference Below is the snippet of my code. function checkUserPermissions(cognitoidentityse ...

Linking asynchronous AJAX requests using Angularjs

Currently in my AngularJS project, I have created a service with multiple functions that return promises. The AJAX Service I've Created: angular.module('yoApp') .factory('serviceAjax', function serviceAjax($http) { return ...