2

I want an event to be triggered after the user scrolls, say 300px after another event happens.

To put simply, an example would be:

I want the user to first press a button and then after pressing the button when he scrolls by some amount, an event is triggered, also if the user didn't press the button then the event does not trigger. The button may be anywhere in the viewport for eg: and the scroll amount should be considered relative to from when the button was pressed not from the start of the page.

Note: this was just an example to explain what I want to do, this is not exactly what I'm trying to do but a general logic would help, thanks.

marsian8
  • 133
  • 6

1 Answers1

1

You don't need IntersectionObserver for this. You can just add a scroll listener on the window which triggers an event after the window's scrollY has exceeded a limit (in this case: 300):

const button = document.querySelector('button')

let scrolled = false
window.addEventListener('scroll', function(){
  if(window.scrollY > 300 && !scrolled) {
    scrolled = true;
    button.click()
  }
})

button.addEventListener('click', () => console.log('button clicked'))
body{
  height: 1000px;
}
<button>This button will be clicked after you scroll 300px</button>

In your specific case, you could use a flag to indicate whether the button has been clicked or not to determine whether to trigger the event after scrolling:

document.querySelector('#a').addEventListener('click', () => track = true)
const button = document.querySelector('#b')

let track = false
let scrolled = false
window.addEventListener('scroll', function(){
  if(track && window.scrollY > 300 && !scrolled) {
    scrolled = true;
    button.click()
  }
})

button.addEventListener('click', () => console.log('button clicked'))
body{
  height: 1000px;
}
<button id="a">Start checking scroll</button>
<button id="b">This button will be clicked after you scroll 300px</button>
Spectric
  • 30,714
  • 6
  • 20
  • 43