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 myself. I also wanted to create one, just in case I succeeded.
On that website, I found GlobeKit created by Rally. It seems to switch styles by listening to scroll events, so I looked into how to listen to scroll events.
Listening to Mouse Scroll on PC#
Listening#
Depending on the browser, add a scroll event listener to the page in the mounted function. scrollFun is the function that will be executed when scrolling 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: if positive, it means scrolling up
// "event.detail" property value in DOMMouseScroll event: if negative, it means 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 scroll events on mobile devices because they don't have a mouse.
To achieve the desired effect, I hide the scroll bar 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 touch:
- touches: an array of touch objects for the current touch operations.
- targetTouches: an array of touch objects specific to the event target.
- changeTouches: an array of touch objects that have changed since the last touch.