Search code examples
vue.jsscrollnuxt.jsvue-composition-api

How to detect scroll event when scrolling on a position fixed element


My project is built on nuxt.js with vue composition api

So, my scroll event is not firing because my container has overflow:hidden. Is there any way that I can have the scroll event fire up even when overflow is hidden?

HTML

<template>
  <div id="test">
    <full-page ref="fullpage" :options="options" id="fullpage">
      <div class="title">Title</div>
      <div class="details">Details</div>
      <form>
        <input type="text" placeholder="Name" name="your-name"/>
      </form>
    </full-page>
  </div>
</template>

JS

function handleScroll(e: any) {
  console.log('scrolled')
}
onMounted(() => {
  const t = = document.getElementById('test')
  t!.addEventListener('scroll', handleScroll)
}

The objective is to have the form to only show up with some animation whenever I scroll in this #test div, while having the rest of the elements fixed. But for now I'm outputting a console log just to check if it works.


Solution

  • This is somewhat complicated to achieve as you request, by using the overflow: hidden the scroll ability is lost and thus not possible as-is.

    To capture the scroll event on an overflow hidden element, you'll have to re-create the scroll event yourself by adding an event listener to the wheel (mouse) instead. Note that browser support may be inconsistent. Also note that this won't account for up/down keyboard key scrolling, or touchmove scrolling (which you would need to add a listener to as well).

    For just the basic mousewheel event, you can use:

    t!.addEventListener('wheel', handleScroll);
    

    This should work, make sure to check for browser support and accessibility. And to add the listener to the touchmove event and up/down keys if needed. You can review the arrow keys codes and proper event listener here: https://www.geeksforgeeks.org/javascript-detecting-the-pressed-arrow-key/