Reputation: 165
I'm trying to set the size of a background image to match the screen size upon window resize. The problem is that width and height don't alternate their values when I change the mobile orientation. When I test it in the dev tools of a desktop browser it works, however when testing in several mobile browsers, although the orientation does get changed, the measures don't.
This is the basic js:
$(function() {
function resizeBackground() {
$('#background-image').height(screen.height);
}
resizeBackground();
$(window).resize(resizeBackground);
});
Unfortunately due to a weird vh bug on iOS I'm forced to use JS. The issue here is that the background image jumps when the browser address bar of some browsers, specially Chrome and Firefox, gets hidden. It's detailed here: stackoverflow.com/questions/24944925/.
Upvotes: 2
Views: 4988
Reputation: 620
For Mobile Safari you can check window.orientation
and if it is 90/-90, choose smaller of width/height for your "height". When orientation is 0, then choose higher value. I have now observed that when opening Mobile Safari directly in landscape, the values are swapped and do not swap on orientation change. As window.orientation
is deprecated, it should only be used for Mobile Safari. FOr the rest, we use window.screen.orientation.angle
.
Upvotes: 0
Reputation: 4394
Summarizing my comments I want to describe why your solution doesn't work:
window.screen.height
and window.screen.width
get you the device's actual height and width and these values don't change on page resize or orientation change.
For the viewport sizes (you actually need viewport) the appropriate methods (variables) are window.outerWidth
and window.outerHeight
(in some cases window.innerWidth
and window.innerHeight
will work also).
For getting actual document size (html document), use document.documentElement.clientWidth
and document.documentElement.clientHeight
.
For detecting orientation change I would suggest orientationchange
event instead of onresize
event, because onresize
also fires when keyboard is shown for example.
Upvotes: 1
Reputation: 979
Those mobile browsers should support the more specific orientationchange
event. Perhaps they're only firing that one and not resize. Try handling orientationchange too.
window.addEventListener('orientationchange', resizeBackground);
Upvotes: 0