2

I am using jquery window.resize function with location.reload method because I want to reload my page when mobile user change from portrait to landscape and its working great in my desktop browser while I change my window size but when I get it in mobile my window.resize event getting fired every time when I scroll up or down in mobile. I dont know why its happening on scroll event when it is supposed to be happened only on portrait and landscape.

Here is my code.

$(document).ready(function () {
function resize() {
    alert("Hello")

resize();
});

$(window).resize(function() {
    location.reload();      
}); 

So where its going wrong and whats the solution?

  • PLease post a jsFiddle with a working example. Also, your code is missing at least a closing brace. – A. Rama Dec 19 '14 at 07:54
  • I tried with chrome on android and the resize event while scrolling is fired *only* when the address bar happens to appear or disappear and that's correct, since the visible page actually resizes. And if I may put forth some suggestion, reloading the page on a resize event is not a good idea. – A. Rama Dec 19 '14 at 08:01
  • If you're trying to reload based on changing portrait<->landscape, you want to check the orientation change. Try this answer: http://stackoverflow.com/questions/850472/how-do-i-detect-when-the-iphone-goes-into-landscape-mode-via-javascript-is-ther/850475#850475 – Matt Sach Dec 19 '14 at 16:50

1 Answers1

1

Use the window.onorientationchanged event to detect the change in orientation and avoid this issue. This is a common issue using the onresized event on mobile devices. Any time a menu bar or keyboard is shown by even 1 pixel it will fire this event. If you need to get the orientation also, use window.orientation. Check out this thread: How do I detect when the iPhone goes into landscape mode via JavaScript? Is there an event for this?

window.orientation will return 0 for default, or -90,90,180 for how many degrees clockwise from default it is rotated. Generally, 0 and 180 are portrait, and -90 and 90 are landscape, but this can vary by device. Check out this link for more: http://davidwalsh.name/orientation-change

Example:

$(document).ready(function () {
    $( window ).on( "orientationchange", function( event ) {
        location.reload();  
    });
});
Community
  • 1
  • 1
Brino
  • 2,442
  • 1
  • 21
  • 36