'Smooth scrolling when a link is clicked on mobile
I have created a site and have anchor links at the top of the site. On a computer, when I press a link, it scrolls to the given section in a smooth manor, but on a phone it just jumps straight to the section. I originally used scroll-behavior: smooth, but implemented JavaScript code instead because I thought that may fix the problem; it didn't. Below I have attached my html code and JavaScript code I am currently using:
<nav class="nav">
<h6 id="site">website.net</h6>
<ul class="nav__links">
<li class="nav__item">
<a href="#about" class="link">About</a>
</li>
<li class="nav__item">
<a href="#experience" class="link">Link2</a>
</li>
<li class="nav__item">
<a href="#skills" class="link">Link3</a>
</li>
<li class="nav__item">
<a href="#projects" class="link">Link4</a>
</li>
</ul>
<div class="hidden--btn menu--btn">
<div class="menu-btn__burger"></div>
</div>
</nav>
JavaScript:
const nav = document.querySelector('.nav');
/*scroll animation */
const scrollTo = function (e) {
e.preventDefault();
const target = e.target;
if (target.classList.contains('link')) {
const id = target.getAttribute('href').slice(1);
document.getElementById(id).scrollIntoView({behavior: "smooth"});
}
if (target.classList.contains('hamburger--link')) {
const id = target.getAttribute('href').slice(1);
document.getElementById(id).scrollIntoView({behavior: "smooth"});
hamburgerBin.classList.toggle('hidden--two');
}
}
nav.addEventListener('click', scrollTo);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
