1

I'm trying to make an element hide on scroll within a div. I tried this tutorial https://codepen.io/neutraltone/pen/poobdgv, but it works when the complete window is scrolled. I could not make it work on the specific div.

  mounted() {
    this.lastScrollPosition = window.pageYOffset
    window.addEventListener('scroll', this.onScroll)
  },
  beforeUnmount() {
    window.removeEventListener('scroll', this.onScroll)
  },

I'm using Vuejs 3. I think the problem is, that I can't specifically point to the div. I tried it with this.$ref.name (using ref="name" on the div), instead of window, but something is not adding up.

Thanks in advance!

1 Answer 1

3

You could listen for the scroll event on the div using the v-on:scroll listener (or shorthand (@scroll) and then do whatever you want in the handler (in this case checking for scroll position and then hiding the element):

<template>
  <div class="scrollable-container" @scroll="scrollHandler">
    <div class="content">
      <div v-show="isVisible" class="to-hide">Scroll Me</div>
    </div>
  </div>
</template>

<script>

export default {
  data: function() {
return {
    isVisible: true
  };
},
  methods: {
    scrollHandler(e) {
      this.isVisible = e.target.scrollTop > 300 ? false : true
    }
  }
}
</script>

<style>

.scrollable-container {
  height: 500px;
  width: 300px;
  margin: 200px auto;
  overflow-y: scroll;
  border: 1px solid black;
}

.content {
  height: 1000px;
}

.to-hide {
  min-height: 500px;
  background-color: blue;
}

</style>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.