I ve the following working in codepen but not localy
https://codepen.io/LoudDesignStudios/pen/RwxPJKY
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="assets/css/css1.css">
</head>
<body>
<section id="about-us" class="">
s1
</section>
<section id="why-choose-us" class="">
s2
</section>
<section id="funfacts" class="">
s3
</section>
<section id="services" class="">
s4
</section>
<section id="studio" class="">
s5
</section>
<section id="contactus" class="">
s6
</section>
<section id="footer-widgets" class="">
s7
</section>
<footer id="footer" class="footer">
footer
</footer>
<button onclick="topFunction()" id="scrollUp"><i class="las la-chevron-up" aria-hidden="true"></i></button>
<script>
var mybutton = document.getElementById("scrollUp");
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 60 || document.documentElement.scrollTop > 60) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
function topFunction() {
document.body.scrollTop = 0;
document.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
</script>
</body>
</html>
Same codes working in other websites made a while ago and still working just starting from scratch now the window.scroll is not firing.
Thanks.
It's because you're trying to get an element (mybutton) by its ID before the document's contents are fully loaded.
You will need to wrap your code inside a DOMContentLoaded event handler. Below is slightly modified version of your JavaScript code:
document.addEventListener("DOMContentLoaded", function () {
var mybutton = document.getElementById("scrollUp");
window.onscroll = function () { scrollFunction() };
function scrollFunction() {
if (document.body.scrollTop > 60 || document.documentElement.scrollTop > 60) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
});
function topFunction() {
document.body.scrollTop = 0;
document.scrollTop = 0;
document.documentElement.scrollTop = 0;
}