I am unable to apply a horizontal scrolling function (using the mousewheel) to both of the containers in my code below. I would like this function to be applied to any container I make in the future 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 element = document.querySelector("#container");
element.addEventListener('wheel', (event) => {
event.preventDefault();
element.scrollBy({
left: event.deltaY < 0 ? -30 : 30,
});
});
</script>
</body>
I attempted to make a flexible horizontal scrolling function that uses the mousewheel. I can only apply this function to the first container in my code. The second container and any following them does not have this functionality applied to them.
There can't be more than 1 element with the same id, so change container to classes. Then since you are selecting multiple elements, you need to use querySelectorAll. So you will have an array of containers and now u can iterate it with forEach.
const element = document.querySelectorAll(".container");
elements.forEach(el = > {
el.addEventListener('wheel', (event) => {
event.preventDefault(); }
el.scrollBy({
left: event.deltaY < 0 ? -30 : 30,
});
})