Struggling to incorporate smooth scroll on Safari using Vanilla js. Despite following the documentation to a tee, the implementation is still not functioning as expected.
Outlined below is the vanilla.js code:
(function() {
scrollTo();
})();
function scrollTo() {
const links = document.querySelectorAll('.scroll');
links.forEach(each => (each.onclick = scrollAnchors));
}
function scrollAnchors(e, respond = null) {
const distanceToTop = el => Math.floor(el.getBoundingClientRect().top);
e.preventDefault();
var targetID = (respond) ? respond.getAttribute('href') : this.getAttribute('href');
const targetAnchor = document.querySelector(targetID);
if (!targetAnchor) return;
const originalTop = distanceToTop(targetAnchor);
window.scrollBy({ top: originalTop, left: 0, behavior: 'smooth' });
const checkIfDone = setInterval(function() {
const atBottom = window.innerHeight + window.pageYOffset >= document.body.offsetHeight - 2;
if (distanceToTop(targetAnchor) === 0 || atBottom) {
targetAnchor.tabIndex = '-1';
targetAnchor.focus();
window.history.pushState('', '', targetID);
clearInterval(checkIfDone);
}
}, 100);
}
Highlighted section from layout.html:
<head>
<script src="static/vanilla.js"></script>
<li class="nav-item">
<a data-scroll class="scroll nav-link" href="#bazinga">¿Como funciona?</a>
</li>
</head>
Snippet from index.html:
<section id="bazinga" align="left" class="features" id="features">
<div class="container">
<div class="section-heading text-center">
<h2>Funciones ilimitadas, información ilimitada</h2>
<p class="text-muted">Descubre la magia que hay detrás de una simple pulsera tyveck</p>
<hr width="15%">
</section>
Despite efforts, the scroll behavior remains abrupt on Safari. Any assistance would be greatly appreciated.
Edit: Please note that this template is solely for testing purposes and is not functional as is.
<!DOCTYPE html>
<html>
<head>
<script src="/static/vanilla.js"></script>
</head>
<body>
<a class="scroll" href="#bazinga">¿Como funciona?</a>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<p>My first paragraph.</p>
<p>My first paragraph.</p>
<p>My first paragraph.</p>
<p>My first paragraph.</p>
<p>My first paragraph.</p>
<p>My first paragraph.</p>
<p>My first paragraph.</p>
<p>My first paragraph.</p>
<p>My first paragraph.</p>
<p>My first paragraph.</p>
<p>My first paragraph.</p>
<p>My first paragraph.</p>
<p>My first paragraph.</p>
<p>My first paragraph.</p>
<div id=bazinga class="container">
<p>Bazinga</p>
</div>
</body>
</html>