Trigger event when user scroll to specific element - with jQuery

后端 未结 12 1512
攒了一身酷
攒了一身酷 2020-11-22 11:52

I have an h1 that is far down a page..

TRIGGER EVENT WHEN SCROLLED TO.

and I want to trigger an alert

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 12:47

    Intersection Observer can be the best thing IMO, without any external library it does a really good job.

    const options = {
                root: null,
                threshold: 0.25, // 0 - 1 this work as a trigger. 
                rootMargin: '150px'
            };
    
            const target = document.querySelector('h1#scroll-to');
            const observer = new IntersectionObserver(
               entries => { // each entry checks if the element is the view or not and if yes trigger the function accordingly
                entries.forEach(() => {
                    alert('you have scrolled to the h1!')
                });
            }, options);
            observer.observe(target);
    

提交回复
热议问题