Utilizing Mouseover Event to Create a Loop Function in Pure Javascript

My goal is to design a carousel with images and have it horizontally scroll when the user hovers over the left or right side of the div. I've created two "invisible" divs for the controls on the left and right, each equipped with eventListeners:

right.addEventListener("mouseover", goRight)

function goRight() {
    document.getElementById('images').scrollLeft += 20;
}

left.addEventListener("mouseover", goLeft)

function goLeft() {

    document.getElementById('images').scrollLeft -= 20;
}

Currently, when I hover over the controls, the scrolling happens just once. To achieve continuous scrolling until mouseout, how can I make goRight()/goLeft() loop while hovering over the controls?

Answer №1

To address this issue, you can utilize the setInterval() function and ensure it is terminated on mouseout. By saving the interval id and executing clearInterval() when mouseout event occurs:

const delayTime = 100;
let timerId;

function moveLeft() {
  timerId = setInterval(
    () => (document.getElementById('images').scrollLeft -= 20),
    delayTime,
  );
}

function moveRight() {
  timerId = setInterval(
    () => (document.getElementById('images').scrollLeft += 20),
    delayTime,
  );  
}

function stopMovement() {
  clearInterval(timerId);
}

left.addEventListener('mouseover', moveLeft);
left.addEventListener('mouseout', stopMovement);
right.addEventListener('mouseover', moveRight);
right.addEventListener('mouseout', stopMovement);

Answer №2

If you want to detect when a user hovers over an element, you can create a Boolean variable that turns 'true' when the mouse is on top of it.

// for the right side:
let hoveringOverRight = false;

right.addEventListener("mouseenter", function(){
    hoveringOverRight = true;
});
right.addEventListener("mouseleave", function(){
    hoveringOverRight = false;
});

You can then use a set interval function to control the speed at which this check occurs.

window.setInterval(function(){
  if (hoveringOverRight)
  /// Add scroll logic here
}, 300);

Remember to repeat the same process for the left side as well.

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 are the steps to take in order to successfully deploy an Express server on GitHub Pages?

I heard that it's possible to host an Express server on GitHub Pages, but I'm not sure how to do it. Is the process similar to deploying a regular repository on GitHub Pages? ...

Issues with premature execution of Angular JS code have been observed at times

Currently facing an issue with my code where the updateProduct() function call is happening before the forEach loop begins running on about 1 out of every 10 page loads. Not sure why this is occurring or how to solve it. Any insights on what might be causi ...

Failure to fetch data through Axios Post method with a Parameter Object

I've encountered an issue with Axios while attempting to make a post request with a parameters object to a Laravel route. If I use query parameters like ?username=user, the post request works successfully. However, when I use an object, it fails: Be ...

The functionality of Ajax appears to be malfunctioning when attempting to validate

Hey there, I'm having trouble with my Ajax code. I need it to verify my login information and return either 'success' or 'fail'. Unfortunately, my Ajax script seems to be throwing an error. var user = $('.username').valu ...

Customize the font color in Material UI to make it uniquely yours

How can I customize the default Text Color in my Material UI Theme? Using primary, secondary, and error settings are effective const styles = { a: 'red', b: 'green', ... }; createMuiTheme({ palette: { primary: { ...

The supertest request body cannot be found

Testing my express server POST endpoint using supertest has been a challenge for me. Although everything works perfectly in postman, I encountered an issue when trying to pass body parameters into the test. It seems like the body parameters are not being p ...

Add a button that allows users to input their information into an array, and then display the data from the array in a <div>

I'm new to the coding world, so please bear with me if I miss any unspoken rules. I welcome any feedback. Essentially, I have three text input fields: Name:, Age:, and Password:. If any of these fields are left empty, an error message will display. H ...

What is the process of transferring an object to a different scope by utilizing checkboxes and Ajax?

I find myself lost in contemplation. I have a checkbox that I want to utilize to move a corresponding object to another area on my page. Furthermore, I am interested in transferring only one specific field of this checked object. In the past, I utilized Aj ...

Center-align the text by disregarding the absolutely positioned element

I have created a custom flex table with filtering and sorting capabilities. The filter and sort icons are located in the right corner of the table header. Additionally, users can choose to align the header text left or center. The Issue: When positioning ...

Discovering the position of digits within a string using Javascript

Could someone help me find the positions of the numbers (1994 and 27) within this string? I attempted to split the string but I'm unsure about how to proceed from there. let str = 'year of birth: 1994, and i'm 27 yo' ...

guide to setting up router access using token

I've received a token from the backend axios.post(process.env.VUE_APP_LOGIN, payload) .then(response => { const {access_token, token_type, user} = response.data; this.token = access_token this.$store.commit(&a ...

Displaying SVGs in the <object> tag within an Angular 2 component is not functioning properly in Internet Explorer

When embedding an SVG within an <object> tag, it is not displayed in IE 11 and Edge. Instead, they only show the innerHTML as "SVG no supported," giving the impression that the tag is not supported at all. Interestingly enough, both browsers do d ...

What's causing the "Uncaught SyntaxError: Unexpected token u" error to consistently pop up in Chrome?

I've been trying to figure this out all day by searching online, but I'm still stuck. My code is quite long and runs fine in Firefox, but Chrome throws an error: "Uncaught SyntaxError: Unexpected token u". Could someone please point out where I ...

Parameter for Ajax URL

As a beginner in the world of Ajax, I'm on a mission to grasp the inner workings of this technology. I came across a tutorial on w3schools that sparked my curiosity. In the code snippet below, the 'url' is defined as demo_ajax_load.txt. Wil ...

Having trouble with Jquery toggle functionality on Firefox browser

Can anyone help me troubleshoot this jQuery script that doesn't seem to be functioning properly in Firefox? $(document).ready(function () { $('#all_lists').hide(); $('#add_lists').click( function(){ event.stopPropagation ...

Problems arise when making a second call back to the ajax web method

I have an ajax method that helps me find the selected row from a table and display the information in a series of fields. The issue I am facing is that the first time the call is made, it works fine. However, when I search for another record, the data is n ...

Load Bootstrap tab activation

I'm having trouble getting the active class to work on my tabs. I've tried using body onload click trigger, showing tabs by ID, and many other methods, but nothing seems to be working. I have implemented hashed URLs to allow for individual tab li ...

ReactJs: How useEffect is invoked before onClick function in NextJS

I am facing an issue with a button in my Next project. Here is the code for the button: <Button minWidth={'140px'} onClick={() => exec(scope)} >Save</Button> When this button is clicked, it triggers the following function: c ...

Tips on revealing TypeScript modules in a NodeJS environment

Currently, I am working on developing a TypeScript library. My goal is to make this library compatible with both TypeScript and JavaScript Node projects. What would be the most effective approach for achieving this? Should I create two separate versions ...

JQuery may be successfully loaded, but it is not functioning as intended

Just started dabbling in JQuery (I'm a newbie) but I'm having trouble getting it to work! Initially, it worked a couple of times but then suddenly stopped working (pretty strange). I made some changes and now it doesn't work at all. JQuery a ...