Skip to content

Commit

Permalink
Fix: Inview locking and triggering (fixes #588)
Browse files Browse the repository at this point in the history
  • Loading branch information
oliverfoster committed Oct 10, 2024
1 parent c7ab17d commit 5eedeb1
Showing 1 changed file with 23 additions and 35 deletions.
58 changes: 23 additions & 35 deletions libraries/inview.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,25 +51,8 @@
// handler functions
function register(element, data, type) {
const observer = new IntersectionObserver(entries => {
if (isLocked()) {
item.shouldTriggerAfterUnlock = true;
return;
}
const measurement = getMeasurement(item.element);
const uniqueMeasurementId = measurement.uniqueMeasurementId;
const hasMeasureChanged = (
!item.uniqueMeasurementId ||
item.uniqueMeasurementId !== uniqueMeasurementId
);
if (!hasMeasureChanged) return;
item.onscreen = measurement.uniqueMeasurementId;
switch (item.type) {
case TYPE.onscreen:
processOnScreen(item, measurement);
break;
case TYPE.inview:
processInView(item, measurement);
}
if (isLocked()) return;
processItem(item);
}, {
root: null,
threshold: thresholds
Expand Down Expand Up @@ -98,21 +81,25 @@
function process() {
const registeredCount = registered.length;
if (registeredCount === 0) return;
const triggerable = registered.filter(item => item.shouldTriggerAfterUnlock);
triggerable.forEach(item => {
const measurement = getMeasurement(item.element);
const isFirstMeasurementAfterUnlock = (item.onscreen === null);
item.onscreen = measurement.uniqueMeasurementId;
item.shouldTriggerAfterUnlock = false;
if (isFirstMeasurementAfterUnlock) return;
switch (item.type) {
case TYPE.onscreen:
processOnScreen(item, measurement);
break;
case TYPE.inview:
processInView(item, measurement);
}
});
registered.forEach(processItem);
}
function processItem(item) {
const measurement = getMeasurement(item.element);
const uniqueMeasurementId = measurement.uniqueMeasurementId;
const hasMeasureChanged = (
!item.uniqueMeasurementId ||
item.uniqueMeasurementId !== uniqueMeasurementId
);
if (!hasMeasureChanged) return;
item.onscreen = measurement.uniqueMeasurementId;
if (!measurement.onscreen) return;
switch (item.type) {
case TYPE.onscreen:
processOnScreen(item, measurement);
break;
case TYPE.inview:
processInView(item, measurement);
}
}
function processOnScreen(item, measurement) {
$(item.element).trigger('onscreen', measurement);
Expand Down Expand Up @@ -146,6 +133,7 @@
// interface to allow for inview/onscreen to be disabled
function lock(name) {
if (isLocked(name)) return;
if (locks.includes(name)) return;
locks.push(name);
}
function unlock(name) {
Expand All @@ -154,8 +142,8 @@
const lock = locks[i];
if (lock !== name) continue;
locks.splice(i, 1);
break;
}
if (isLocked()) return;
process();
}
function isLocked(name) {
Expand Down

0 comments on commit 5eedeb1

Please sign in to comment.