What is the best way to manage horizontal scrolling using buttons?

I was hoping that when the button is clicked, the scroll would move in the direction of the click while holding down the button. Initially, it worked flawlessly, but suddenly it stopped functioning.

export default function initCarousel() {
  const carousel = document.querySelector("[data-carousel='scroll']");
  const rightBtn = document.querySelector("[data-carousel='right']");
  const leftBtn = document.querySelector("[data-carousel='left']");

  let timer;
  leftBtn.addEventListener("mousedown", () => {
    timer = setInterval(() => {
      carousel.scrollLeft -= 50;
    }, 20);
  });

  rightBtn.addEventListener("mousedown", () => {
    timer = setInterval(() => {
      carousel.scrollLeft += 50;
    }, 20);
  });

  leftBtn.addEventListener("mouseup", () => {
    if (timer) clearInterval(timer);
  });

  rightBtn.addEventListener("mouseup", () => {
    if (timer) clearInterval(timer);
  });
}

Answer №1

It appears that your code is designed to handle horizontal scrolling using buttons when mouse down events occur. Despite the correctness of your code, it may have ceased functioning due to various factors. Here are some suggestions for troubleshooting and consideration:

document.addEventListener("DOMContentLoaded", function() {
  initializeScrollingFunctionality();
});

function initializeScrollingFunctionality() {
  const scrollableElement = document.querySelector("[data-scroll='horizontal']");
  const rightButton = document.querySelector("[data-action='scroll-right']");
  const leftButton = document.querySelector("[data-action='scroll-left']");

  let intervalId;

  leftButton.addEventListener("mousedown", () => {
    intervalId = setInterval(() => {
      scrollableElement.scrollLeft -= 50;
    }, 20);
  });

  rightButton.addEventListener("mousedown", () => {
    intervalId = setInterval(() => {
      scrollableElement.scrollLeft += 50;
    }, 20);
  });

  document.addEventListener("mouseup", () => {
    if (intervalId) clearInterval(intervalId);
  });
}

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

Create a search bar using HTML and CSS that utilizes the GET method

My current challenge involves creating a search functionality using HTML based on the username entered, such as 'user'. Upon clicking the search bar, the page should redirect to http://localhost/searchuser/user I am encountering difficulties wi ...

The FormControlLabel radio button within the RadioGroup is experiencing difficulty in becoming selected

Utilizing a RadioGroup component to showcase a dynamic list of Radio options using FormControlLabel. The dynamic radio choices are appearing correctly on the screen and I can obtain the selected radio option through onChange in RadioGroup. However, after s ...

Duplicate a Google Sheet and save it to a specific folder in Google Drive

I currently have two spreadsheets in my possession. The first spreadsheet consists of raw data that includes unique employee numbers and the names of the employees. The second spreadsheet is the one I aim to duplicate to a designated Google Drive folder. M ...

The close menu button is not functioning properly when clicked outside the menu - the buttonevent.matches is not recognized as a

I am encountering an issue with the dropdown menu that is not closing when clicking outside of the menu button. Despite having faced this problem before, I can't seem to find a solution now. Any help would be greatly appreciated as I am uncertain why ...

Utilizing Javascript's Mapping Functionality on Arrays

Here is an array that I need help with: var gdpData = {"CA": 1,"US": 2,"BF": 3,"DE": 4}; I am trying to retrieve the value associated with BF using a loop Can anyone provide guidance on how to accomplish this using either JQuery or Javascript? ...

Create PDFs using PhantomJS when the HTML content is fully loaded and ready

I am a newcomer to utilizing phantomjs and encountering difficulties in rendering my website as a PDF file. Although I can successfully render a simple version of the page, issues arise when multiple images and web fonts are involved, causing the DOM not t ...

Creating a two-column post loop in Wordpress is a great way to display content in a

I've been attempting to separate posts for a long time without success. No matter what variations I try, the result is always either a single post or duplicating all of them. In other words, multiple posts are not displaying as intended. If anyone ha ...

Retrieving information from an object using JavaScript

Hello, I am facing a challenge with extracting data from an object via a web API in ReactJS. It seems like the data returned by the API is not structured properly as a JavaScript object. To view the issue directly in your browser visit: I need assistance ...

Modify the color of the field that is currently chosen

Is there a way to modify the highlight color of the active record in an extjs combobox? In the image provided below, the record Petty Cash Fund is currently selected in my dropdown, but the highlighting is not very visible. How can I adjust this for all co ...

JavaScript Evaluation Test Outcome

(Apologies, I am still in the process of learning JavaScript) My goal is to create a checklist quiz that provides different outcomes based on the number of checkboxes selected by the user. There are a total of 7 checkboxes, and if the user selects 1 or few ...

What is the process for defining an outcome when a draggable element is placed into a droppable area using Jquery?

Currently, I am working on a task where I need to increase the value of a counter (var counter = 0;) every time a draggable image is dropped into a dropzone, which is also an image rather than a div. $( "#goldbag" ).draggable({ revert: "invalid", containm ...

The simplest method to make HTML elements inaccessible to the Simple HTML Dom Parser in PHP

Imagine a scenario where a basic web application is running and utilizing Simple HTML Dom Parser. The code snippet below demonstrates this: <?php include('simple_html_dom.php'); $html = file_get_html('http://someurl.com'); ...

Sort products by the subcategory in Firebase

I am currently facing a challenge in filtering products based on their sub child nodes within Firebase. This is how my data is structured: products/ product1 /author: 12345 /title: "Awesome" /description: "more awesome" ...

Within a <div> element, there is a <span> element with a border and a specific line height. The

Can anyone explain why the border of the span is positioned next to the top? When I remove the display property for the span, it seems to work fine. Thank you. div { height: 80px; border: 1px solid green; line-height: 80px } .inner-span { heigh ...

Challenge Encountered with Create-React-App TypeScript Template: Generating JS Files Instead of TSX Files

Encountering a problem setting up a new React application with TypeScript using the Create-React-App template. Followed the guidelines on the official documentation (https://create-react-app.dev/docs/adding-typescript/) and ran the command below: npx creat ...

What is the best way to display and conceal various elements with each individual click?

Utilizing the onClick function for each triggering element, I have implemented a show/hide feature for multiple element IDs upon click. The default setting is to hide the show/hide elements using CSS display property, except for the initial 3 main elements ...

Creating dual permission menus for two different roles in Vue JS 3

This is my router file checking which role is logged in: router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresAdmin)) { if(VueJwtDecode.decode(localStorage.getItem('accessToken')).sub == &quo ...

Using Jquery and css to toggle and display active menu when clicked

I am trying to create a jQuery dropdown menu similar to the Facebook notification menu. However, I am encountering an issue with the JavaScript code. Here is my JSFiddle example. The problem arises when I click on the menu; it opens with an icon, similar ...

The AutoComplete component in React Material UI does not automatically assign the initialValue

I've encountered an issue with my form.js component. In this component, I have two states: update and create. Within the component, there's an AutoComplete component that works perfectly fine in the create state (data creation works as intended). ...

What is the process for using the scrollIntoView function on an svg element like a rectangle?

I have a graph panel with an SVG. The nodes in the SVG are listed in a separate panel. I would like for when a node is clicked in the node list, the SVG will scroll to that specific node. Each node is represented by a rectangle shape. However, I noticed th ...