Skip to content Skip to sidebar Skip to footer

How Do I Get The New Dimensions Of An Element *after* It Resizes Due To A Screen Orientation Change?

I'm working on a mobile web app, and in my page I have a div element with its width set to 100%. I need to set the height of this div so that the height is correct for a set aspec

Solution 1:

A few methods for you to try:

(1) Set a timeout inside your orientationchange event handler so the DOM can update itself and the browser can draw all the changes before you poll for the new dimension:

$(window).bind('orientationchange', function (e) { 
    setTimeout(function () {
        // Get height of div
        var div   = $('#div'),
            width = div.width();

        // Set the height of the div
        div.css({ height: Math.ceil(width / ratio) });
    }, 500);
});

It won't make too big of a difference but note that Math.ceil takes a lot longer to complete (relatively) than Math.floor since the latter only has to drop everything after the decimal point. I generally just pass the browser the un-touched float number and let it round where it wants to.

(2) Use the window.resize event instead to see if that updated fast enough for you:

$(window).bind('resize', function (e) { 
    // Get height of div
    var div   = $('#div'),
        width = div.width();

    // Set the height of the div
    div.css({ height: Math.ceil(width / ratio) });
});

On a mobile device this will fire when the orientation changes since the size of the browser view-port will also change.

(3) If you are updating the size of this <div> element because it holds an image, just apply some CSS to the image to make it always be full-width and the correct aspect ratio:

.my-image-class {
    width  : 100%;
    height : auto;
}

Post a Comment for "How Do I Get The New Dimensions Of An Element *after* It Resizes Due To A Screen Orientation Change?"