0

I have a simple "Back to top" button coded in JS. When I scroll down 150px it shows on the bottom-right part of the page and when I click on this button it takes me back to the top of the page.

This works correctly on Google Chrome, but on Mozilla Firefox it does not.

I have a similar problem with another script that generates a random number from a user input.

first script on codepen:

(function(){

  function createButton() {

    var button = document.createElement("button");


    button.classList.add("backToTop", "hiddenBack");
    button.textContent = "back";
    document.body.appendChild(button);

    return button;
  }
  var button = createButton();

  function animatedScroll(){
    if(window.pageYOffset > 0){
      window.scrollBy(0, -5);
      setTimeout(animatedScroll, 10);
    }

  };

  button.addEventListener("click", function(e) {
      e.stopPropagation();
      animatedScroll();

   },false);

  window.addEventListener("scroll", function(e){

    if( window.pageYOffset >= 150){
      button.classList.remove("hiddenBack");
    }else {
      button.classList.add("hiddenBack");
    }

  },false);


})();

second script on codepen:

var btn = document.querySelector("#getNumbers"),
    output = document.querySelector("#showNumbers");

function getRandom(min, max) {
  return Math.round(Math.random() * (max - min) + min);
}

function showRandomNumber(){

  var numbers = [];
  var random,
  from = document.querySelector("#from").value,
  to = document.querySelector("#to").value,
  how = document.querySelector("#how").value;

  for(var i = 0; i < how; i++){

    random = getRandom(from,to);

    while(numbers.indexOf(random) !== -1){
      random = getRandom(from,to);
    }

  numbers.push(random)
  }

  output.value = numbers.join(", ");

}

btn.onclick = showRandomNumber;
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
  • Post your code here, not just at a remote site. You can use [Stack Snippets](https://stackoverflow.blog/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) to make it executable. – Barmar Apr 24 '17 at 20:56
  • I corrected some grammatical and spelling errors as well as included hyperlinks and code from the codepen links provided. – jon3laze Apr 26 '17 at 05:26

1 Answers1

1

Use the window.pageYOffset instead of document.body.scrollTop:

if(window.pageYOffset >= 150)

More detail on the issue here : document.body.scrollTop Firefox returns 0 : ONLY JS

Jonathan Dion
  • 1,651
  • 11
  • 16