Reputation: 25409
I have intersection observer object it works, but I want it to notify my once some element is 100pixels over or at bottom of intersection point.
With default config it just changes value of .isIntersection once the element is exactly in view. But I want to do some stuff when elements are 100pixels above or below the viewport.
This is my code:
var iObserver = new IntersectionObserver(function(element) {
console.log('elementi', element); // I want to trigger here when elementi is 100px or less of distance to the viewport.
});
var el;
for (var i = 0; i < elements.length; i++) {
el = elements[i];
console.log('eli', el);
iObserver.observe(el);
}
Thanks to user for answer I used this and it worked:
var iObserver = new IntersectionObserver(function(entryEvent) {
//...
}, {'rootMargin': '100px 0px 100px 0px'});
Upvotes: 1
Views: 1920
Reputation: 192467
You can define the rootMargin
top and bottom in the options you pass to the observer.
In the demo, hover the red rectangle, when it reaches a distance of 10px
from the .container
the observer is called:
const options = {
root: document.querySelector('.container'),
rootMargin: '10px 0px 10px 0px',
};
let i = 0;
const iObserver = new IntersectionObserver((entries) => console.log(`intersection ${i++}`), options);
iObserver.observe(document.querySelector('.element'));
.container {
position: relative;
height: 20px;
background: lightblue;
}
.element {
position: absolute;
top: calc(100% + 30px);
height: 100px;
width: 100px;
background: red;
margin-bottom: 20px;
transition: top 5s;
}
.element:hover {
top: calc(100% - 30px);
}
.as-console-wrapper {
height: 50px;
}
<div class="container">
<div class="element">1</div>
</div>
Upvotes: 1