Search code examples
javascripthtmlbrowserresizewindow

Is there any way to make the site go to another page when the browser window is resized?


I'm using HTML5. In my Javascript file, I have the following code in my Javascript file to redirect mobiles users to the mobile site. However, is there a way to redirect to the mobile site as well when the browser window is resized to 480px or below? I looked everywhere and couldn't find any solutions anywhere.

if( screen.width <= 480 ||  /webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)  )  {     
window.location = "mobile.html";

}

Solution

  • One thing to note is that screen is the size of a desktop user's monitor, so it may not change. Instead, use jQuery to figure out the width of the browser's window, not the screen:

    <script src=https://code.jquery.com/jquery-1.12.4.js></script>
    
    <script type="text/javascript">
    
      window.onresize = function(event) {
        if ($(window).width() <= 480) {
            console.log('do stuff');
        }
      }
    </script>