Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace page based on screen size

I'm trying to redirect pages based on the screen sizes, I have two different index files, one is for a mobile version of the web and the second one is for a web version.

on the web version index file I've included:

<script>
    if (screen.width <= 767) window.location.replace("./m/index.html")
        else window.location.replace("index.html")
</script>

and on the mobile index page I've included:

<script>
    if (screen.width >= 767) window.location.replace("../index.html")
        else window.location.replace("index.html")
</script>

The problem is two of these index pages keeps refreshing, the pages aren't loaded.

what seems to be the problem here, appreciate your help.

like image 278
user2317954 Avatar asked Mar 16 '26 09:03

user2317954


1 Answers

You can use the resize javascript event, as Tushar said.

window.addEventListener("resize", getTemplate);

CurrentPage = 'DesktopPage';

function getTemplate() {
    if (screen.width >= 767 && CurrentPage != 'DesktopPage') {
        return window.location.replace("desktop.html");
    }

    if (screen.width < 767 && CurrentPage != 'MobilePage') {
        return window.location.replace("mobile.html");
    }
}

getTemplate();

This will check your current page and the screen size, because there is no sense to redirect to the Desktop page if you already are in the Desktop page.


You also can add more versions, like a "SmallerMobilePage".

window.addEventListener("resize", getTemplate);

CurrentPage = 'SmallerMobilePage';

function getTemplate() {
    if (screen.width >= 767 && CurrentPage != 'DesktopPage') {
        return window.location.replace("desktop.html");
    }

    if (screen.width < 767 && CurrentPage != 'MobilePage') {
        return window.location.replace("mobile.html");
    }

    if (screen.width <= 480 && CurrentPage != 'SmallerMobilePage') {
        return window.location.replace("smaller_mobile.html");
    }
}

getTemplate();
like image 153
Iago Avatar answered Mar 18 '26 23:03

Iago



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!