views:

349

answers:

2

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>
+2  A: 

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.

Marc Novakowski
+2  A: 

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.

WindPower