Define dimension in px based on dimension in%

3

I'm having trouble developing a resize script

function resizeImagePreview(){
    var imageHolder = document.getElementById("image-holder");
    imageHolder.style.width = "25%";
    console.log(imageHolder.style.width);
    imageHolder.style.height = imageHolder.style.width + "px";
    console.log(imageHolder.style.height);
}resizeImagePreview();

The script does not display any errors, however, the height of the element is not defined, what is causing the error and how to correct?

    
asked by anonymous 04.05.2017 / 23:59

2 answers

4

Your code:

function resizeImagePreview(){
    var imageHolder = document.getElementById("image-holder");
    imageHolder.style.width = "25%";
    console.log(imageHolder.style.width);
    imageHolder.style.height = imageHolder.style.width + "px";
    console.log(imageHolder.style.height);
}resizeImagePreview();

On the third line, you assign the value 25% to the width attribute. In the fifth line, you assign to the height attribute the value of width concatenated with the string px . Considering that the attribute will have the value 25% , given line 3, the value of height will be 25%px , which does not make any sense and the browser probably discards.

Now, if you intend to get the value in pixels that width has after being assigned 25% , then you should use the offsetWidth property of the element. It would look something like:

function resizeImagePreview(){
    var imageHolder = document.getElementById("image-holder");
    imageHolder.style.width = "25%";
    console.log(imageHolder.style.width);
    imageHolder.style.height = imageHolder.offsetWidth + "px";
    console.log(imageHolder.style.height);
}resizeImagePreview();

See the example:

function resizeImagePreview(){
    var imageHolder = document.getElementById("image-holder");
    imageHolder.style.width = "25%";
    console.log(imageHolder.style.width);
    imageHolder.style.height = imageHolder.offsetWidth + "px";
    console.log(imageHolder.style.height);
}resizeImagePreview();
#image-holder {
  background: blue;
}
<div id="image-holder"></div>
    
05.05.2017 / 00:15
0

If you understand correctly what you want, you need to read the width calculated by the browser and set the height based on it. Something like this:

var estilos = getComputedStyle(imageHolder);

// estilos.width já é uma string com 'px' no final.
// se quiser como número, usar parseInt(estilos.width, 10)
imageHolder.style.height = estilos.width;
    
05.05.2017 / 00:14