I was experimenting with pure JavaScript and came across the following curiosity:
When I pass the reference values to the top of the page for variables, the code does not work, it breaks.
How it works:
window.onscroll = function(){
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
backToTop.style.display = "block";
} else {
backToTop.style.display = "none";
}
};
This does not work:
var distanciaTopoBody = document.body.scrollTop;
var distanciaTopoHtml = document.documentElement.scrollTop;
window.onscroll = function(){
if (distanciaTopoBody > 20 || distanciaTopoHtml > 20) {
backToTop.style.display = "block";
} else {
backToTop.style.display = "none";
}
};
Notice that the code does not change much, it's a noticeably small change, but the result is completely different.
I just assign document.body.scrollTop
to a variable ( distanceTopoBody ) and document.documentElement.scrollTop
to the other ( distanceTopoHtml );