This is the second way to check if the user scrolled to specified element in Vue.js/JavaScript.
I wrote the original tutorial in 2019. Instead of updating it, I decided to write a second part.
Let’s start by creating a new Vue.js method called isScrolledIntoView
:
isScrolledIntoView (el) {
let rect = el.getBoundingClientRect()
let elemTop = rect.top
let elemBottom = rect.bottom
let isVisible = elemTop < window.innerHeight && elemBottom >= 0
return isVisible
},
This function checks if the passed element is partially visible. If yes, it will return true
.
Now, let’s add another method called scroll
.
scroll () {
window.onscroll = () => {
let scrolledTo = document.querySelector('.replace-with-your-element')
if (scrolledTo && this.isScrolledIntoView(scrolledTo)) {
console.log('scrolled')
}
}
}
Now let’s initialise our method.
mounted () {
this.scroll()
}
That’s it, it will now print ‘scrolled’ every time your selected element is viewed on a page.
If you find this post useful, please let me know and share your favourite filters in the comments below.
Cheers,
Renat Galyamov
Want to share this with your friends?
👉renatello.com/vue-js-scroll
PS: You can also check how to get the first item in Vue.js array, how to add a class to body tag in Vue.js, How to hide uncompiled mustache {{ code }} in Vue.js, How to use Vue.js filters inside the Vue instance and other Vue.js tutorials.
not work again. everytime I scroll the document.querySelector(‘#cardList’),
it’s simply saying that it reach the bottom.
“`
let scrolledTo = document.querySelector(‘#cardList’)
if (scrolledTo && this.isScrolledIntoView(scrolledTo)){
console.log(‘bottom reached’);
}else {
console.log(‘not yet bottom’);
}
“`
If you see the ‘bottom reached’ text that means the code is working fine. What are you trying to achieve?