What is the best way to merge multiple window.onscroll events together?

One feature is a colorful RGB scroller positioned next to the standard scrollbar, indicating the progress of page scroll. The second feature is a classic "scroll to top" button.

FIRST FEATURE

HTML

<button onclick="topFunction()" id="myBtn" title="SCROLL ME UP!">▲▲▲</button> 

JavaScript

let mybutton = document.getElementById("myBtn");

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

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


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

SECOND FEATURE

HTML

<div id="progressbar"></div>
<div id="scrollpath"></div>

JavaScript

    let progress = document.getElementById('progressbar');
    let totalHeight = document.body.scrollHeight - window.innerHeight;
    window.onscroll = function () {
    let progressHeight = (window.pageYOffset / totalHeight) * 100;
    progress.style.height = progressHeight + "%";
        }

CSS


::-webkit-scrollbar
{
    width: 0;
}
#scrollPath
{
    position: fixed;
    top: 0;
    right: 0;
    width: 10px;
    height: 100%;
    background: rgba(255,255,255,0.05);
}
#progressbar
{
    position: fixed;
    top: 0;
    right: 0;
    width: 10px;

    background: linear-gradient(to top, #008aff,#00ffe7);
    animation: animate 5s linear infinite;
}
@keyframes animate
{
    0%,100%
    {
        filter: hue-rotate(0deg);
    }
    50%
    {
        filter: hue-rotate(360deg);
    }
}
#progressbar:before
{
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(to top, #008aff,#00ffe7);
    filter: blur(10px);
}
#progressbar:before
{
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(to top, #008aff,#00ffe7);
    filter: blur(30px);
}
::placeholder {
    color: white;
}

Both features work fine independently, but seem to interfere with each other when used simultaneously. Any insights on how to resolve this issue?

I expect both features to work seamlessly together.

Answer №1

Having multiple onscroll events can cause the last one to overwrite the first. To avoid this, you can use

window.addEventListener('scroll', function() { ... })
to append scroll events instead of replacing them.

Alternatively, you can attach the events to each other like so:

let mybutton = document.getElementById("myBtn");

window.addEventListener('scroll',  function() {
  scrollFunction();
  let progressHeight = (window.pageYOffset / totalHeight) * 100;
  progress.style.height = progressHeight + "%";
};

function scrollFunction() {
  mybutton.style.display = (document.body.scrollTop > 38 || document.documentElement.scrollTop > 512) ? "block" : "none";
}

Instead of using mybutton.style.display, consider adding a class to hide the element such as .d-none { display: none; }. Then you can add the class conditionally:

mybutton.classList.toggle('d-none', (document.body.scrollTop > 38 || document.documentElement.scrollTop > 512))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

During the installation of a package, npm encountered a require stack error with the code MODULE_NOT_FOUND

Whenever I attempt to install something using the npm install command, it throws an error saying "require stack" and "code MODULE_NOT_FOUND" C:\Users\dell>npm audit fix node:internal/modules/cjs/loader:1075 const err = new Error(message); ...

Ensure that the dropdown menu remains visible even after the mouse no longer hovers over it

Looking to create a main menu with dropdown items that appear when the user hovers over them? You may have noticed that typically, the dropdown disappears once the hover event is lost. But what if you want the menu to stay visible and only disappear upon c ...

I am experiencing challenges with utilizing moment and angular filters

I was able to get this code working perfectly before the recent jsfiddle update. However, now it seems to be causing issues. Any assistance would be greatly appreciated. Let's start with the HTML code: <div ng-app="app" ng-controller="ctrl"> ...

Manipulate inherited CSS styles from an external source

Currently, I am working on creating a pagination using the NG-Bootstrap pagination component. However, I encountered an issue where I need to modify or specifically remove some CSS properties that are applied by default in the NG-Bootstrap library. Is ther ...

Editing in real time, yet no instance to be found

I have developed my own custom non-jQuery ajax solution for building web applications. Recently, I encountered compatibility issues with IE9 while using TinyMCE, so I am considering switching to CKeditor. The editable content is contained within a div str ...

Implementing AJAX to transfer dynamically created variables using the POST method

In an HTML page, there is a table with rows and a checkbox inside each row. When a checkbox is selected, a message can only be deleted by clicking a red button called the "button-of-death." Example table    tr(unique_id)   & ...

What would be the ideal labels for the parameters within Array.reduce?

When it comes to enhancing code readability, what naming convention should be employed when naming callback arguments in Array.reduce for optimal best practices? const studentAges= [15,16,14,15,14,20] Generalized Approach const sum = studentAges.reduce ...

SVG with complete coverage of width and height

Here's the challenge: create a full window svg image with aspect distortion without using an SVG tag. Why avoid the SVG tag? Because I plan to replace the SVG later on (possibly frequently) and haven't found a simple way to do so. Previous attem ...

"Is an Ionic Top Navigation Bar the best choice for your

Creating an Ionic Top Navigation Bar Greetings! I am facing some challenges while trying to implement a Top Navigation Bar in my Ionic Project. Despite the lack of documentation on this specific topic, I am struggling to make it work properly. Your as ...

Getting data from a xhttp.send() request in a Node.js Express server

On my front page, I have this code snippet: var x = "Hi"; var y = 123; xhttp.open("POST", "/toNodeServer", true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send(x, y); Meanwhile, on the server ...

Modify the height of an element in real-time using jQuery

I'm looking to dynamically adjust the height of a div based on another element, but only if that element does not have the class collapsed (which is used in a Bootstrap toggle collapse feature). The initial setup seems to work fine, however, when I i ...

Create a sleek design by aligning labels with CSS 3 fancy radio buttons

I have a radio button with a larger circle that needs to be 38px input[type=radio] { visibility: hidden; } .label { font-weight: normal; color: #333; } .label::before { content: ''; position: absolute; left: 0; w ...

Having difficulty animating camera rotation in ThreeJS with Tween

I am facing an issue with animating the ThreeJS camera rotation using TweenJS. While I can successfully tween the camera position, the camera.rotation does not seem to update as expected. To illustrate my problem, I have created a simple example based on ...

"An error occurred with the Google chart due to 'null' not being recognized as an object, specifically in relation to the select menu and onchange event

Currently, I have implemented the following Script: <header> <script type="text/javascript" src="http://www.google.com/jsapi"></script> </header> <body> <script type="text/javascript"> google.load("visualization", "1 ...

Guide to establishing a connection with a Node.js socket server

I'm delving into the world of node JS and experimenting with creating a real-time application that involves a node JS server using socket.io, along with a unity application that can communicate with it. Below is the code I used to set up the server w ...

Guide: Implementing Vuex store within a plugin

I recently developed a custom Vue plugin which includes a customized instance method import Echo from 'laravel-echo'; import Vue from 'vue'; import config from '@/config'; const echor = { install(Vue){ Vue.prototy ...

React Component that closes when it loses focus

In my React project, I am working on creating a custom select2 style component. Most of the functionality is complete, but I am struggling with figuring out how to hide the result box when the user clicks away. Here is the render method: render() { l ...

Is there a way to determine in FireBug the specific JavaScript code being received from the server following an Ajax request?

Within my HTML code, I am transmitting a dollar amount to the server in order to convert its currency within the application. Is there a way for me to use FireBug to track and view the JavaScript that is being received from the server following this Ajax ...

What could be causing my CSS relative positioning to malfunction?

I am struggling to adjust the positioning of my divs using relative and absolute properties. Any advice on how to resolve this issue would be greatly appreciated. Thank you. Example Code: <div id="game"><img src="gta-game.jpg" height="100" width ...

When setting the margin to auto, it perfectly centers elements on servers and IE, but on Chrome off the server, it appears to be aligned to the

There seems to be an issue with the display of my page in Chrome - it starts at the middle and ends on the right side. However, when I view it on my server or try it on Internet Explorer 11, it appears centered. Why is that? This problem only arose after ...