Difficulty with Horizontal Mousewheel Scrolling

Struggling to implement a horizontal scrolling feature (via mousewheel) for both containers in the code below. I want this feature to be easily applied to any future container creations as well.

<body>
    
<style>
 #container {
  display: flex;
  overflow-x: scroll;
  
  max-width: 100rem;
  margin: 0 auto;
}

#container p {
  font-family: sans-serif;
  
  border-radius: 8px;
  background: #ff6961;
  color: black;
  
  padding: 2rem 3rem;
  margin: 2rem 1rem;
}

</style>
    
      <h1> Hello World! </h1>
      
      <br>

 <h2>Container Title</h2>
  <div id="container">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p> 
<p>7</p>
<p>8</p> 
<p>9</p>
<p>10</p>
<p>11</p> 
<p>12</p>
<p>13</p> 
  </div>
  <h2>Container 2 Title</h2>
  <div id="container">
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>4</p>
    <p>5</p>
    <p>6</p> 
    <p>7</p>
    <p>8</p> 
    <p>9</p>
    <p>10</p>
    <p>11</p> 
    <p>12</p>
    <p>13</p> 
      </div>


  </html>
  <script>
    const elements = document.querySelectorAll(".container");
    
    elements.forEach((element) => {
      element.addEventListener('wheel', (event) => {
        event.preventDefault();
        
        element.scrollBy({
          left: event.deltaY < 0 ? -30 : 30,
          
        });
      });
    });
    
        </script>
</body>

Created a dynamic horizontal scrolling method utilizing the mousewheel. Unfortunately, it only works on the first container and not on subsequent containers. Looking to make this functionality universally applicable to all containers moving forward.

Answer №1

It's important to avoid having multiple elements with the same id, so consider using classes instead of containers. To select and work with multiple elements, use querySelectorAll. This will give you an array of containers that can be iterated through using forEach.

 const elements = document.querySelectorAll(".container");
      elements.forEach(element => {
        element.addEventListener('wheel', (event) => {
          event.preventDefault(); }
        element.scrollBy({
          left: event.deltaY < 0 ? -30 : 30,
          
        });
      })

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

Having trouble creating an angularjs table using ng-repeat in the controller?

I have a sample snippet that I would like to discuss. My goal is to display a JSON object in an angular table using ng-repeat, which is being generated from my angular controller script. I have attempted the code below, but for some reason, the table is no ...

Tips for abbreviating HTML content using PHP

Similar Question: PHP: Truncate HTML, ignoring tags I have some HTML content stored in a database. I need to display this content in a shortened form. I attempted to use the mb_strstr function like so; $str = mb_strstr($this->htmlData, "</p> ...

What could be causing the d3.js pie chart transition to malfunction?

Today I am experimenting with d3.js to create a unique pie chart from scratch. While following tutorials here as my base, there were modifications made in the code to add personal touches and customization. The challenge arose during Step 6 when introduc ...

Exploring the principles of object-oriented design within the context of Node

I am facing challenges with the asynchronous flow of Node.js. Let's assume we have the following class: function myClass() { var property = 'something'; var hasConnected = false; this.connect = function(params) { // Logic to conn ...

Repeatedly triggering the Jquery Dialog Event

When I open a calendar plugin in jquery dialog, I encounter a recurring issue. Every time I close and reopen the dialog, my calendar event onDayClick triggers multiple times – twice, thrice, and so on. <div id="show_calendar"> <div class="c ...

My router-outlet is malfunctioning when trying to display my component

I am currently diving into learning Angular 2 in order to revamp my personal website. However, I've encountered an issue where my application fails to load the component when I navigate to the appropriate route by clicking on the navigation bar. Insi ...

prevent unauthorized changes to input using browser developer tools in Angular

We have a login page for our application with three fields: "user name," "password," and a "login" button. Here's the issue I'm facing: I enter a valid user name. Then, I open the Browser Developer Tools and input the following code: d ...

Leveraging the power of Javascript and Firebase within the Angular framework

When attempting to integrate Firebase with Angular, I encountered an issue where my localhost was not able to function properly with my JavaScript code. The strange thing is that everything works fine when the code is placed directly in the index.html file ...

Methods for removing cookie during logout with Express and Passport JS?

I have been struggling to delete cookies upon logout but haven't had any luck so far. I searched online and came across two methods: Setting a new expiration date for the cookie res.cookie('connect.sid', '', {expires: new Date(1 ...

If the value of the "Global Region" field in the PDF form is not empty, then execute the following JavaScript code:

I need to restrict access to a PDF form when the "Global Region" field is filled out. Testing this code can be time-consuming, so I want to confirm that the syntax to check for a NOT NULL value in the Global Region Field is correct. if(this.getField("Gl ...

When working with AngularJS, you can enhance your application by implementing a global AJAX error handler if one has

Is there a way to set a global AJAX handler that will only be called if an error handler is not already defined for a specific AJAX call? Some of my AJAX calls need to execute certain logic if an error occurs (such as re-enabling a button), while others s ...

The menu does not adjust to fit the site properly, causing the video/photos to appear off to the right on smaller screens

Earlier, I received some fantastic help for which I am extremely grateful. However, I find myself in need of your expert assistance once again. The website I am currently working on is . After simplifying the code and removing absolute positioning, I enco ...

Experience the magic of CSS Sprite once it's been successfully uploaded!

Visit the website for testing here Located at the bottom of the page are two images with hover effects - one labeled "Contact us" and the other "Jobs Available!" During local testing, these images are visible. However, once uploaded to a server, they dis ...

AngularJS - Create Alert Pop-Up for Missing Input Fields

I've been struggling to set up my app so that it displays an alert when the user attempts to submit a form with an empty input box. Despite having a confirmation popup working in another part of the application, I can't seem to figure out why thi ...

Creating a React Native project without the use of TypeScript

Recently I dived into the world of React Native and decided to start a project using React Native CLI. However, I was surprised to find out that it uses TypeScript by default. Is there a way for me to create a project using React Native CLI without TypeS ...

Upon sending a POST request to http://localhost:5000/getData, a 404 error (Not Found) was encountered while using axios

As a newcomer to react and node.js, I have set up a fake server running on port 5000 with an API (http://localhost:5000/getData) that contains a hardcoded array of objects. My goal is to add a new object to this API from my react frontend running on port 3 ...

The issue with style.background not functioning in Internet Explorer is causing complications

I am currently developing a JavaScript game that involves flipping cards. However, I have encountered an issue with the style.background property. It seems to be functioning correctly in Chrome but not in Internet Explorer. Here is the problematic code sn ...

Create a JavaScript function that adds cells to a table, each containing an input field and a corresponding

I successfully developed a function that appends a table with rows and cells, then fills those cells with data from an array. However, I am now faced with the challenge of modifying it so that the generated cells contain an input field where the value= att ...

Obtain the key by using the JSON value

I am seeking to identify the recursive keys within a JSON Object. For instance, consider the following JSON Object: { "Division1" : { "checked": true, "level": 1, "District1-1": { "checked": true, "level ...

Is the jquery autocomeplete plugin malfunctioning when using numbers in the input?

I encountered a requirement to display stock number suggestions within a search box. To achieve this, I decided to implement the Jquery autocomplete plugin. Through an ajax call to a function in my cfc, I was able to retrieve all the stock numbers and stor ...