I'm trying to redirect user who access a site to a mobile site. This is what I have done so far but the problem is that the function keeps running every time when the page loads. The functions gets called after the page loads. I'm a JavaScript beginner.
function redirectPage() {
var runOnce = 0;
if (runOnce == 0 && windowWidth <= 767){
runOnce = 1;
window.location.assign("example.net/mobile-site");
}
else if (runOnce == 0 && windowWidth >= 767){
runOnce = 1;
window.location.assign("example.net/regular-site");
}
}
UPDATE
This is what I did but so far the browser keeps loading again and again.
var windowWidth = 0;
$(document).ready(function(){
checkBrowserWidth();
redirectPage();
});
function checkBrowserWidth() {
windowWidth = window.outerWidth;
}
function redirectPage() {
if (typeof(Storage) != 'undefined') {
// Store value
localStorage.setItem('runOnce', 0);
}
var runOnce = localStorage.getItem('runOnce');
if (runOnce == 0 && windowWidth <= 767){
localStorage.setItem('runOnce', 1);
window.location.assign("example.net/mobile-site");
}
else if (runOnce == 0 && windowWidth >= 767){
localStorage.setItem('runOnce', 1);
window.location.assign("example.net/regular-site");
}
}