-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathscrollingOperations.js
More file actions
56 lines (50 loc) · 1.85 KB
/
scrollingOperations.js
File metadata and controls
56 lines (50 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import './scrollingOperation.module.scss';
export const smoothScrollTo = (targetElement) => {
// offset to avoid the sticky header on top to block the "Create a Queue at the click of a button" text
const offset = 45;
// setting the exact position on the document to scroll to
const bodyRect = document.body.getBoundingClientRect().top;
const elementRect = targetElement.getBoundingClientRect().top;
const elementPosition = elementRect - bodyRect;
const offsetPosition = elementPosition - offset;
// scroll to the exact position
// console.log ('checking scrollTo', offsetPosition);
/* window.scrollTo ({
top: offsetPosition,
left: '40px',
behavior: 'smooth',
}); */
// $ ('html, body').animate ({scrollTop: $ (hash).offset ().top - 100}, 800);
window.scrollTo('40px', offsetPosition);
};
export const smoothScrollToHomePageTop = (history) => {
const element = document.getElementById('target_top');
if (element) {
smoothScrollTo(element);
} else {
history.push('/');
}
};
/**
* Execute a callback as soon as an element is available on the DOM.
* The function will stop checking after 5 seconds to prevent memory leaks.
*
* @param {string} id - element id to wait on
* @param {Function} callback - callback to execute as soon as the element becomes available.
* The element is passed to the callback when it is triggered.
* */
export const onLoadById = (id, callback) => {
const maxAttempts = 50; // 50 attempts * 100ms = 5 seconds
let attempts = 0;
const checkAndExecute = setInterval(() => {
const element = document.getElementById(id);
attempts += 1;
if (element) {
callback(element);
clearInterval(checkAndExecute);
} else if (attempts >= maxAttempts) {
// Element not found after timeout, clear interval to prevent memory leak
clearInterval(checkAndExecute);
}
}, 100);
};