Utilizing Jquery to apply CSS styles to three div elements sequentially with a timed loop of N seconds for each

I have 3 different HTML divs as shown below:

HTML

<div id="one" class="hide">Text one</div>
<div id="two" >Text two</div>
<div id="three" class="hide">Text three</div>

I am looking to use jQuery to dynamically change the CSS of these divs at regular intervals. Here is an example of how I want it to behave:

JS

// First N seconds : 
$("#two").hide(); 
$("#one").show();

//Next N seconds:
$("#one").hide(); 
$("#three").show();

//Next N seconds:
$("#three").hide(); 
$("#two").show();

The cycle should then repeat, switching between the divs in this pattern.

I have attempted using setInterval, but so far I haven't been able to make it work smoothly without skipping actions.

Instead of relying on checking the visibility of divs through CSS classes, I am seeking a method that will allow me to switch between the divs based on the IDs provided in an array. For instance:

idArray=["one", "two", "three"];

Answer №1

It seems like your code may be a bit confusing since the selectors you've mentioned use ids instead of classes as intended.

One alternative approach is to target all the div elements and implement a combination of setInterval, addClass, removeClass, and hide methods to achieve the desired functionality.

var $current = $('div').first();
// Hide all divs initially
$('div').addClass('hide');
// Display the first div
$current.removeClass('hide');

var interval = setInterval(function() {
    // Hide all divs
    $('div').addClass('hide');
    if($current) {
        $current = $current.next('div');
    }

    if($current && $current.length === 0) {
         $current = $('div').first();   
    }
    $current.removeClass('hide');                       
}, 500);

View Fiddle Example

UPDATE

This solution works for elements located anywhere on the page. To make it work, ensure that all elements to be shown or hidden have a common class assigned to them.

var $current = $('.toggle').first();
// Hide all elements with the 'toggle' class
$('.toggle').addClass('hide');
// Display the first element
$current.removeClass('hide');

var interval = setInterval(function () {
    // Hide all elements with the 'toggle' class
    $('.toggle').addClass('hide');
    var length = $('.toggle').length,
        found = false;

    $(".toggle").each(function(index) {
        if($(this).is($current) && !found) {
             var nextIndex = index + 1;
            if(nextIndex >= length) {
                $current = $('.toggle').first();
            } else {
                $current = $('.toggle').eq(nextIndex);
                found = true;
            }
         }
    });
    $current.removeClass('hide');
}, 500);

Updated Fiddle Example

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's the simplest method for updating a single value within a nested JSON object using TypeScript?

Using TypeScript version ^3.5.3 Consider the following JSON data: const config = { id: 1, title: "A good day", body: "Very detailed stories" publishedAt: "2021-01-20 12:21:12" } To update the title using spread synta ...

Running multiple languages locally may encounter issues, however, Codepen operates smoothly without any problems

While conducting research, I came across several options for creating multilingual websites. After implementing one method (jQuery), I noticed some slowness in translation and processing the information. Additionally, it only partially worked in the normal ...

What is the best way to dynamically filter checkboxes based on user input using jQuery in the following code snippet?

In order to filter the checkboxes in the code below, I would like to only display the checkbox with a value matching the input entered in the input field with the class "js-filter-input". For example, if I type "uni1" in the input field, I want to show onl ...

Ways to implement two functions within a single onclick event

Is it possible to call two functions with onclick event? <input id = "test" onclick="func1()"> Can I add another function as well? How would I go about doing that? ...

Adjusting the width of columns in an HTML/CSS table

Struggling to format a table based on specific requirements with no success: Some columns need to adjust width to fit content. Other columns should share remaining available width equally. Table width must not exceed parent width but still fill it. I tr ...

Express/axios fails to properly configure cookies and headers for response delivery

I am facing a complex issue with my project that involves two APIs. One API serves as the front-end of the application, while the other is for the back-end. The process simply entails sending requests from the front-end API to the back-end API. The front- ...

What is the purpose of using *//<![CDATA[* and *//]]>* in a jQuery code snippet?

Check out this JavaScript code snippet that I have: <script type="text/javascript> //<![CDATA[ jQuery(document).ready(function() { jQuery("#page_template option[value='sidebar-page.php']").remove(); }); ...

Obtain the reconstructed on-site dispatch mechanism from withReducer in conjunction with withHandlers

I have a situation where I have a component that is already connected to the redux store and has access to the dispatch function. In an attempt to update the local state of this component, I am utilizing withReducer and withHandlers in the following manner ...

Using Django Form with Bootstrap: Incorporating CSS classes and <div> elements

I am currently implementing Twitter Bootstrap with Django to style forms. Bootstrap can enhance the appearance of forms, but it requires specific CSS classes to be included. My challenge lies in the fact that Django's generated forms using {{ form.a ...

Display two lists of models categorized by time

I have two lists of model types that are initialized in the controller and values are inserted into them. These list objects are then assigned to ViewData so that I can iterate through them using a foreach loop. However, the issue is that the models of the ...

The onClick event is not executing my function

Having trouble triggering the onclick() event when trying to modify table data using ajax. Here's the code snippet: (the onclick() event is located in the last div tag) @{ ViewBag.Title = "Edit_Room"; Layout = "~/Views/Shared/_LayoutAdmin.csh ...

Can someone please provide a reference to an online illustration of implementing TinyMCE with a print format similar to Microsoft Word

Are there any online resources demonstrating the use of TinyMCE with a print layout resembling Word, with visible page breaks? Alternatively, are there any other WYSIWYG editors with a built-in print layout feature available for open source use? ...

Tips for implementing manual gravity effects on objects in cannon.js?

Is there a proper way to control gravity on individual objects without compromising collision events or rotation velocity? I came across this issue but seeking a more comprehensive solution. In my situation, I need player physics to function normally, wh ...

The Angular directive ng-model is not able to return a value

I'm currently troubleshooting an issue with the filters in an older project. Here's the HTML snippet: <input type="text" class="form-control" ng-model="FilterEventsEdit" ng-change="FilterEvents()" ...

The code inside the if statement is somehow executing even when the if statement is not true

Similar Question: Issue with jQuery function running at inappropriate times I've spent several hours trying to figure out why my function isn't working properly. I have a function inside an if ($window.width() < 1000) statement, but it se ...

Steps to finish (refresh) a mongoDB record

Currently, I am dealing with the following scenario: An API request from one service is creating multiple MongoDB documents in a single collection. For example: [ {_id: 1, test1: 2, test: 3}, {_id: 2, test1: 3, test: 4} ] Subsequently, a second service ...

Validate if the token has expired by utilizing this JWT library

My token configuration looks like this: jwt.sign( { user: pick(user, ['_id', 'username']) }, secret, { expiresIn: '2m' } ); However, when attempting to verify if the token has expired, the following code isn ...

What is the best method for sending PHP data to an HTML file?

Once the user logs in, I aim to direct them to a separate HTML page (a landing page) that greets them with "welcome, (user)." I initially attempted to utilize cookies for this functionality but realized it isn't feasible. How can I achieve this? Here ...

The radio button is not appearing correctly in my HTML form

Seeking guidance as a newcomer to html and css. Looking to create a signup form using html and css, but encountering issues with the radio button not displaying in the browser. Unsure of the root cause of the problem. Any assistance would be greatly apprec ...

Prevent running function bodies simultaneously based on user events in JavaScript until a previously triggered execution is completed

When a user clicks on a button in my component, the doSomething function is activated. The issue I am facing is that doSomething takes between 200-1100ms to finish execution and change state. What complicates matters is that when the button is clicked rapi ...