When I was bored and browsing Zhihu, I discovered a treasure trove website for front-end design called awwwards. I was amazed by the websites created by the experts on there, but at the same time, I was eager to try it out myself. I also wanted to create one, just in case I succeed.
On the website, I found GlobeKit written by Rally. It seems to switch styles by listening to scroll events, so I looked into how to listen to scroll events.
Scroll Event Listening on PC#
Listening#
Depending on the browser, add a scroll event listener to the page in the mounted function. The scrollFun is the method executed when a scroll event is detected.
// Browser compatibility
if ((navigator.userAgent.toLowerCase().indexOf("firefox") != -1)) {
document.addEventListener("DOMMouseScroll", this.scrollFun, false)
} else if (document.addEventListener) {
document.addEventListener("mousewheel", this.scrollFun, false)
}
Getting Scroll Event Information#
Retrieve scroll properties from the passed event object.
// Scroll page
scrollFun(event: any) {
// "event.wheelDelta" property value in mousewheel event: positive value indicates scrolling up
// "event.detail" property value in DOMMouseScroll event: negative value indicates scrolling up
const delta = event.detail || (-event.wheelDelta);
if (delta > 0 ) {
// Scroll down
console.log("Scroll down")
} else if (delta < 0) {
// Scroll up
console.log("Scroll up")
}
}
Touch Events on Mobile#
The above method cannot be used to listen to scrolling on mobile devices because they don't have a mouse.
To achieve the desired effect, I hide the scrollbar and listen to touch events to determine if the user is scrolling up or down.
- touchstart event: triggered when a finger touches the screen, even if there is already a finger on the screen.
- touchmove event: triggered continuously when a finger moves on the screen. Calling preventDefault() during this event can prevent scrolling.
- touchend event: triggered when a finger leaves the screen.
Adding Events#
The methods are called within double quotes.
<div id="main" @touchstart="touchstart($event)" @touchend="touchend($event)">
Retrieving Information#
Retrieve touch event information from the passed $event object.
Example:
touchstart(e: any): void{
this.startY = e.touches[0].pageY // Get the Y coordinate of the touch point
}
touchend(e: any): void{
const moveEndY = e.changedTouches[0].pageY // Get the Y coordinate when releasing the finger
......
}
By subtracting the two coordinates, we can determine if the user is scrolling up or down based on the positive or negative result.
The passed object includes three properties for tracking touches:
- touches: an array of touch objects representing the currently tracked touch operations.
- targetTouches: an array of touch objects specific to the event target.
- changeTouches: an array of touch objects representing what has changed since the last touch.