When div appears on screen, i need to run a function
but since i am new to javascript i couldn't succeed.
how can i do it using intersection observer
<div id='demo'/>
my function
function myFunc() {
var headID = document.getElementById("demo");
var newScript = document.createElement('script');
newScript.src = '/myscript.js';
headID.appendChild(newScript);
}
In the observer's callback, check for each observed entry if they are interesecting. If they are, then call myFunc() and unobserve the element to only call myFunc once.
function myFunc() {
const script = document.createElement('script');
script.src = '/myscript.js';
demo.append(script);
console.log('Script appended');
}
/**
* This is called whenever an observed element is
* in view or went out of view.
*/
const onIntersection = (entries, observer) => {
for (const { isIntersecting, target } of entries) {
if (isIntersecting) {
myFunc();
observer.unobserve(target);
}
}
};
/**
* The options for the observer.
* 50px 0px on the rootMargin says that the observer triggers
* after 50px in the top and bottom.
*/
const options = {
root: null,
rootMargin: '50px 0px',
threshold: [0]
};
/**
* Select the demo element, create an observer and start observing the demo element.
*/
const demo = document.getElementById('demo');
const observer = new IntersectionObserver(onIntersection, options);
observer.observe(demo);
#demo {
display: block;
height: 100px;
width: 100px;
background: red;
margin-top: 1000px;
}
<div id="demo"></div>