The onScroll Event

I started to review this when I wanted a "Top of page" button to display on my Parish Council website.

The code for the Parish Council template works but there is probably more that I can do with this technique. For example, having a menu item displaying only after the screen is scrolled.

The W3C example

The JavaScript is:

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

function myScroll() {
  if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
    document.getElementById("myP").className = "test";
  } else {
    document.getElementById("myP").className = "";
  }
}

The Parish Council solution

To get this to work I changed the function from the W3C example to change the navbar class. I also created a function to clear the menu icon.

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

function myScroll2() {
  if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
  var x = document.getElementById("myNavbar");
  if (x.className === "navbar icon" || document.body.scrollTop > 50) {
    x.className = "navbar show";
  }
  }
}
function clear_show() {
  var x = document.getElementById("myNavbar");
    x.className = "navbar icon";
}

The display of the bottom menu is achieved by using the same function as used in fbm.css. In this case the only item in the bottom menu is the "Top of page" item. (in the fbm menu the icon className is either "navbar responsive" or just "navbar")

// the function controlling the Responsive Bottom Menu
function myFunction() {
  var x = document.getElementById("myNavbar");
  if (x.className === "navbar") {
    x.className += " responsive";
  } else {
    x.className = "navbar";
  }
}

There is probably a more elegant method of doing this.

Links

External Sources

The onScroll Event - January 2021