Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recognize scroll as an action and observe relative movement #1

Draft
wants to merge 3 commits into
base: trunk
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion build/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 28 additions & 2 deletions demo/css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ body {

.container {
position: relative;
padding: 100vh 0; /* Add padding to allow scrolling */
padding: 100vh 0 200vh 0; /* Add padding to allow scrolling */
}

.scrollers .container {
padding-top: 20vh;
}

.horizontal-line {
Expand Down Expand Up @@ -36,8 +40,13 @@ body {
position: relative;
}

.double-box {
height: 200px;
}

.demo-box::before,
.demo-box::after {
content: attr(class);
content: attr(style);
position: absolute;
bottom: -20px;
left: 0;
Expand All @@ -50,9 +59,26 @@ body {
background-color: rgba(255, 255, 255, 0.8);
padding: 2px;
border-radius: 3px;
width: fit-content;
}

.demo-box::after {
content: attr(class);
top: -20px;
bottom: initial;
}

.observe-triggered {
transform: scale(1.1);
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}

.animated-left {
transform: translateX( calc( var( --distance-from-trigger ) * -1px ) );
transition: transform 50ms linear;
}

.animated-right {
transform: translateX( calc( var( --distance-from-trigger ) * 1px ) );
transition: transform 50ms linear;
}
46 changes: 46 additions & 0 deletions demo/scrollers.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Observe Triggers Demo</title>
<link rel="stylesheet" href="../demo/css/style.css">
<link rel="stylesheet" href="../demo/css/animations.css">
<link rel="stylesheet" href="../demo/css/colors.css">
<style>
:root {
--distance-from-trigger: 0;
}
</style>
</head>
<body class="scrollers">
<div class="container">
<div class="horizontal-line" style="top: 10vh" data-percentage="10%"></div>
<div class="horizontal-line" style="top: 20vh" data-percentage="20%"></div>
<div class="horizontal-line" style="top: 30vh" data-percentage="30%"></div>
<div class="horizontal-line" style="top: 40vh" data-percentage="40%"></div>
<div class="horizontal-line" style="top: 50vh" data-percentage="50%"></div>
<div class="horizontal-line" style="top: 60vh" data-percentage="60%"></div>
<div class="horizontal-line" style="top: 70vh" data-percentage="70%"></div>
<div class="horizontal-line" style="top: 80vh" data-percentage="80%"></div>
<div class="horizontal-line" style="top: 90vh" data-percentage="90%"></div>

<div class="demo-box double-box observe-trigger-10-top-scroll observe-scroll animated-left" style="background-color: #ff5733;"></div>
<div style="height: 30vh;"></div> <!-- Spacer -->
<div class="demo-box observe-trigger-30-top-scroll observe-scroll animated-right" style="background-color: #33ff57;"></div>
<div style="height: 10vh;"></div> <!-- Spacer -->

</div>

<script type="module">
import ObserveTriggers from '../src/index.js';

new ObserveTriggers();

window.addEventListener('observerTriggered', (event) => {
const { element, isIntersecting, config } = event.detail;
console.log(`Element intersected at ${config.rootMargin}% of viewport ${config.edge}. Action: ${config.action}, Custom class: ${config.class}`);
});
</script>
</body>
</html>
89 changes: 87 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ class ObserveTriggers {
};
this.observers = new Map();
this.elementStates = new WeakMap();
this.scrollers = new Map();
this.scrollersActive = false;
this.handleScrollers = this.handleScrollers.bind(this);
this.viewportHeight = false;
this.init();
}

Expand All @@ -32,7 +36,7 @@ class ObserveTriggers {
* - baseTriggerClass: The base class name that triggers the observer.
* - rootMargin: The root margin for the observer.
* - edge: (Optional, default top) The edge to observe: top, bottom, left, right.
* - action: (Optional, default toggle) The action to perform: toggle, add, remove, replace.
* - action: (Optional, default toggle) The action to perform: toggle, add, remove, replace, scroll.
* - class: (Optional, default observe-triggered) The class to add, toggle, or remove.
* - root: (Optional, default null) The root element to observe.
*
Expand Down Expand Up @@ -76,7 +80,9 @@ class ObserveTriggers {

// Parse for a specified action, if it exists.
if (
['toggle', 'add', 'remove', 'replace'].includes(parts[currentPart])
['toggle', 'add', 'remove', 'replace', 'scroll'].includes(
parts[currentPart]
)
) {
config.action = parts[currentPart];
currentPart++;
Expand Down Expand Up @@ -162,6 +168,40 @@ class ObserveTriggers {
this.observers.get(element).set(className, observer, false);
}

/**
* Handle scrollers.
*
* @param {Event} scrollEvent The scroll event.
*/
handleScrollers(scrollEvent) {
if (!this.scrollers) {
return;
}

this.scrollers.forEach(({ classes, config }, element) => {
if (false === this.viewportHeight) {
this.viewportHeight = window.innerHeight;
}

// If `observe-scroll` is present, calculate the distance from the top of the viewport to the top of the scroller.
if (classes.includes('observe-scroll')) {
// Calculate the distance from the top of the viewport to the top of the scroller.
let hasScrolledAmount =
this.viewportHeight * (config.rootMargin / 100) -
element.getBoundingClientRect().top;

if (hasScrolledAmount < 0) {
hasScrolledAmount = 0;
}

element.style.setProperty(
'--distance-from-trigger',
hasScrolledAmount
);
}
});
}

/**
* Handle an observed intersection.
*
Expand Down Expand Up @@ -213,6 +253,51 @@ class ObserveTriggers {
}
});
element.classList.add(config.class);
break;
case 'scroll':
if (
entry.isIntersecting &&
!this.scrollers.has(element) &&
isTriggered
) {
const scrollerClasses = [];

// Capture any class names that start with `observe-scroll`.
element.classList.forEach((className) => {
if (className.startsWith('observe-scroll')) {
scrollerClasses.push(className);
}
});

// Add this scroller to the scrollers map.
this.scrollers.set(element, {
classes: scrollerClasses,
config,
});
} else if (
!entry.isIntersecting &&
this.scrollers.has(element)
) {
this.scrollers.delete(element);
}

// If there are intersecting scrollers, setup a scroll event listener.
if (this.scrollers.size > 0 && !this.scrollersActive) {
window.addEventListener(
'scroll',
this.handleScrollers,
{ passive: true }
);
this.scrollersActive = true;
} else if (this.scrollers.size === 0) {
window.removeEventListener(
'scroll',
this.handleScrollers,
{ passive: true }
);
this.scrollersActive = false;
}

break;
case 'toggle':
default:
Expand Down