0

I have an image id="img1" with "width=100%;height:auto". And another image id="img2" ... in an almost un-related parentage, that needs to be fixed width but the same height as img1.

I found here: [Set height of <div> = to height of another <div> through .css that:

If you're open to using javascript then you can get the property on an element like this: document.GetElementByID('rightdiv').style.getPropertyValue('max-height');

And you can set the attribute on an element like this: .setAttribute('style','max-height:'+heightVariable+';');

So I tried:

var imgHeight = GetElementByID('img1').style.getPropertyValue('height');
.setAttribute('style','height:'+imgheight+'px';');

First issue is how to get it to work. Second is, would it resize when visitor resizes/rotates their device?

user801347
  • 1,165
  • 3
  • 14
  • 28
  • add it to "on document ready" and "on window resize" – Evik Ghazarian Nov 27 '19 at 18:48
  • `GetElementByID` should be `getElementById` and should be preceded by `document.`. The `.setAttribute` will not work because you closed the variable: `;`. Also, no, it will not adjust on resize. You'll have to create an event handler for window resize and put the code inside it for that to make it work. – icecub Nov 27 '19 at 18:49

1 Answers1

2

You need to get the second element in a similar way as you got the first one before you can apply setAttribute to it. However, you need to add document before your getElementById function.

Also, please note that GetElementByID will not work. Quote from the official docs:

The capitalization of "Id" in the name of this method must be correct for the code to function; getElementByID() is not valid and will not work, however natural it may seem.

It was also possible to write the height of the image a bit more simply, by just using .height instead of your original code.

To get it to resize when the user resizes the window, put all that code inside a function and then add two event listeners, one that fires upon loading the page and another that fires upon resize.

Here is the complete code:

window.addEventListener("load", resizeImage);
window.addEventListener("resize", resizeImage);

function resizeImage(){
   var imgHeight = document.getElementById('img1').height;
   document.getElementById('img2').height = imgHeight;
}
icecub
  • 8,615
  • 6
  • 41
  • 70
Run_Script
  • 2,487
  • 2
  • 15
  • 30