Jelena Ajdukovic
Jelena Ajdukovic

Reputation: 351

Detect event when scroll is on bottom of div Vue

Scroll event @scroll="onScroll" in div not working. I need to detect when scroll is on bottom of div.

<template>
  <div>
    <button @click="showCountries = !showCountries">Show countries</button>
    <div
      v-bind:class="countriesContainerClass"
      v-if="showCountries"
      @scroll="onScroll"
    >
      <ul>
        <li
          v-for="country in createChunk(countries, 20)"
          v-bind:key="country.iso2"
          v-bind:class="countryItemClass"
        >
          <div v-bind:class="countryFlagClass">
            <img class="product_image" :src="country.flag" />
          </div>
          <div v-bind:class="countryNameClass">{{ country.name }}</div>
        </li>
      </ul>
    </div>
  </div>
</template>

This is my onScroll method.

   onScroll({ target: { scrollTop, clientHeight, scrollHeight } }) {
      console.log("scroll"); // I don't get "scroll" in console.
      if (scrollTop + clientHeight >= scrollHeight) {
        console.log("bottom");
      }
    },

Upvotes: 0

Views: 13822

Answers (1)

Lucas David Ferrero
Lucas David Ferrero

Reputation: 1902

First, you should check if you're listening scroll event in the proper element. An Element fires this event when the element itself has scroll, not its parent or children.

In other words: An element that has a fixed height (example: height: 100px or max-height) and an overflow-y: auto || scroll, will fire scroll event when the user scrolls in that particular element.

Now, in your case, the div element is not the one that generates the scrollbar, so it will not fire the scroll event. Identify correctly what element paints the scrollbar, and then attach the scroll event to it.

Then, for detecting if a scroll has reached the end (is in the bottom), you could try:

onScroll(e) {
  const { scrollTop, offsetHeight, scrollHeight } = e.target
  if ((scrollTop + offsetHeight) >= scrollHeight) {
    console.log('bottom!')
  }
}

I've a working example at codepen for you to check it out. You should open the codepen console at the bottom left to se the logs. https://codepen.io/LucasFer/pen/MWOQMLX

Upvotes: 4

Related Questions