How To Detect Horizontal and Vertical Scroll on JavaScript (VueJs)
In this article, I would like to show how to detect a horizontal and vertical scroll movement by using JavaScript.
This can be useful if you would like to perform some actions on scrolling. For example, if you would like to show a pop-up window.
Vertical Scroll
One of the easiest ways to detect vertical scroll is actually to use window.scrollY.
const scroll = window.scrollY // Get scroll position
By using this method you can check window scroll position and use it as you wish.
Vertical Scroll in VueJs
Detecting scroll in VueJs can be slightly different than simple JavaScript and in order to have the same results you have to use “destroyed” and “created”.
How it works?
destroyed() {
window.removeEventListener('scroll', this.actionScroll);
},created() {
window.addEventListener('scroll', this.actionScroll);
}methods:{
actionScroll (event) {
const scroll = window.scrollY;
console.log(scroll) // shows pixel position of window scroll // You can also perform any action while using this method}
}
Horizontal Scroll
On simple JavaScript, you can use again the same system of window.scroll but this time you have to use scrollX.
const scroll = window.scrollX
Horizontal Scroll in VueJs
Here comes one of the initial reasons why I wanted to write this article — it is the problem that I got while trying to detect a horizontal scroll of a div. In my case, it was a timetable with a sticky header. The header was not following the whole timetable’s columns in a fixed position.
What I did to solve this problem and how actually can we detect the horizontal scroll of an element in VueJs?
First of all our element have to have an ID to be able to find it among the others or in my case I was using $refs which makes it much easier.
<div
id="scroll-div"
ref="scrollDiv"
>
Then, to be able to get horizontal scroll position you need to create a function in “mounted” and to get scrollLeft of the element.
const scroll = this.$refs.scrollDiv; // We found the divscroll.addEventListener('scroll', () => {
const scrollPosition = this.$refs.scrollDiv.scrollLeft;
console.log(scrollPosition) // We saved the scroll position and check it with console log for any further actions }, false)
That’s it! 😊
I hope this article was useful for you if you found yourself in the same situation as I did.