Reputation: 23
I'm new to web development and came across a lot of tutorials on jQuery but there wasn't a lot on pure JS. I'm trying to convert this piece of code I found online which scrolls the page up when user clicks a button in the bottom right into pure JavaScript but I'm having some trouble.
function main() {
$('.back-to-top').hide();
$(window).scroll(function(){
if($(window).scrollTop()>400){
$('.back-to-top').fadeIn('fast');
}else{
$('.back-to-top').fadeOut('fast');
}
})
$('.back-to-top').click(function(){
$('body').animate({
scrollTop: 0
}, 1000)
return false;
})
}
This is what I have so far but it doesn't work:
var scrollUp = document.getElementsByClassName('back-to-top');
window.onscroll = function(){
if(window.pageYOffset >= 400){
scrollUp.style.display = 'block';
}else{
scrollUp.style.display = 'none';
}
}
scrollUp.onclick = function(){
window.scrollTo(0,0);
}
HTML
<a class="back-to-top" id="back-to-top" href="#">
<i class="fa fa-arrow-up" aria-hidden="true"></i>
<h2 class="text">Scroll Up</h2>
</a>
This is for web development assignment, can I have some advice?
Upvotes: 0
Views: 1025
Reputation: 96
The problem is that document.getElementsByClassName('back-to-top') returns an array-like object. Check documentation here: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
Solution:
var scrollUp = document.getElementsByClassName('back-to-top')[0];
window.onscroll = function(){
if(window.pageYOffset >= 400){
scrollUp.style.display = 'block';
}else{
scrollUp.style.display = 'none';
}
}
scrollUp.onclick = function(){
window.scrollTo(0,0);
}
See working example here: https://jsfiddle.net/9m7doq1m/
To avoid this issue, you can use the id selector (getElementById) instead of the class selector.
Upvotes: 1
Reputation: 1990
var scrollUp = document.getElementsByClassName('back-to-top');
scrollUp.onclick = function(){
window.scrollTo(0,0);
}
#content {
height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content" style="height:1000px">
</div>
<a class="back-to-top" id="back-to-top" href="#">
<i class="fa fa-arrow-up" aria-hidden="true"></i>
<h2 class="text">Scroll Up</h2>
</a>
Upvotes: 0