Transform the hover effect of a div using a jQuery interval

Seeking guidance as a jQuery beginner. I am looking to create 5 classes (.button1 - .button5) with a timer that alternates the hover or active state of the next class every 4000ms in a continuous loop. Additionally, I would like the timer to pause and resume if the user hovers over another one of the classes. Any suggestions on where to start or any threads with a similar solution would be appreciated. Diagram attached.

CSS

.wrapper { width:100%; margin:0 auto; background:#f3f3f3; }
#buttonblock { display:block; }
.button1, .button2, .button3, .button4, .button5 { display:inline-block; margin:0 5px; height:50px; width:50px; border-radius:25px; background:#3cc8dd; }
.button1:hover, .button2:hover, .button3:hover, .button4:hover, .button5:hover{ background:#fbc040; }

HTML

<div class="wrapper">
<div id="buttonblock">
    <div class="button1"></div>
    <div class="button2"></div>
    <div class="button3"></div>
    <div class="button4"></div>
    <div class="button5"></div>
</div>
</div>

Answer №1

To iterate through the array of objects, you can utilize a simple loop like this:

var $buttons = $('#buttonblock div');

for (var x=0; x<$buttons.length; x++)
{
    var element = $buttons[x]; // convert dom element to jQuery object using $(element)
    // perform desired actions here, such as setting intervals.
    if(x == $buttons.elngth)
        x=0; // reset the loop
}

Answer №2

HTML

<div class="container">
<div id="buttonsection">
    <div class="btn btn1"></div>
    <div class="btn btn2"></div>
    <div class="btn btn3"></div>
    <div class="btn btn4"></div>
    <div class="btn btn5"></div>
</div>

CSS

.highlight {
 background:#fbc040;
}

JavaScript

var counter = 1;
var timer;
$(document).ready(function () {
 startTimer();
 $('.btn').mouseenter(function () {
    $('.highlight').removeClass('highlight');
    clearInterval(timer);
 });

 $('.btn').mouseleave(function () {
    startTimer();
 });
});

function startTimer() {
 timer = setInterval(function () {
  counter = (counter > 5) ? 1 : counter;
  $('.highlight').removeClass('highlight');
  $('.btn' + counter).addClass('highlight');
  counter++;
 }, 4000);
}

Link to JSFiddle

Answer №3

Give this a shot

const buttons = $('#buttonblock').children('button'),
    totalButtons = buttons.length,
    currentIndex = 0,
    timeInterval = 3000;

function startTimer() {
    buttons.removeClass('active');
    buttons.eq(currentIndex).addClass('active');
    currentIndex++;
    if (currentIndex === totalButtons) {
        currentIndex = 0;
    }
}

startTimer();
const timer = setInterval(startTimer, timeInterval);

buttons.mouseenter(function () {
    clearInterval(timer);
    buttons.removeClass('active');
    const currentButton = $(this);
    currentButton.addClass('active');
    currentIndex = buttons.index(currentButton);
}).mouseleave(function () {
    timer = setInterval(startTimer, timeInterval);
});

Check out the demo using setInterval

Alternatively, explore the setTimeout method here

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

Is there a way to set the menu to automatically open when the page loads?

Looking for some help with a slide out menu that I want to be always open and cannot be closed. I tried changing the open=true setting to open=false but it didn't work as expected. Here's the code snippet below. I aim to remove the open and close ...

Choose images at random from an array within a React Native application

I've been working on a feature that involves randomly selecting an image from an array of images. However, I keep running into the issue of getting an "invalid props source supplied to image" error. My goal is to display a different random image each ...

How can you prioritize one CSS file over another?

To avoid repetition, I wish to have all the classes, tags, and ids from css.css take precedence over bootstrap.min.css, without duplicating any from bootstrap.min.css. <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/css.css ...

Utilize a CompareValidator to evaluate conditions only when necessary

I am dealing with a checkbox containing a javascript function that triggers onclick to toggle the visibility of a div. Within this div, there is a textbox with a CompareValidator that validates the input as a Double. The issue arises when the checkbox is ...

jQuery Chosen not triggering the onchange event after updating the value using JavaScript

JSFiddle In the JSFiddle link provided, I have created a select element with 3 options (including one blank option). When manually switching from foo to bar, the change event listener works as expected. However, when resetting the select element via Java ...

Insert a clickable element within an HTML document

I have an idea for a questionnaire that includes questions and an interactive element at the end. At the completion of the questionnaire, there will be a button labeled "display answers" which users can click to reveal the correct responses. For example, ...

Improving Website SEO with jQuery-Generated Anchor Links for Dynamic Content

So, is this a safe method to use internal links on your site? I have the index page generating the usual php content section and passing it to the div element. THE MAIN QUERY: Will Google still index the pages using this technique? Common sense says it sh ...

Include the image pathway within the script to retrieve the image from the JSON file

Context : I am trying to extract an image from a path provided in the following JSON file: { "path" : " shape\/", "info" : { "author" : "" }, "name" : "shape", "layers" : [ { "height" : 612, "layers" : [ ...

Ways to restart script following Ajax call when additional search results are loaded

Implementing Klevu's search results page has been a manageable task so far. However, I encountered an issue where the search results page is displaying an Add to Cart button that should not be there, as confirmed by Klevu themselves. Their suggestion ...

Delay showing the div until it has finished loading

<section class="slideshow" id="slideshow"> <div id="slides"> <div class="slides-container"> <div class="slide"> <img src="img/people.jpeg" alt="Cinelli"> </div> < ...

Showcase a picture within a row of a table using Ajax in an MVC framework

Getting straight to the point, I have a similar code snippet in my Controller: return base.File(getSomeImageBitmap, "image/jpeg"); This code successfully displays the image in a new window using @Html.ActionLink. However, I want the image to be directly ...

How can I manage the horizontal scrolling in a large, expansive HTML Bootstrap table?

Currently, I am working on a Laravel project and have encountered an issue with a table that is overflowing from the right side. Despite trying various methods for implementing horizontal scroll, none of them seem to be effective in resolving the problem. ...

Bringing in an outside JavaScript document into VueJS

I'm having an issue with Vue CLI where I need to import a JavaScript file from a different server. Unfortunately, no matter what I try, I keep encountering the same error message as indicated below. https://i.sstatic.net/ssFy2.png Does anyone have a ...

Show button once modal has been closed

I have a 'start' button that triggers a modal window with an embedded video. Once the user closes the modal, I want to show a 'redeem' button after a delay of 6 seconds. HTML: <a id="video-start" onclick="openVideoModal()"><i ...

The axios method remains dormant even after submitting the form in React

When working with a form that allows file uploads, I encountered an issue where adding the type="submit" attribute to my 'upload' button prevented the axios method in handleSubmit from being called. However, if I remove the type="s ...

Asynchronous jQuery operations using promises and finally functionality

I am attempting to interact with a REST api using jQuery's ajax feature. My goal is to return the Promise<Customer> object, but I am encountering an error stating that the property finally is missing. It used to work before, so I assume there h ...

Manipulate SVG elements by dragging them along the boundary of the path

Looking to achieve a specific functionality where I can drag and drop an element along the edges of a drawn path, rather than inside the path itself. To clarify, the goal is to move the red marked element on the black line bordering the path, allowing move ...

Using listBox in conjunction with Jquery

Can someone please help me understand how I can save the state of two list boxes on post back using jQuery? I am unsure of which event to use, how to save the view state, or how to utilize a hidden field to persist the state of both list boxes. < ...

Sending a bulky item as a straightforward argument or object

Here's a simple question - will the veryLargeObj pass as a reference in both scenarios? And if so, is there any performance difference aside from object creation? Example 1: import veryLargeObj from './here' function someFn(veryLargeObj){ ...

Retrieve information from api and showcase it in html

Recently, I came across an interesting API file that caught my attention: My goal is to extract information from this API and present it on a HTML page in a visually appealing format. Despite scouring various forums, I have yet to find a solution that fi ...