Variable scope in JavaScript - Value of the DOM attribute is not passed by assignment

0

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 );

JS Fiddle for anyone who wants to test

    
asked by anonymous 02.02.2018 / 05:07

1 answer

0

window.onscroll performs a function every time scroll is rolled.

So for it to work, the variables must be inside the function!

var backToTop = document.getElementById("back-to-top");
window.onscroll = function(){
  var distanciaTopoBody = document.body.scrollTop;
  var distanciaTopoHtml = document.documentElement.scrollTop;
  if (distanciaTopoBody > 20 || distanciaTopoHtml > 20) {
    backToTop.style.display = "block";
  } else {
    backToTop.style.display = "none";
  }
};
#back-to-top {
  text-decoration: none;
  font-size: 24pt;
  font-weight: bold;
  padding: 15px 20px 7px 20px;
  background-color: blue;
  color: white;
  position: fixed;
  bottom: 10px;
  right: 10px;
  border-radius: 15px;
  opacity: .7;
  transition: opacity .7s ease-out;
  display: none;
}
<!-- Back to top button using pure JavaScript -->
<a href="#" id="back-to-top">^</a>
<div style="height: 900px;"></div>

The same goes for scroll .

var backToTop = document.getElementById("back-to-top");
window.addEventListener('scroll', function(e) {
  var distanciaTopoBody = document.body.scrollTop;
  var distanciaTopoHtml = document.documentElement.scrollTop;
  if (distanciaTopoBody > 20 || distanciaTopoHtml > 20) {
    backToTop.style.display = "block";
  } else {
    backToTop.style.display = "none";
  }
});
#back-to-top {
  text-decoration: none;
  font-size: 24pt;
  font-weight: bold;
  padding: 15px 20px 7px 20px;
  background-color: blue;
  color: white;
  position: fixed;
  bottom: 10px;
  right: 10px;
  border-radius: 15px;
  opacity: .7;
  transition: opacity .7s ease-out;
  display: none;
}
<!-- Back to top button using pure JavaScript -->
<a href="#" id="back-to-top">^</a>
<div style="height: 900px;"></div>

Reference

02.02.2018 / 05:26