How to check if the user scrolled to the top or bottom in Vue.js/JavaScript (part 2)

in General Write a comment

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.


Hi, I'm Renat 👋

 


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 arrayhow to add a class to body tag in Vue.jsHow to hide uncompiled mustache {{ code }} in Vue.jsHow to use Vue.js filters inside the Vue instance and other Vue.js tutorials.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment

2 Comments

  1. 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’);
    }
    “`