I have to scrollIntoView
a particular element smoothly and then do something.
Example
JavaScript
x
4
1
element.scrollIntoView({behavior: 'smooth'}).then(() => {
2
// Do something here
3
})
4
I know that it can’t be done this way as native scrollIntoView
doesn’t return a Promise. But, how do I achieve something like this?
I’m using Angular 7 BTW. So if there are any directives that could help me achieve this, it would be great.
Advertisement
Answer
You can work with prototypes, I think this could be a solution to your problem without download any npm packages
JavaScript
1
36
36
1
/* Extends Element Objects with a function named scrollIntoViewPromise
2
* options: the normal scrollIntoView options without any changes
3
*/
4
5
Element.prototype.scrollIntoViewPromise = function(options){
6
7
// "this" refers to the current element (el.scrollIntoViewPromise(options): this = el)
8
this.scrollIntoView(options);
9
10
// I create a variable that can be read inside the returned object ({ then: f() }) to expose the current element
11
let parent = this;
12
13
// I return an object with just a property inside called then
14
// then contains a function which accept a function as parameter that will be execute when the scroll ends
15
return {
16
then: function(x){
17
// Check out https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API for more informations
18
const intersectionObserver = new IntersectionObserver((entries) => {
19
let [entry] = entries;
20
21
// When the scroll ends (when our element is inside the screen)
22
if (entry.isIntersecting) {
23
24
// Execute the function into then parameter and stop observing the html element
25
setTimeout(() => {x(); intersectionObserver.unobserve(parent)}, 100)
26
}
27
});
28
29
// I start to observe the element where I scrolled
30
intersectionObserver.observe(parent);
31
}
32
};
33
}
34
35
36
element.scrollIntoViewPromise({behavior: "smooth"}).then(()=>console.log("EHI!"));
I’ve created an example. I know it’s not an angular application, but it’s a good starting point. You just need to implement it (If you’re using typescript you have to create an interface which extends Element with the new function).