What is the best way to create an onwheel event that produces an up and down effect using JavaScript?

Looking for a way to trigger a function or loop when scrolling up or down using the onwheel event. Check out the code snippet below:

let demo = document.querySelector('#demo');
let c = 0;
window.onwheel = function() {
  c ++;
  demo.innerHTML = c;
}
body{
height: 300vh;
}
h1{
position: fixed;
text-align: center;
width: 100vw;
}
<h1 id="demo" > Hello World </h1>

Currently, the number increments when scrolling up, but I need it to decrement when scrolling down. Looking for a clear JavaScript solution. Thank you.

Answer №1

Implementing the wheel event listener enables you to determine the scroll direction using event.deltaY:

let demo = document.querySelector('#demo');
let c = 0;

window.addEventListener('wheel', function(event) {
  if (event.deltaY < 0) {
    console.log('scrolling up');
    if (c == 0) { // ensure non-negative values
      demo.innerHTML = 0;
    } else {
      c--;
      demo.innerHTML = c;
    }
  } else if (event.deltaY > 0) {
    console.log('scrolling down');
    c++;
    demo.innerHTML = c;
  }
});
body {
  height: 300vh;
}

h1 {
  position: fixed;
  text-align: center;
  width: 100vw;
}
<h1 id="demo"> Hello World </h1>

Answer №2

document.addEventListener('wheel', function(event) {
  if (event.deltaY > 0) {
    // scrolling down
  } else {
    // scrolling up
  }
});

Answer №3

If you want to detect if a user has scrolled down on a webpage, you can store the window.pageYOffset value and compare it to the current scroll position.

let demo = document.querySelector('#demo');
let c = 0;
let last_scroll= window.pageYOffset;
window.onwheel = function() {
  if(window.pageYOffset >= last_scroll && last_scroll != 0){
    c ++;
    demo.innerHTML = c;
  }
  last_scroll = window.pageYOffset;
}
body{
height: 300vh;

}
h1{
position: fixed;
text-align: center;
width: 100vw;
}
<h1 id="demo" > Hello World </h1>

Answer №4

 let dynamicHeight = dynamic.offsetHeight; 
 dynamic.onscroll = function(){}

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

What is the technique for causing this element to move in reverse?

How can I utilize JS to halt the interval and direct the alien to move backwards once it reaches 700px? I am aware that CSS can achieve this, but I prefer a strictly JS approach. I am struggling with stopping the interval as it hits the left position of 70 ...

Code Not Functioning on Website Despite Working in Console

I've developed a jQuery script that eliminates any delivery methods containing the phrase "Royal Mail" if certain products are present in the user's cart. The script functions flawlessly when executed in Google Chrome Console but fails to work wh ...

Sentry: Easily upload source maps from a nested directory structure

I am currently developing a NextJs/ReactJs application using Typescript and I am facing an issue with uploading sourcemaps to Sentry artefacts. Unlike traditional builds, the output folder structure of this app mirrors the NextJs pages structure, creating ...

React: Render function did not return any content. This typically indicates that a return statement is missing

Can anyone help me troubleshoot this error? Error: CountryList(...): No render was found. This typically indicates a missing return statement. Alternatively, to display nothing, return null index.js import React from 'react'; import ReactDOM f ...

Instead of using onload, activate function upon click instead

Upon page load, I have a function that executes: function loadData(page){ showLoading(); $.ajax({ type: "GET", url: "load_data.php", data: "page="+page, success: function(msg) { ...

Transmit the identification to angularjs for the genuine content to be displayed

I have a hidden field where I store an Id, which can also be 2, 3, 4, or 59. I need to send this Id from the hidden field to my opgaver.js file so it can download the content. However, I am facing difficulty in figuring out how to pass the Id to the opgav ...

Encountering the error message "undefined is not a function" while attempting to retrieve JSON data

I'm running into some issues with retrieving data from a PHP file. Upon calling the variable msg[0}, I'm getting an undefined error even though it should have been filled in during the JSON request. The JavaScript code is provided below, and you ...

Is there a way to automatically update a webpage?

When two computers, pc1 and pc2, are on the same page and pc1 changes the status of a field, is there a way to update pc2's aspx page without needing to refresh it? ...

Conditionally displaying an input model in Vue.js using v-if

Just starting to learn vue.js and I'm looking to display table data. My idea is that when the table is in display mode, it should only show the data. However, when I click on the edit button of a table row, I want that specific row to switch to edit m ...

I am unable to showcase the image at this time

Hey there, I'm having an issue with displaying an image stored inside the NextJS API folder. The alt attribute is showing up fine, but the actual image isn't displaying. When I console.log the image data, everything seems to be in place. Can anyo ...

The raycaster is experiencing issues when used with multiple cameras in the Three.js library

I am currently developing an application similar to the threeJs editor. In this project, I have implemented four different cameras, each with unique names and positions. Here is an example of one of the cameras: cameras['home'] = new THREE.Combi ...

How to include a javascript file in a vuejs2 project

Just starting out with the Vue.js framework and I've hit a snag trying to integrate js libraries into my project. Would greatly appreciate any assistance! By the way, I attempted adding the following code to my main.js file but it didn't have th ...

Is it feasible to conceal certain parameters within a URL using Angular UI Router?

Looking to pass two values to a new ui-view via parameters: item id list of objects However, I want the new view to display only the id in the browser URL and not the stringified array of objects: http://www.myapp.com/#/my-view/4 INSTEAD OF http://ww ...

Nuxtjs is functioning properly on 127.0.0.1:5000, but unfortunately it is not working on localhost:5000

Currently, I'm working on a project with Nuxtjs. The application opens successfully when I use the URL 127.0.0.1. However, when I attempt to access it through localhost:5000, I receive the error message Access to localhost was denied. You don't h ...

What are some React component libraries compatible with Next.js 13.1?

I'm exploring Next.js and experimenting with version 13.1 and the new app directory. Is it feasible to accomplish this without sacrificing the advantages of server controls? An error message I encountered states: You're attempting to import a c ...

Issues with Bootstrap 4 (possibly JQuery) - mobile menu navigation items are unresponsive

I've encountered an issue with my Bootstrap4 navbar on mobile screens where the links in the menu don't seem to work. Below is the code I used: <nav class="navbar navbar-expand-sm navbar-dark" style="background-color: #E2BA28"> < ...

Exporting a object in Angular2 Using TypeScript

I've been working on a small Angular2 application using Typescript and things have been going smoothly so far. My goal is to utilize a file called config that contains all the necessary settings for the application. Here's the file in question: ...

Storing user credentials in Firestore after registration - best practices

Hi, I need some assistance with storing user credentials in Firestore after they sign up. Unfortunately, I keep encountering the following error: Invalid collection reference. Collection references must have an odd number of segments, but userDatabase/QMJ ...

Using Bootstrap to handle opening a link when a dropdown menu button is clicked

Utilizing Bootstrap in my main menu was essential for navigating through the numerous pages, subpages, and sub-subpages within my project. The dropdownmenu feature proved to be very helpful in this regard. However, my client now has a specific request - t ...

Synchronize your store by utilizing cookies in the nuxtServerInit function of NuxtJS

I am currently working with NuxtJS's auth module and attempting to retrieve the Bearer token along with a custom cookie that holds a sessionType during nuxtServerInit in order to update the store through a mutation. However, I am facing an issue where ...