HTML5 is different from PC Web development. In the previous articles, we learned how to develop H5 about HTML and CSS. Now, we will learn how to develop H5 about Javascript.
click 300ms delayโ
Click events in mobile browsers have a 300ms delay. Here are three solutions.
Disable page zoomingโ
We know that the root cause of click delay is page zooming, so we can disable page zooming to solve the problem at the source, but the disadvantage of this solution is obvious, the page cannot be zoomed.
<!-- user-scalable=no -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
Replace click event with touchEnd eventโ
document.addEventListener(
"touchend",
function (e) {
// do something
},
false
);
fastclickโ
fastclick is easy-to-use library for eliminating the 300ms delay between a physical tap and the firing of a click event on mobile browsers.
const attachFastClick = require("fastclick");
attachFastClick(document.body);
A matter of timeโ
The date format YYYY-MM-DD HH:MM:ss
is an error on Apple, but it is perfectly fine on Android. But the YYY/MM/DD HH:mm:ss
date format works on both Apple and Android, so we just need to stick with it.
const date = "2022-12-31 12:30:00";
new Date(date.replace(/\-/g, "/"));
Scroll to the specified positionโ
This technique works on both PC and mobile, Use Element.scrollIntoView() method, We no longer need to use window.scrollby()
and window.scrollto()
to scroll to a specified location.
element.scrollIntoView();
element.scrollIntoView(alignToTop);
element.scrollIntoView(scrollIntoViewOptions);
Listen for landscape and portrait eventsโ
window.addEventListener("resize", () => {
if (window.orientation === 180 || window.orientation === 0) {
console.log("landscape");
}
if (window.orientation === 90 || window.orientation === -90) {
console.log("portrait");
}
});
System themeโ
Sometimes to follow system themes to show dark and light themes, we can use media queries.
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
function darkModeHandler() {
if (mediaQuery.matches) {
console.log("dark mode");
} else {
console.log("light mode");
}
}
mediaQuery.addListener(darkModeHandler);
Further readingโ
You can read more about H5 development knowledge in the following articles: