This seems basic but i can't wrap my head around it.Honest ain't got no clue but what i need is set the image width in percentage just like in css file but this time around i wonna know the method or technique used to do that.
Example..
//I have tried this but it didn't work
//var image_width_from_server=(the_img_width_from_php);
//image_width_from_server=image_width_from_server/$(parent).width()*90
//Now the result i get from the console does not match the browser set width of the image's p-ercentage width.
#parent{
width:250px;
height:250px;
background:deepskyblue;
border:5px;
}
#parent img{
width:90%;/**Now how can i do this in javaScript..?*/
height:auto;
}
/**Please note that direct css code won't help.
I need a way in javaScript to set the image's width using percentage but also basing on both the image's width size and the parent width size too.
*/
<div id='parent'>
<img src='https://i.vimeocdn.com/video/584087165_780x439.jpg'/>
</div>
Please note that direct css code won't help. I need a way in javaScript to set the image's width using percentage but also basing on both the image's width size and the parent width size too.
Am really out-of ideas, Any help appreciated.
Thanks
</div>
First select your image and after that you can set the width from js.
$('#parent > img').css('width', '90%');
new width = ( old width / 100 ) * percentile ?
If you want to use vanilla JavaScript instead of JQuery you can use .offsetWidth
to retrieve element width, and then:
var newWidth=document.getElementById("parent").offsetWidth * 0.9; // Get 90% of parent width
document.getElementById("img").style.width = newWidth + "px"; // Set the new width
Another simple solution that avoids using a calculation consists on setting the width percentage directly (still using vanilla JavaScript)
document.getElementById("img").style.width = "90%";