Intersection Observer with viewport margins in Alpine

Viewed 38

Problem:

Need to execute an action when an element enters the middle third area of the viewport:

enter image description here

Constraints:

I am using Alpine JS.

According to the Alpine intersect docs, I can control the rootMargin property of the underlying IntersectionObserver using .margin, in order to change the limit where the observer will trigger. I'm doing it as follows:

h1 {
margin-top: 95vh;
position: relative;
background-color: blue;
color: white;
z-index: 2;
}

body {
height: 200vh;
}

body::before,
body::after {
content: '';
position: fixed;
left: 0;
right: 0;
height: 33%;
background-color: grey;
z-index: 1;
}

body::before{
top: 0;
}

body::after{
bottom: 0;
}
<html>
<head>
<!-- Alpine Plugins -->
<script defer src="https://unpkg.com/@alpinejs/intersect@3.x.x/dist/cdn.min.js"></script>
 
<!-- Alpine Core -->
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
</head>
<body>
    <h1 x-data="{ message: 'Alpine Is Working' }"
    x-intersect:enter.margin.-33%.0.-33%.0="message = 'ENTERED'"
    x-intersect:leave.margin.-33%.0.-33%.0="message = 'LEFT'"
    x-text="message"></h1>
</body>
</html>

In the above example, you can see it's not respecting the 33% top/bottom margin with the viewport. I marked those in grey using pseudoelements.

What should happen:

In the example above, it should say "Entered" or "Left" when the element scrolls into and out of the white area.

Any idea on what I may be doing wrong?

Thanks!

0 Answers
Related