1

I try to simplify my code with a const but it isn't working

// my const 'myscroll' is not working ?? Why ??

const myscroll = document.querySelector('.scrollup');

// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function () {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 800 || document.documentElement.scrollTop > 800) {
    myscroll.style.display = "block";
  } else {
    myscroll.style.display = "none";
  }
};

I have to do it that way

window.onscroll = function () {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 800 || document.documentElement.scrollTop > 800) {
    document.querySelector('.scrollup').style.display = "block";
  } else {
    document.querySelector('.scrollup').style.display = "none";
  }
};

It must be so simple but I'm blind ! Thanks for your helps

Lo1176
  • 21
  • 5
  • 3
    Put the `const myscroll = …;` inside the `scrollFunction` so that it doesn't run before the document is loaded - like your original did. – Bergi Jul 30 '20 at 15:02
  • Can you elaborate on what you mean by "not working"? What are you trying to do? – zcoop98 Jul 30 '20 at 15:02
  • please check whether **myscroll** has some values in it i think it would be null. and if it is null your js is loading before the html content is rendered. – Ashish Mishra Jul 30 '20 at 15:17

1 Answers1

1

const myscroll = document.querySelector('.scrollup');

window.onscroll = scrollFunction;

function scrollFunction(e) {
    const state = document.documentElement.scrollTop > 200;
    myscroll.style.display = state ? 'block' : 'none';
};
body {
    height: 500vh;
}

.scrollup {
    width: 50px;
    height: 50px;
    position: fixed;
    bottom: 10px;
    right: 10px;
    background-color: red;
    border-radius: 50%;
    display: none;
}
<div class="scrollup"></div>
MoloF
  • 231
  • 1
  • 5
  • Thanks @MoloF The style is a way much better. But I still have the same issue. I have to do this to make it works in localhost : ` const state = document.documentElement.scrollTop > 400; document.querySelector('.scrollup').style.display = state ? 'block' : 'none'; ` – Lo1176 Jul 30 '20 at 16:55
  • @Lo1176, I understand correctly, you have a problem on the `local machine`? Perhaps you write the `JS` code first and then the `html`? Try adding `JS` to the very bottom inside the `BODY` tag – MoloF Jul 30 '20 at 17:07