简体   繁体   中英

Screen width as a condition to redirect to other url during on load

i have a website and i was wondering if it is possible to set a condition in which when the screen is less than a certain size it will automatically open a different url?

the mobile version of website is completely different than my desktop one, so basically all i am asking is if it passible to load a different INDEX.html when the request comes from a smaller screen. also: is it possible to combine javascript, css and html only? (without jquery) thank you so much!

All the above can be solved simply with JavaScript.

First we need to get the width, so we can call window.innerWidth or document.clientWidth for that.

Next we need to redirect if it's under a certain amount of pixels, so use window.location .

Finally we need to run the function when the page loads and when the view is resized.

 function redirectMobileHandler() { const width = Math.max(document.clientWidth || 0, window.innerWidth || 0); if(width < 1000) { window.location = 'https://linktoyourmobilesite.com'; } } window.onload = redirectMobileHandler(); window.onresize = () => redirectMobileHandler();

Alternatively you can either do a user agent check either with window.navigator on the client side, or by the User-Agent header on the server side to determine what kind of device it is.

As you said you can catch the width on which you want to load the other page

 // when width equal 500px if (window.innerWidth === 500) { //window.location = "path to new page" }

hope this helped

The answers given are work as long as you are only concerned for the screen width of the browser. But if you need to capture the actual screen width of the device then you need to use the 'screen' property.

 function redirectToMobile() { if(screen.width < 1000) { window.location = 'YOUR LOCATION'; } } window.onload = redirectToMobile();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM