Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DHTML: Get updated element size

I'm updating the src attribute of an <img> tag in javascript. After I've done this, I need to get the new height of its parent <div> so that I can update the size of other elements on the page. If I retrieve the parent's offsetHeight property directly after updating the image's src, however, I get the height before the change was made. Is there a way to force the browser to render the updated page so that I can get the new height?

Repro:

<html>
<head>
<script type="text/javascript">
    function changeImage(){
        document.getElementById("image").src = "b.jpg";
        // here I need to re-render the page
        alert(document.getElementById("parent").offsetHeight);
        // ^ alerts the height of a.jpg, not b.jpg (unless this is the second click)
    }
</script>
</head>

<body onclick="changeImage()">

<div id="parent">
    <img id="image" src="a.jpg" />
</div>

</body>
</html>
like image 303
P Daddy Avatar asked Jan 25 '26 02:01

P Daddy


2 Answers

If you don't need the new height right away, use Marc's solution. However, if you need the height right when the user clicks, you'll need to preload b.jpg. Then, I don't know if the height will be correct straight in the same function, but I suppose a setTimeout('alert(document.getElementById("parent").offsetHeight);',1); would alert the height within a millisecond.

like image 54
Etienne Perot Avatar answered Jan 27 '26 15:01

Etienne Perot


You might need to wait for the image to finish loading before the height is available. In your sample code, setting the "src" attribute will load the image (b.jpg) asynchronously so you may want to attach an "onload" hander on that element to be notified when it's finished loading and rendering.

like image 36
Marc Novakowski Avatar answered Jan 27 '26 15:01

Marc Novakowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!