<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Smooth Scrolling</title>
<style>
.scroll-section {
height: 100vh;
overflow-y: scroll;
position: relative;
}
.scrolling-anchor {
height: 100vh;
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
.scrolling-anchor:not(:first-child)::before {
content: "";
position: absolute;
top: -10vh;
left: 0;
width: 100%;
height: 10vh;
background-color: rgba(255, 0, 0, 0.5);
}
.last {
height: 100vh;
}
</style>
</head>
<body>
<div class="scroll-section">
<section
class="scrolling-anchor"
style="background-color: lightblue"
></section>
<section
class="scrolling-anchor"
style="background-color: lightgreen"
></section>
<section
class="scrolling-anchor"
style="background-color: lightyellow"
></section>
</div>
<div class="last"></div>
<script>
const scrollSection = document.querySelector(".scroll-section");
const anchors = document.querySelectorAll(".scrolling-anchor");
let handlingScroll = false;
function normalizeDelta(delta) {
return Math.sign(delta);
}
function getClosestAnchorDirection() {
const scrollOffset = scrollSection.scrollTop;
const windowHeight = scrollSection.clientHeight;
let nextAnchorDistance = null;
let anchorOffset = null;
let signOfAnchor = null;
anchors.forEach((anchor) => {
anchorOffset = anchor.offsetTop;
let distanceToAnchor = Math.abs(
anchorOffset - scrollOffset
);
if (nextAnchorDistance == null) {
nextAnchorDistance = distanceToAnchor;
signOfAnchor = normalizeDelta(
anchorOffset - scrollOffset
);
} else if (distanceToAnchor < nextAnchorDistance) {
nextAnchorDistance = distanceToAnchor;
signOfAnchor = normalizeDelta(
anchorOffset - scrollOffset
);
}
});
return signOfAnchor;
}
function getAnchorInDirection(delta) {
const scrollOffset = scrollSection.scrollTop;
const windowHeight = scrollSection.clientHeight;
let nextAnchor = null;
let nextAnchorOffset = null;
let anchorOffset = null;
anchors.forEach((anchor) => {
anchorOffset = anchor.offsetTop;
if (
(delta > 0 && anchorOffset > scrollOffset) ||
(delta < 0 && anchorOffset < scrollOffset)
) {
if (
nextAnchor === null ||
Math.abs(anchorOffset - scrollOffset) <
Math.abs(nextAnchorOffset - scrollOffset)
) {
nextAnchor = anchor;
nextAnchorOffset = anchorOffset;
}
}
});
if (nextAnchor === null) {
return false;
}
console.log(delta, nextAnchorOffset);
return nextAnchorOffset;
}
function scrollToAnchor(offset) {
/*
scrollSection.scrollTo({
top: offset,
behavior: "smooth",
});*/
scrollSection.scrollTo(0, offset);
}
function onMouseWheel(event) {
event.preventDefault();
if (!scrolling == true && !handlingScroll == true) {
handlingScroll = true;
const deltaY = normalizeDelta(event.deltaY);
const nextAnchorOffset = getAnchorInDirection(deltaY);
console.log("was mouse anc");
if (nextAnchorOffset !== false) {
scrollSection.scrollTop += deltaY;
} else {
handlingScroll = false;
}
/*
setTimeout(() => {
handlingScroll = false;
}, 500);*/
}
}
scrollSection.addEventListener("wheel", onMouseWheel, {
passive: false,
});
// Handle keydown events
const scrollKeys = [32, 33, 34, 35, 36, 37, 38, 39, 40, 107, 109];
function onKeyDown(event) {
event.preventDefault();
if (!scrolling == true && !handlingScroll == true) {
if (scrollKeys.includes(event.keyCode)) {
handlingScroll = true;
const deltaY =
event.keyCode === 38 ||
event.keyCode === 107 ||
event.keyCode === 36
? -1
: 1;
const nextAnchorOffset = getAnchorInDirection(deltaY);
if (nextAnchorOffset !== false) {
scrollSection.scrollTop += deltaY;
} else {
handlingScroll = false;
}
/*
setTimeout(() => {
handlingScroll = false;
}, 500);*/
}
}
}
scrollSection.addEventListener("keydown", onKeyDown);
scrollSection.tabIndex = 0;
scrollSection.focus();
function onTouchStart(event) {
if (!scrolling == true && !handlingScroll == true) {
if (event.touches.length === 1) {
startY = event.touches[0].pageY;
}
}
}
function onTouchMove(event) {
event.preventDefault();
if (!scrolling == true && !handlingScroll == true) {
if (event.touches.length === 1) {
handlingScroll = true;
const deltaY = startY - event.touches[0].pageY;
const normalizedDelta = normalizeDelta(deltaY);
const nextAnchorOffset =
getAnchorInDirection(normalizedDelta);
if (nextAnchorOffset !== false) {
scrollSection.scrollTop += normalizedDelta;
} else {
handlingScroll = false;
}
/*
setTimeout(() => {
handlingScroll = false;
}, 500);*/
}
}
}
let startY;
scrollSection.addEventListener("touchstart", onTouchStart, {
passive: false,
});
scrollSection.addEventListener("touchmove", onTouchMove, {
passive: false,
});
function onGamepadConnected(event) {
const gamepad = event.gamepad;
gamepadLoop(gamepad);
}
let holdingScrollBar = false;
function gamepadLoop(gamepad) {
if (!scrolling == true && !handlingScroll == true) {
handlingScroll = true;
const axes = gamepad.axes;
const deltaY = axes[1];
if (Math.abs(deltaY) > 0.5) {
const normalizedDelta = normalizeDelta(deltaY);
const nextAnchorOffset =
getAnchorInDirection(normalizedDelta);
if (nextAnchorOffset !== false) {
scrollSection.scrollTop += normalizedDelta;
} else {
handlingScroll = false;
}
/*
setTimeout(() => {
handlingScroll = false;
}, 500);*/
}
requestAnimationFrame(() => gamepadLoop(gamepad));
}
}
function clickedOnScrollBar(mouseX) {
console.log("click", window.outerWidth, mouseX);
if (scrollSection.clientWidth <= mouseX) {
return true;
}
return false;
}
scrollSection.addEventListener("mousedown", (e) => {
console.log(
"down",
clickedOnScrollBar(e.clientX),
" : ",
holdingScrollBar
);
if (clickedOnScrollBar(e.clientX)) {
holdingScrollBar = true;
cancelScroll = true;
console.log("Cancel Scrolling cuz hold scroll bar");
}
});
scrollSection.addEventListener("mouseup", (e) => {
console.log("up", holdingScrollBar);
if (holdingScrollBar) {
scrolling = false;
handlingScroll = false;
oldScroll = scrollSection.scrollTop;
cancelScroll = false;
const normalizedDelta = getClosestAnchorDirection();
scrollSection.scrollTop += normalizedDelta;
holdingScrollBar = false;
}
});
scrollSection.addEventListener(
"gamepadconnected",
onGamepadConnected
);
let lastDirection = 0;
let scrolling = false;
let cancelScroll = false;
let oldScroll = 0;
scrollSection.addEventListener("scroll", (event) => {
event.preventDefault();
if (scrolling) {
const delta = oldScroll >= scrollSection.scrollTop ? -1 : 1;
if (lastDirection !== 0 && lastDirection !== delta) {
cancelScroll = true;
console.log("Cancel Scrolling");
}
return;
} else {
const animF = (now) => {
console.log("FF", oldScroll, scrollSection.scrollTop);
const delta = oldScroll > scrollSection.scrollTop ? -1 : 1;
lastDirection = delta;
const nextAnchorOffset = getAnchorInDirection(delta);
if (nextAnchorOffset !== null) {
const scrollOffset = scrollSection.scrollTop;
const windowHeight = scrollSection.clientHeight;
const distanceToAnchor = Math.abs(
nextAnchorOffset - scrollOffset
);
const scrollLockDistance = 10; // vh
const scrollLockPixels =
(windowHeight * scrollLockDistance) / 100;
if (distanceToAnchor <= scrollLockPixels) {
scrolling = true;
console.log(
scrollOffset,
distanceToAnchor,
scrollLockPixels
);
scrollLastBit(
nextAnchorOffset,
distanceToAnchor,
true,
delta
);
} else {
const freeScrollValue =
distanceToAnchor - scrollLockPixels;
const newScrollOffset =
scrollOffset + delta * freeScrollValue;
scrolling = true;
console.log(
newScrollOffset,
freeScrollValue,
scrollOffset,
distanceToAnchor,
scrollLockPixels
);
scrollCloseToAnchor(
newScrollOffset,
freeScrollValue,
false,
() => {
scrollLastBit(
nextAnchorOffset,
scrollLockPixels,
true,
delta
);
}
);
}
}
};
requestAnimationFrame(animF);
}
});
function scrollLastBit(offset, distance, braking, direction) {
offset = Math.round(offset);
distance = Math.round(distance);
const start = scrollSection.scrollTop;
const startTime = performance.now();
//console.log(offset, distance);
const scrollDuration = braking ? distance * 10 : distance * 2;
let endTick = false;
if (offset == scrollSection.scrollTop) {
//console.log("scrolling = false");
scrolling = false;
handlingScroll = false;
oldScroll = scrollSection.scrollTop;
cancelScroll = false;
console.log(
"doğmadan öldüm ben",
offset,
scrollSection.scrollTop
);
return;
}
let difference = Math.abs(scrollSection.scrollTop - offset);
const tick = (now) => {
if (cancelScroll) {
console.log("animasyon iptal");
lastDirection = 0;
cancelScroll = false;
} else {
console.log("scroll bit anim devam ediyor");
if (
Math.abs(scrollSection.scrollTop - offset) >
difference
) {
// Baba error diğer tarafa tıklayınca, 1 birim uzaklaşma olduğu için animasyonu bitirip diğer tarafa başlıyor.
//scrolling = false;
//handlingScroll = false;
//oldScroll = window.scrollY;
console.log("Baba error, uzaklaştı");
difference = Math.abs(
scrollSection.scrollTop - offset
);
requestAnimationFrame(tick);
} else {
difference = Math.abs(
scrollSection.scrollTop - offset
);
if (endTick) {
//console.log(offset, window.scrollY);
if (direction < 0) {
if (offset >= scrollSection.scrollTop) {
//console.log("scrolling = false");
scrolling = false;
handlingScroll = false;
cancelScroll = false;
oldScroll = scrollSection.scrollTop;
console.log(
"öldüm ben",
offset,
scrollSection.scrollTop
);
} else {
requestAnimationFrame(tick);
}
} else {
if (offset <= scrollSection.scrollTop) {
//console.log("scrolling = false");
scrolling = false;
handlingScroll = false;
oldScroll = scrollSection.scrollTop;
console.log(
"öldüm ben",
offset,
scrollSection.scrollTop
);
} else {
requestAnimationFrame(tick);
}
}
} else {
const elapsed = now - startTime;
const fraction = elapsed / scrollDuration;
//console.log(elapsed, fraction);
if (fraction < 1) {
const easeOut = braking
? -Math.pow(2, -10 * fraction) + 1
: fraction;
scrollToAnchor(
start + (offset - start) * easeOut
);
requestAnimationFrame(tick);
} else {
scrollToAnchor(offset);
endTick = true;
requestAnimationFrame(tick);
}
}
}
}
};
//console.log("requestAnimationFrame");
requestAnimationFrame(tick);
}
function scrollCloseToAnchor(
offset,
distance,
braking,
callback = null
) {
if (offset == scrollSection.scrollTop) {
//console.log("scrolling = false");
scrolling = false;
handlingScroll = false;
oldScroll = scrollSection.scrollTop;
cancelScroll = false;
console.log(
"doğmadan öldüm ben",
offset,
scrollSection.scrollTop
);
return;
}
console.log("scroll to anchor anim başladı");
offset = Math.round(offset);
distance = Math.round(distance);
const start = scrollSection.scrollTop;
const startTime = performance.now();
//console.log(offset, distance);
const scrollDuration = braking ? distance * 10 : distance * 2;
let difference = Math.abs(scrollSection.scrollTop - offset);
const tick = (now) => {
if (cancelScroll) {
console.log("animasyon iptal");
lastDirection = 0;
cancelScroll = false;
} else {
console.log("scroll to anchor anim devam ediyor");
if (
Math.abs(scrollSection.scrollTop - offset) >
difference
) {
//scrolling = false;
//handlingScroll = false;
//oldScroll = window.scrollY;
console.log("Baba error, uzaklaştı");
difference = Math.abs(
scrollSection.scrollTop - offset
);
requestAnimationFrame(tick);
} else {
difference = Math.abs(
scrollSection.scrollTop - offset
);
const elapsed = now - startTime;
const fraction = elapsed / scrollDuration;
//console.log(elapsed, fraction);
if (fraction < 1) {
const easeOut = braking
? -Math.pow(2, -10 * fraction) + 1
: fraction;
scrollToAnchor(
start + (offset - start) * easeOut
);
requestAnimationFrame(tick);
} else {
if (callback !== null) callback();
scrollToAnchor(offset);
}
}
}
};
//console.log("requestAnimationFrame");
requestAnimationFrame(tick);
}
</script>
</body>
</html>
Before providing you with the solution, let me quickly summarize the requirements. You need to adapt the existing scrolling animation system to accommodate scrolling within a section before moving to the next one, and you want to prevent scrolling into the next section while scrolling freely within a section. You also requested only the difference of the modified code to be provided.
Here is the difference of the code (only the modifications) based on your requirements. I have added comments to explain the changes, and you can incorporate these changes into your current code.
+function isMoreContentInSection() {
+ const scrollOffset = scrollSection.scrollTop;
+ const viewBottom = scrollOffset + scrollSection.clientHeight;
+ const currentAnchor = getCurrentAnchor();
+ if (viewBottom < currentAnchor.offsetTop + currentAnchor.clientHeight) {
+ return true;
+ }
+ return false;
+}
+
+function getCurrentAnchor() {
+ const scrollOffset = scrollSection.scrollTop;
+ return Array.from(anchors).find(anchor => {
+ return (
+ anchor.offsetTop <= scrollOffset &&
+ anchor.offsetTop + anchor.clientHeight > scrollOffset
+ );
+ });
+}
+function isOnSectionEdge(d, anchor) {
+ const nextAnchor = getAnchorInDirection(d);
+ if (d > 0) {
+ return (
+ scrollSection.scrollTop + scrollSection.clientHeight >=
+ anchor.offsetTop + anchor.clientHeight
+ );
+ } else {
+ return scrollSection.scrollTop <= anchor.offsetTop;
+ }
+}
- anchors.forEach((anchor) => {
+ // Replace the forEach with a for loop to return early
+ for (let i = 0; i < anchors.length; i++) {
+ const anchor = anchors[i];
+ anchorOffset = anchor.offsetTop;
let distanceToAnchor = Math.abs(
anchorOffset - scrollOffset
);
if (nextAnchorDistance == null) {
nextAnchorDistance = distanceToAnchor;
signOfAnchor = normalizeDelta(
anchorOffset - scrollOffset
);
} else if (distanceToAnchor < nextAnchorDistance) {
nextAnchorDistance = distanceToAnchor;
signOfAnchor = normalizeDelta(
anchorOffset - scrollOffset
);
}
+ if (Math.sign(anchorOffset - scrollOffset) !== direction) break;
+ }
Before calling `getAnchorInDirection`, add a check for `isMoreContentInSection()`:
- const nextAnchorOffset = getAnchorInDirection(deltaY);
+ const sectionHasMoreContent = isMoreContentInSection();
+ const nextAnchorOffset = sectionHasMoreContent
+ ? false
+ : getAnchorInDirection(deltaY);
Similarly for handling the keydown event. Add this check before calling `getAnchorInDirection`:
- const nextAnchorOffset = getAnchorInDirection(deltaY);
+ const sectionHasMoreContent = isMoreContentInSection();
+ const nextAnchorOffset = sectionHasMoreContent
+ ? false
+ : getAnchorInDirection(deltaY);
Now modify the `onTouchMove` event handling:
- const deltaY = startY - event.touches[0].pageY;
+ const deltaY = Math.abs(startY - event.touches[0].pageY);
+ const scrollingUp = startY > event.touches[0].pageY;
+ startY = event.touches[0].pageY;
+ const deltaDirection = scrollingUp ? 1 : -1;
- const nextAnchorOffset = getAnchorInDirection(normalizedDelta);
+ const sectionHasMoreContent = isMoreContentInSection();
+ const nextAnchorOffset = sectionHasMoreContent
+ ? false
+ : getAnchorInDirection(normalizedDelta);
To ensure that you do not scroll into the next anchor section while scrolling within an anchor, only disable scrolling and play the animation if no more content is within the section or if the section is on the edge:
Replace these lines:
if (nextAnchorOffset !== false) {
scrollSection.scrollTop += deltaY;
}
With the following code block:
if (sectionHasMoreContent && !isOnSectionEdge(deltaY, getCurrentAnchor())) {
scrollSection.scrollTop += deltaY * 10;
} else if (nextAnchorOffset !== false) {
scrollSection.scrollTop += deltaY;
}
Make the same changes in the onKeyDown and onTouchMove event handlers.
With these changes, the scrolling within a section will be allowed before moving on to the next section, and it will prevent scrolling into the next anchor section while scrolling freely within an anchor section.