0

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";

}
Adam Azad
  • 10,675
  • 5
  • 25
  • 63
Megan
  • 3
  • 1

2 Answers2

0

I would put my check in a function, run it initially, and assign the function to window.resize property:

function checkWinSize(){

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

}

checkWinSize(); // intial check
window.onresize = checkWinSize; // check when window is resized

A drawback with window.onresize is that it's a property so it cannot have multiple functions. In case you might do other things window is resized, use addEventListener

window.addEventListener('resize', checkWinSize);
Adam Azad
  • 10,675
  • 5
  • 25
  • 63
0

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>
AHAY
  • 156
  • 1
  • 5