Reputation: 129
Im doing a small proyect with litelement, but I want to fire an event when a webcomponent is shown, not only the first time, but every time that the component shows, how can I do that?
thanks in advance
Upvotes: 0
Views: 439
Reputation: 21030
Intersection Observer API will help you find if the element is on the screen. For more information, visit MDN docs.
// 1. Observer options
let options = {
// The scroll area - mostly body or document
root: document.querySelector('#parent'),
rootMargin: '0px',
threshold: 1.0
};
let callback = () => { /* Do something */ };
// Observe Element
let observer = new IntersectionObserver(callback, options);
// Start observing
const targetElm = document.querySelector('#target');
observer.observe(targetElm);
The API is supported on all browsers except IE but a polyfill is already available: https://github.com/w3c/IntersectionObserver
Upvotes: 0