Automatically add a class to the current list item in jQuery and remove the class from the

Here is my HTML code, where I am looking to dynamically swap the classes between two li elements every 2 seconds using jQuery.

<li class="">
    <a href="#">
        <img src="client_logo01.png">
    </a>
</li>

<li class="active">
    <a href="#">
        <img src="client_logo02.png">
    </a>
</li>

This is how I'm attempting to accomplish it:

$('ul li a').click(function() {
    $('ul li.current').removeClass('active');
    $(this).closest('li').addClass('active');
});

However, this current method only works on click events and I need it to happen automatically. Any suggestions?

Answer №1

It is quite evident that this code only runs when clicked, since a click event is the only one bound.

setInterval(function()
{
    // Remove .active class from the active li, select next li sibling.
    var next = $('ul li.active').removeClass('active').next('li');

    // Did we reach the last element? If so: select first sibling
    if (!next.length) next = next.prevObject.siblings(':first');

    // Add .active class to the li next in line.
    next.addClass('active');
}, 2000);

If you run this on document ready, the script will move the active class to the next sibling every 2 seconds.

This code will work regardless of how many li children your ul element has

View the jsfiddle demo here: http://jsfiddle.net/kg4huLrL/2/

Answer №2

Give this a try: take away the active class from the li element that has the class active, and add the active class to its adjacent li sibling.

   setInterval(function(){
       var $active = $('ul li.active');
       $active.removeClass('active');
       $active.siblings().addClass('active');
   },2000);

Check out the Demo

Answer №3

If you're looking to implement a recurring function, consider using setInterval. Check out this helpful post on how to utilize it effectively:

Working with setInterval

Answer №4

setInterval(function() {
    if($('ul').find('li.active').eq(0).next('li') != null) {
        $('ul').find('li.active').eq(0).removeClass('active').next('li').addClass('active');
    } else {
        $('ul').find('li.active').eq(0).removeClass('active');
        $('ul').find('li').eq(0).addClass('active');
    }
}, 2000);

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

"Implementing a fixed header and footer with a scrolling content area within a parent div that has a fixed position for

I'm seeking assistance with some CSS tasks. Specifically, I need to maintain the same functionality in responsive view when utilizing a fixed position in the parent div (Bootstrap 5 is in use). (the main focus of this project is on fullscreen view of ...

Tips for implementing and utilizing onclick functions in EJS

My goal is to develop a trivia game with interactive features. I aim to enable users to click on an answer, which will trigger a border effect and increase the points variable. Below is the layout of the entire page: <% include ../partials/boilerp ...

Arranging individual spans within a div using CSS for perfect alignment

My current code looks like this: <div id='div_selectores' class='row_titulo '> <span class="label_selector" id="lbl_show"></span><span id="div_selector_show"></span> <br /> <span class ...

Exploring Next JS: Effectively altering SVG attributes and incorporating new elements

I have integrated SVGR to load an SVG as a component in my latest Next.js 13 application: import CvSvg from './../../public/image.svg' export default function Home() { return ( <div className="flex flex-col min-h-screen" ...

Efficiency in Javascript coding techniques

Hey there, I'm seeking some feedback on the efficiency of my aspect ratio function. This function is designed to determine the aspect ratio and limit the size of an image. Take a look and let me know what you think! function constrainTwoNumbers(optio ...

The issue encountered while attempting to utilize jspdf for exporting data

Currently, I am working on developing a web application using angularJS in combination with asp.net. My main goal is to export data into a PDF file, but unfortunately, I am facing some challenges in achieving this. While browsing on StackOverflow, I came ...

Saving the value of array[i] from a for loop into a fresh array results in undefined

I am currently developing a matching algorithm that compares two arrays of strings. If there is an exact match (===), it stores the results in the unSafeResult array. If there is a match using Regex, it stores the results in the warningResult array. Howeve ...

Retrieve information from the form and construct a multi-layered array with it

I'm working on a basic HTML form structured like this: <form name="test" action=""> <tr class="selectable" data-selected=false> <input type="hidden" name="product[gate][id] value=<? echo $pid?>"/> <input ...

What is the best way to transfer Flow type properties from one React component to another?

I'm in the process of developing a component that will wrap another component known as Button. The tricky part is that the library where Button is defined does not expose the type of its properties. In order to properly assign types to my component, ...

Tips for efficiently transferring a retrieved object from App.js to a child component in ReactJS version 16 and above using asynchronous methods

TL;DR How can I pass a fetched object from App.js to a child component asynchronously? Do I need to wait for the data to be completely fetched before returning App.js? If so, how can I achieve this? In an attempt to create a dashboard using react-chartj ...

Utilizing jQuery to pinpoint the exact position within a Flexbox container

I have a unique setup with multiple boxes arranged using Flexbox as the container and list tags as individual boxes inside. These boxes are responsive and change position as the width is resized. My goal is to use jQuery to detect which boxes are touching ...

Dealing with the response data from $http request in AngularJS

Below is the client-side code written in AngularJS (which is functioning properly): $scope.ajaxLogin = function(){ var fn = document.getElementById("username").value; var pw = document.getElementById("password").value; $http({ url: "my ...

Exploring a property within a JavaScript object

Within my code, I am working with an array of objects called user. When I try to log the first object using console.log(user[0]);, I receive this output: Object {activityId: "2", id: "1", activityDt: "01/15/2016"} Afterwards, I attempt to store user[0] in ...

What is the best way to display my .js.erb file in this context?

After having a form that calls a controller action, the controller action then redirects to another action (my `create` action) with the following code: respond_to do |format| format.html format.js end Despite having a create.js.erb file that should ...

What is the best way to determine if an image already exists in a database where the objects are spread across two distinct SQL tables?

Currently, I am working on a project using classic ASP and SQL. In this project, I have an input box where the image name is entered by the user after clicking the "Update" button. Upon clicking the update button, pre-existing images are displayed in a tab ...

I am facing an issue with the Angular signup page that is using ui-router, as it is unable

I have been working on an Angular sign-up page and here is the project directory structure: signUpPage-Angular bin bower_components model mongodbApp.js node_modules **partials fail.html main.html succe ...

Execute a sorted operation with proper authorization

Recently, I developed a NextJs dashboard that enables Discord users to connect to their accounts. One of the main features is retrieving the user's guilds and filtering them to include only the ones where the user has either the MANAGE_GUILD permissio ...

Aligning the navigation links vertically

I am working on aligning my navigation bar vertically, even when I scroll the page. I found a method in another thread which suggests using the following CSS code for vertical alignment: #container { position: absolute; top: 50%; height: 400p ...

The error message I'm receiving is saying that the map function is not recognized for the posts variable (posts.map

I encountered a puzzling error, even though everything seems fine: posts.map is not a function import React from 'react' import { useSelector } from 'react-redux' export const PostsList = () => { const posts = useSelector(state = ...

Customize the antd theme in a create-react-app project without the need to eject webpack

Struggling with customizing antd in my react app. I'm hesitant to mess with the webpack config.js file since I'm not well-versed in webpack. My goal is to avoid having a site that looks like a generic antd clone, but all my attempts at customizat ...