Automatically play the elements within a div using jQuery

I have various sections within different divs that I want to display without the need for manual clicking on tabs. While I've been able to toggle the visibility of these sections by clicking, I would prefer them to display automatically in a loop using jQuery. Below are the codes I've been working on:

$(document).ready(function(){
       $('#advantages').click(function(){
         $('#featureContent').fadeOut(400).addClass('hidden');
         $('#advantageContent').fadeIn(400).removeClass('hidden');
         $('#benefitsContent').fadeOut(400).addClass('hidden');
       });

        $('#benefits').click(function(){
          $('#featureContent').fadeOut(400).addClass('hidden');
          $('#advantageContent').fadeOut(400).addClass('hidden');
          $('#benefitsContent').fadeIn(400).removeClass('hidden');
        });

        $('#features').click(function(){
        $('#featureContent').fadeIn(400).removeClass('hidden');
        $('#advantageContent').fadeOut(400).addClass('hidden');
        $('#benefitsContent').fadeOut(400).addClass('hidden');
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="featureLinks" class="col-lg-6 col-md-6 col-sm-6">
            <ul class="text-center">
               <li id="features"> Smart travel </li>
               <li id="advantages"> Smart route </li>
               <li id="benefits"> Smart payment </li>
             </ul>
         </div>

    <div id="featureContent" class="col-lg-6 col-md-6 col-sm-6">
          <h2 class="text-center"> Smart travel </h2>
           <ul>
              <li>All your favourite transit service providers like Uber, KLM, Great Western Rail and Blue Star Ferries on one integrated app! </li>
             
              <li>Compare the availability, price and ETA for taxis/buses, flights, metro andferries, anytime and anywhere.
              </li>
           </ul>
      </div>

      <div id="advantageContent" class="col-lg-6 col-md-6 col-sm-6 hidden">
        <h2 class="text-center"> Smart Route </h2>
           <ul>
              <li> Big data is finally at your service</li>
             <li>Go where you&#39;ve never gone before with integrated Satellite navigation system.</li>
           </ul>
      </div>

       <div id="benefitsContent" class="col-lg-6 col-md-6 col-sm-6 hidden">
       <h2 class="text-center"> Smart Payment </h2>
          <ul>
               <li> Experience the ease and security of paying via the app. </li>
         </ul>
</div>

Answer №1

Hey @Yemmy, check out this cool example where a loop runs these animations 10 times. You can customize the delays to suit your needs.

$(document).ready(function(){
            var i = 0;
       while (i < 10){
         $('#featureContent').fadeOut(400).addClass('hidden').delay(400);
         $('#advantageContent').fadeIn(400).removeClass('hidden').delay(400);
         $('#benefitsContent').fadeOut(400).addClass('hidden').delay(400);



          $('#featureContent').fadeOut(400).addClass('hidden').delay(400);
          $('#advantageContent').fadeOut(400).addClass('hidden').delay(400);
          $('#benefitsContent').fadeIn(400).removeClass('hidden').delay(400);



        $('#featureContent').fadeIn(400).removeClass('hidden').delay(400);
        $('#advantageContent').fadeOut(400).addClass('hidden').delay(400);
        $('#benefitsContent').fadeOut(400).addClass('hidden').delay(400);
        i++
       };
    });

Check it out on fiddle: https://jsfiddle.net/nn4hgrv2/#&togetherjs=kcgRhDRIGb

Answer №2

If you're looking to call a function repeatedly on a timer, you can utilize window.setInterval. Check out the example below for a demonstration.

$(document).ready(function(){
       var elementsToRotate = [ $('#content1'), $('#content2'), $('#content3') ];
       var currentIndex = 0;

       window.setInterval( function() {
         if (currentIndex > elementsToRotate.length) currentIndex = 0;
         
         for (var i = 0; i < elementsToRotate.length; ++i) {
           if (i == currentIndex)
             elementsToRotate[i].fadeIn(400).removeClass('hidden');
           else
             elementsToRotate[i].fadeOut(400).addClass('hidden');
         }
         
         currentIndex++;
        }, 3000);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="links" class="col-lg-6 col-md-6 col-sm-6">
            <ul class="text-center">
               <li id="content1"> Content 1 </li>
               <li id="content2"> Content 2 </li>
               <li id="content3"> Content 3 </li>
             </ul>
         </div>

    <div id="content1" class="col-lg-6 col-md-6 col-sm-6">
          <h2 class="text-center"> Content 1 </h2>
           <ul>
              <li>This is the first content snippet.</li>
             
              <li>More information about the first content goes here.
              </li>
           </ul>
      </div>

      <div id="content2" class="col-lg-6 col-md-6 col-sm-6 hidden">
        <h2 class="text-center"> Content 2 </h2>
           <ul>
              <li>Details about the second content item</li>
             <li>Explore new features with Content 2.</li>
           </ul>
      </div>

       <div id="content3" class="col-lg-6 col-md-6 col-sm-6 hidden">
       <h2 class="text-center"> Content 3 </h2>
          <ul>
               <li> Learn more about the third content piece. </li>
         </ul>
</div>

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

Getting the next sibling element with Selenium: A complete guide

Having trouble targeting a textbox after the label "First Name" in a list to enter a first name. Here's what I've tried: WebElement firstNameLocTry = driver.findElement(By.xpath("//label[text()='First Name']/following-sibling::d ...

Tips for having <script> update onchange instead of just onload

Is there a way to update the output of the <table id="mortgagetable"> each time a user changes the input values in the form? Currently, it only updates on load. Additionally, the content of the <div id="years" style="display:inline-block;">25 ...

Combining JSON objects in Node.js

I am extracting data from my database and converting it to JSON format. However, I now want to merge all the JSON data into a single JSON object. I have attempted various methods, but due to my limited knowledge of JavaScript syntax, I have not been able ...

Mastering the art of nested await functions in JavaScript

In my current Nodejs application using mongoose, I am implementing cache with MongoDB in-memory and MongoDB database. This setup is running on Nodejs 8.9 with async/await support enabled. let get_func = async(userId) => { let is_cached = await c ...

Leveraging Spotify's webAPI to listen to a randomly selected album by a specific artist (ID

Welcome to my little project! As I am not a developer myself, please bear with me for any silly questions that may arise. My idea is to create an "audio book machine." The concept involves using a website that showcases various artists of audiobooks. Upo ...

What about a Material UI-inspired homepage design?

Looking at the demo image on the main page for Material UI has me really impressed. I am interested in using a similar theme with MUI for my web application. Can you advise me on how I can achieve this look, or do I have to start from scratch? https://i.s ...

Is it possible to use Highcharts in AngularJs without jQuery?

Is there a way to use Highcharts without relying on the full jQuery library? The current popular option seems to require jQuery, but I'm having trouble getting it to work without it: https://github.com/pablojim/highcharts-ng Can I develop a Highchart ...

How about creating a customized sorting algorithm from the ground up that incorporates a comparator?

My current assignment requires me to create a unique sorting method from scratch (cannot use Array.sort()) that accepts a comparator and organizes a list based on that comparator. const people = [ {name: 'Bill', age: 30, likes: 'food' ...

Spinning a div using Jquery

I'm having trouble getting a div to rotate. Despite checking the console, I haven't encountered any warnings or errors. If you'd like to see the JSFiddle version of it, feel free to take a look. Below is the code snippet I've been usi ...

End event in NodeJS response does not activate

I'm encountering an issue with sending the response data to the client. The response is not being sent and the 'end' event is not triggered. I'm at a loss on how to resolve this issue. My objective is to send the retrieved data from red ...

What's the best way in Angular 6 to set focus on an element that's being made content editable?

I am currently utilizing the contentEditable attribute in Angular 6 to allow for editing the content of elements within an ngFor loop. Is there a way to focus on a tag element when its contentEditable attribute is set to true? <div class="tag" *ngFor= ...

Attempting to align content in the center by utilizing table cells

I'm completely new to this, so please bear with me, but I have a question. I've been attempting to vertically align a div in the center of my webpage, but I can't seem to get it to work. The text always ends up loading in the top left corne ...

Retrieve Data from MySQL Database Using ExpressJS Pool Connection

I am relatively new to ExpressJS. I am encountering an issue where console.log is working fine and I can see the data in the terminal when I make a call. However, the data is not being returned as a response. Even after using console.log and return stateme ...

A JavaScript async function with a nested call inside

Below is my node function for the API server: router.post('/find', async (req, res) => { try { const firewalls = []; let count = 0; const devices = await Device.find({ ...req.body }); devices.forEach(async (item) => { ...

Express server unable to process Fetch POST request body

I'm currently developing a React app and I've configured a basic Express API to store user details in the database app.post("/register", jsonParser, (req, res) => { console.log("body is ", req.body); let { usern ...

Effortlessly glide to the form and center your attention on the textarea

Upon clicking the link, I aim to accomplish three tasks: Implement smooth scrolling down to #form Automatically focus on the textarea for immediate message writing Add extra top margin to account for a fixed top bar on the website. <a class="link" ...

The issue with the Woocommerce quantity increment buttons not functioning properly persists after an AJAX refresh, and the automatic load feature only activates after two

I've hit a brick wall with this particular issue. Many people have suggested solutions, but none seem to be effective for me. My situation probably resonates with quite a few individuals: I decided to customize the WooCommerce quantity input (/global ...

The function app.post in Express Node is not recognized

I decided to organize my routes by creating a new folder called 'routes' and moving all of them out of server.js. In this process, I created a file named 'apis.js' inside the routes folder. However, upon doing so, I encountered an error ...

Attempting to align three sections horizontally

I'm having trouble with my current HTML code and I can't seem to figure out what the issue is. As a beginner in HTML, I am struggling to understand. My goal is to have three columns: one on the left taking up 20% of the space, one in the center t ...

Executing jQuery AJAX with PHP using 'POST' method to receive and process PHP code

Something seems to have gone wrong with my setup; it was functioning properly before but is now encountering issues. When trying to make a POST call from an HTML file to a php file (which fetches data from a REST API), instead of receiving the expected API ...