I have searched multiple questions on SO to avoid duplication, but none of the solutions worked for me.
My goal is to toggle the visibility of a button based on scroll position. I tried creating a scroll event listener to trigger a function that checks the scroll position and performs necessary actions accordingly. However, the listener did not fire as expected.
Despite referring to various documentation sources and ensuring my code is correct, I still cannot figure out what's missing here. Any insights?
Here is the relevant document: scroll event
const showHideArrow = () => {
//console.log("func triggered");
const arrow = document.getElementById("scroll-arrow");
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
arrow.style.display = "none";
} else {
arrow.style.display = "block";
}
}
window.addEventListener("scroll", showHideArrow);
section{
max-height: 100vh;
height: 100vh;
width: 90vw;
margin: 0 auto;
display: flex;
flex-direction: column;
}
.scroll-arrow {
margin: auto auto 5rem auto;
text-align: center;
padding-bottom: 5px;
}
<head>
<title>Test</title>
</head>
<body>
<main>
<section class="intro">
<a id="scroll-arrow" class="scroll-arrow" target="_self" href="#about">
<svg width="34" height="34" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M11.0001 3.67157L13.0001 3.67157L13.0001 16.4999L16.2426 13.2574L17.6568 14.6716L12 20.3284L6.34314 14.6716L7.75735 13.2574L11.0001 16.5001L11.0001 3.67157Z"
fill="currentColor" />
</svg>
</a>
</section>
<section id="about" class="about">
<h2>test</h2>
</section>
</main>
</body>
</html>