1

I have added the Scroll Back To Top Button in my Base template and it's working perfectly. But when I go to any other pages, the button won't work. Why?!

Here is my Base template:

<!DOCTYPE html>
<html>
  <head></head>

  <body>
    <button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>
    .
    .
    <div class="container">
      #import("content") 
    </div>
    .
    .
  </body>
</html>

And I'm using the JavaScript from the above link:

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

function scrollFunction() {
  if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
    $('#myBtn').fadeIn();
  } else {
    $('#myBtn').fadeOut();
  }
}

function topFunction() {
  document.body.scrollTop = 0; // For Safari
  document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}

The button is only working on the homepage, but not on any other pages even though I see (from View Page Source) <button onclick="topFunction()" id="myBtn" title="Go to top">Top</button> is in the body. Can anyone please help??

AlwaysANovice
  • 983
  • 4
  • 15
  • 34
  • 1
    It seems likely your Javascript is only rendering on the base page, not on all. Can you open a debug console (web inspector, Javascript console, etc) and see if any warnings or errors are reported? – tobygriffin Mar 01 '18 at 01:43
  • ooops! your are absolutely correct...there was a "Cannot read property 'style' of undefined" error that i didn't notice, and after fixing it, the button is working ^_^ :D thanks!! – AlwaysANovice Mar 01 '18 at 17:04

1 Answers1

0

The code above is actually correct and the button is working perfectly on every page now. After tobygriffin pointed out, I noticed that there was a Cannot read property 'style' of undefined error that I didn't before. The button is working on all pages after fixing that error.

Even though it was a silly mistake on my part, I am keeping this Q&A (not deleting it) hoping someone might find it useful :)

AlwaysANovice
  • 983
  • 4
  • 15
  • 34