1

I have an element in my html code

<div class="my_div">
</div>

Now i want to alert when user scrolled to this element.How can i do that using Vue considering that my_div is in the center of the page?

for rent
  • 105
  • 2
  • 8
  • 1
    I don't think vuejs provides any API for this function, but there're various ways to achieve this. See: https://stackoverflow.com/questions/487073/check-if-element-is-visible-after-scrolling – choasia Aug 21 '17 at 01:12

1 Answers1

0

You should use the vue $ref.

HTML

<div id="PAGE-MAIN-PARENT-DIV" v-scroll="handleScroll">
  <div ref="my_div" > </div>
</div>

JS

Vue.directive('scroll', {
  inserted: function (el, binding) {
    let f = function (evt) {
      if (binding.value(evt, el)) {
        window.removeEventListener('scroll', f)
      }
    }
    window.addEventListener('scroll', f)
  }
})

Inside Vue methods:

methods: {
    handleScroll (evt, el) {
      if (!this.$refs.my_div) {
        return false
      }

      const emissionYOfsset = this.$refs.my_div.$el.offsetTop

      // Change this condition in order to fit your requirements
      if (window.scrollY + window.innerHeight >= emissionYOfsset &&
        window.scrollY <= emissionYOfsset) {
        console.log('currently in screen')

        // Do you want to continue with the event?
        return false
      }
    }
  }
Jesús Fuentes
  • 919
  • 2
  • 11
  • 33