I want to show a JavaScript alert only on mobile devices.
because my website is not responsive on mobile so I want to alert users to visit on desktop.
I want to show a JavaScript alert only on mobile devices.
because my website is not responsive on mobile so I want to alert users to visit on desktop.
use The read-only Window property innerWidth to detect the viewport size then you can be fancy with your code or can keep it simple like the follwing,
// create a function that will be called based on the size of a specific viewport
function reportWindowSize() {
//check if the viweport size is less then 1200px
if (window.innerWidth < 1200) {
// Ignore the following two lines of code; they were written for
// testing on DOM; you can even use this one if you want to.
// const body = document.querySelector("body");
body.innerHTML = "Please go to my desktop site to see the awesome
content.";
// your code
// notify the user to visit the desktop site with an alert()
alert("Please go to my desktop site to see the awesome content.");
};
// Add a Window: resize event to the Window interface to force a reload of the
// page if the viewport size is greater than or equal to 1200px.
window.addEventListener("resize" , () => {
// check if viewport width is greater than or equal to 1200px.
if (window.innerWidth >= 1200) {
// reload/refresh the page
location.reload();
};
});
};
// call your function when page loads
window.onload = reportWindowSize;
// call your function when viewport resize
window.onresize = reportWindowSize;