I am currently making a website. I am making a vanila javascript smooth scroll. I have triple-checked but everything seems right. Please help me out. Highly Appreciated.
The error states: Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
My code:
function smoothScroll(target, duration){
var target = document.querySelector(target);
var targetPosition = target.getBoundingClientRect().top;
var startPosition = window.pageYOffset;
var distance = targetPosition -startPosition;
var startTime = null;
function animation(currentTime){
if(startTime === null) startTime = currentTime;
var timeElapsed = currentTime - startTime;
var run = ease(timeElapsed,startPosition,distance,duration);
window.scrollTo(0, run);
if(timeElapsed < duration) requestAnimationFrame(animation)
}
function ease(t, b, c, d) {
t /= d/2;
if (t < 1) return c/2*t*t + b;
t--;
return -c/2 * (t*(t-2) - 1) + b;
};
requestAnimationFrame(animation);
}
var section1 = document.querySelector('section1');
section1.addEventListener('click',function(){
smoothScroll('.section2', 1000)
});
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="box1"><a href="" class="section1">I cool</a></div>
<div class="box2"><a class="section2" href="#">I cool</a></div>
<script src="/app.js"></script>
</body>
</html>
CSS:
.box1 {
display: flex;
justify-content: center;
align-items: center;
font-size: 3rem;
height: 100vh;
background-color: crimson;
}
.box2 {
display: flex;
justify-content: center;
align-items: center;
font-size: 3rem;
height: 100vh;
background-color: rgb(223, 255, 41);
}
You may be able to do this with the built in scroll method
Javascript:
element.scrollIntoView();
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
CSS:
html {
scroll-behavior: smooth;
}