Reputation: 2457
I'm trying to increase only the top value of the rootMargin by 50px. The code I'm using for the option is rootMargin: '50px 0px 0px 0px'
. And that isn't working.
Although using rootMargin: '50px 0px'
can work for my case, I have no desire to increase the bottom value.
The full test code is listed below. I did not create a demo on jsFiddle because jsFiddle wraps the result in an iframe, which would be the root
. I cannot set that iframe as the root on jsFiddle so the demo would not work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>rootMargin test</title>
<style>
* {
margin: 0;
padding: 0;
}
#full-height {
margin-bottom: 100px;
height: 100vh;
background-color: lightgreen;
}
#observee {
background-color: lightblue;
}
</style>
</head>
<body>
<div id="full-height"></div>
<p id="observee">I'm being observed.</p>
<script>
var observer = new IntersectionObserver(
function(entries) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
console.log('Intersected.');
}
});
},
{
rootMargin: '50px 0px 0px 0px'
}
);
observer.observe(document.querySelector('#observee'));
</script>
</body>
</html>
Upvotes: 3
Views: 3824
Reputation: 18929
While this is an older question, I think the following may help users with similar issues.
You can run the demo in JSFiddle - just change the root you want to use as the trigger. See the demo below to highlight this.
I think you may be confusing the rootMargin properties. From you question, it sounds like you want the observed element to trigger 50px before it comes into view. If that is the case, then you want to increase the root bottom margin: 0px 0px 50px 0px
if you want to trigger the element only when it reaches 50px inside the root, then use: 0px 0px -50px 0px
. You can leave off the last value like: 0px 0px 50px
which would be top left/right bottom
See the demo below:
Upvotes: 6