show and hide element functions

This commit is contained in:
ReznoRMichael 2021-02-16 19:13:41 +01:00
parent 578824f00a
commit 39673d1c12
2 changed files with 21 additions and 11 deletions

View file

@ -30,7 +30,7 @@
</head> </head>
<body> <body>
<button class="scroll-up-button">^</button> <button class="scroll-up-button hidden">^</button>
<div id="background"></div> <div id="background"></div>

View file

@ -1,29 +1,39 @@
/* the document element root (<html>) */
const ROOT = document.documentElement;
function ScrollTo() { function ScrollTo() {
} }
function ShowElement() { function ShowElement(element) {
element.classList.toggle("hidden");
element.classList.add("visible");
} }
function HideElement() { function HideElement(element) {
element.classList.toggle("visible");
element.classList.add("hidden");
} }
function DetectPageScroll() { function TogglePageScrollElement(root, element, ratio) {
/* Maximum number of pixels that can be scrolled by the user */ /* Maximum number of pixels that can be scrolled by the user */
let scrollTotal = ROOT.scrollHeight - ROOT.clientHeight; let scrollTotal = root.scrollHeight - root.clientHeight;
let scrollUpButton = document.querySelector(".scroll-up-button");
if ((ROOT.scrollTop / scrollTotal) > 0.80) { if ((root.scrollTop / scrollTotal) > ratio) {
/* Show button */ /* Show button */
ShowElement(element);
} else { } else {
/* Hide button */ /* Hide button */
HideElement(element);
} }
} }
document.addEventListener("scroll", DetectPageScroll); document.addEventListener("scroll", () => {
TogglePageScrollElement(
/* the document element root (<html>) */
document.documentElement,
/* Which element to toggle visibility */
document.querySelector(".scroll-up-button"),
/* How far the user has to scroll to show the element */
0.50);
});