How to trigger function on viewport visible with Vue viewport plugin

Asked By: Anonymous

I am using an counter to display some numbers, but they load up when the page loads, so it loads unless I do some button to trigger it.
Found this viewport plugin ( but I weren’t able to use it. That’s what I need to do, trigger a function when I reach some element (entirely), how to achieve it?


Answered By: Anonymous

You don’t necessarily need a package to do this. Add an event listener to listen to the scroll event, and check if the element is in the viewport every time there’s a scroll event. Example code below – note that I’ve added an animation to emphasize the “appear if in viewport” effect.

Codepen here.



new Vue({_x000D_
  el: '#app',_x000D_
  created () {_x000D_
    window.addEventListener('scroll', this.onScroll);_x000D_
  destroyed () {_x000D_
    window.removeEventListener('scroll', this.onScroll);_x000D_
  data () {_x000D_
    return {_x000D_
      items: [_x000D_
        6, _x000D_
        7, _x000D_
        8, _x000D_
        9, _x000D_
        10, _x000D_
        11, _x000D_
      offsetTop: 0_x000D_
  watch: {_x000D_
    offsetTop (val) {_x000D_
  methods: {_x000D_
    onScroll (e) {_x000D_
      this.offsetTop = window.pageYOffset || document.documentElement.scrollTop_x000D_
    isElementInViewport(el) {_x000D_
      var rect = el.getBoundingClientRect();_x000D_
      return (_x000D_ >= 0 &&_x000D_
        rect.left >= 0 &&_x000D_
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&_x000D_
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)_x000D_
    callbackFunc() {_x000D_
      let items = document.querySelectorAll(".card");_x000D_
      for (var i = 0; i < items.length; i++) {_x000D_
        if (this.isElementInViewport(items[i])) {_x000D_


.card {_x000D_
  height: 100px;_x000D_
  border: 1px solid #000;_x000D_
  visibility: hidden;_x000D_
  opacity: 0_x000D_
.in-view {_x000D_
  visibility: visible;_x000D_
  opacity: 1;_x000D_
  animation: bounce-appear .5s ease forwards;_x000D_
@keyframes bounce-appear {_x000D_
  0% {_x000D_
    transform: translateY(-50%) translateX(-50%) scale(0);_x000D_
  90% {_x000D_
    transform: translateY(-50%) translateX(-50%) scale(1.1);_x000D_
  100% {_x000D_
    tranform: translateY(-50%) translateX(-50%) scale(1);_x000D_

<div id="app" onscroll="onScroll">_x000D_
  <div v-for="item in items" class="card">_x000D_




Another option is to use an intersection observer – I haven’t explored this yet but this tutorial seems good: Note that you will need a polyfill for IE.

Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen Windows 10 Lisans Office 2019 Mac Satın Al follower kaufen instagram follower kaufen porno