Iterate through Javascript quotes and automatically navigate to the first quote once the loop is completed

I've encountered an issue with the script where I am unable to loop back to the first element once all child elements have been traversed.

https://jsfiddle.net/pad5bp0o/2/

Here is the jQuery code snippet:

$(document).ready(function() {
  var length = $("#tips li").length;
  var old = 0;

  function show() {
    var news = getRan();
    $("#tips li").hide();
    $("#tips li:nth-child(" + news + ")").fadeIn("fast");
    old++;
  };

  function getRan() {
    var news = old + 1;
    if (news < length) {
      return news;
    } else {
      var news = 0 + 1;
      return news;
      old++;
    }
  };

  show();
  $("#something").html(length);
  setInterval(show, 1000);

});
Here is the CSS code snippet:
#tips,
#tips li {
  margin: 0;
  padding: 0;
  list-style: none;
}

#tips {
  width: 250px;
  font-size: 16px;
  line-height: 120%;
}

#tips li {
  padding: 20px;
  background: #e1e1e1;
  display: none;
}

.active {
  opacity: 1;
}
Sample HTML markup:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="tips">
  <li>... if you want to become a better coder you need to eat your vegetables?</li>
  <li>... it takes more time to code a web page than to make a pizza?</li>
  <li>... you should validate your code?</li>
  <li>... jQuery is your friend? For real!</li>
  <li>... no matter what some people claim, you can't learn CSS in 3 hours?</li>
</ul>
<div id="something"></div>

Answer №1

Make sure to update the old variable back to its initial value when you reach the final element.

function getRan() {
    var news = old + 1;
    if (news <= length) {
        return news;
    }

    news = 1;
    old = 0;
    return news;
};

Check out the DEMO here

Answer №2

Once the limit of 5 is reached, reset the variable (old) back to its initial value of 1.

If you want a simpler function, you can try the updated version in this revised fiddle.

$(document).ready(function() {
  var length = $("#tips li").length;
  var old = 1;

  function show() {
    $("#tips li").hide();
    $("#tips li:nth-child(" + old + ")").fadeIn("fast");
    if (old == length) {
      old = 1;
    } else {
      old++;
    }
  };

  show();
  $("#something").html(length);
  setInterval(show, 1000);

});
#tips,
#tips li {
  margin: 0;
  padding: 0;
  list-style: none;
}
#tips {
  width: 250px;
  font-size: 16px;
  line-height: 120%;
}
#tips li {
  padding: 20px;
  background: #e1e1e1;
  display: none; /* hide the items at first only */
}
.active {
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="tips">
  <li>1. ... if you want to become a better coder you need to eat your vegetables?</li>
  <li>2. ... it takes more time to code a web page than to make a pizza?</li>
  <li>3. ... you should validate your code?</li>
  <li>4. ... jQuery is your friend? For real!</li>
  <li>5. ... no matter what some people claim, you can't learn CSS in 3 hours?</li>
</ul>
<div id="something"></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

Is React capable of storing and recognizing images within its system?

As a junior developer, I find this aspect confusing. Specifically, does reusing the same image on multiple routes in React result in the user downloading it more than once in the browser? I am striving to understand whether using the same image repeatedly ...

Utilizing Pseudo Classes in Custom Styled Components with MUI

Exploring the world of React and MUI styled components for the first time. Currently, I'm delving into grid layouts and trying to style all children of a specific component. My goal is to target ${Item1}:nth-child(3n-1), ${Item2}:nth-child(3n-1), ${It ...

Animating an image into a Vue.js div

Is it possible to create a dynamic image animation using Vue.js? I am looking to create an interactive "Add to Cart" experience where when a user clicks on the button, the product's image smoothly glides over to the shopping cart icon before fading a ...

Only expose the next element when the collapse occurs

In my Flask templates, I am facing an issue with displaying scores using a collapse feature: Contact.html <button type="button" class="btn btn-secondary btn-sm" data-target="#score" data-toggle="collapse" data-pla ...

What is the best way to connect two buttons in separate divs?

I'm facing a challenge of adding two buttons side by side when they are located in different div elements. I've tried using the float property in the btn-group, but it interferes with the functionality of the dropdown and affects the animation. H ...

Generating a fresh object from an existing object by incorporating updated values using Angular and Ionic version 3

Currently, I am actively working on an Ionic 3 project that utilizes Angular framework. Within my project, I have a JSON object called 'person' which consists of data fields such as name, job, and home. One feature in my app is an Ionic toggle b ...

What is the best way to set the v-model property to an object that is constantly changing

I'm in the process of creating a dynamic form that allows users to add additional fields by simply clicking on a button labeled "adicionar condição." The concept is similar to what can be seen in the screenshot below: https://i.stack.imgur.com/Mpmr6 ...

Simplified JavaScript Object Structure

A JSON array that is flat in structure looks like this: var flatObject = [ { id : "1", parentId : "0", name : "object 1" }, { id : "2", parentId : "1", name : "object 2" }, { id : "3", parentId : "2", name : "object 3" }, { id : "4", pare ...

Finding the correlation between SVG element IDs and JSON keysUnderstanding how to pair up

Currently, I have an SVG file that can be viewed here. My goal is to present specific data when elements within the SVG are clicked. The data is in JSON format and I am looking to match each ID of an SVG element with a key in the JSON data. If both the key ...

JavaScript example: Defining a variable using bitwise OR operator for encoding purposes

Today I came across some JavaScript code that involves bitwise operations, but my knowledge on the topic is limited. Despite searching online for explanations, I'm still unable to grasp the concept. Can someone provide insight into the following code ...

Can you please provide the Jquery alternative to this?

Can you provide a sleek jQuery solution for this problem? $('A').append(str); ...

Is it possible to add filtering to my MongoDB when using the find() method in express routing? If so, how can

Hey there! I have this GET function that uses async to find a specific "Category" mongoose Schema that the user just clicked on, along with another "Tool" mongoose Schema which fetches all tools from my database and sends them both to a rendered page. I&a ...

What is the method to retrieve the base host in AngularJS?

I need assistance with the following URL: https://192.168.0.10/users/#!/user-profile/20 When I use $location.host, it returns 192.168.0.10 However, I only want to extract https://192.168.0.10 What is the best way to achieve this? ...

The onload function for a JSP embedded in an IFrame was causing the IFrame to expand and fill the entire browser

I am encountering an issue with an IFrame inside a DIV where the SRC attribute is being dynamically set by a JavaScript function. When the SRC is set to "file.jsp", an onload function within the file.jsp containing style adjustments was causing the IFrame ...

Tips for obtaining latency measurements from the DailyMotion player during a live video stream

Is there a way to determine the latency of DailyMotion live video for synchronization with events, such as displaying speaker names alongside the video? I have been utilizing the DailyMotion player API in JavaScript but haven't found any information r ...

What sets apart the two syntaxes for JavaScript closures?

Similar Query: Is there a distinction between (function() {…}()); and (function() {…})();? I've come across a way to prevent variables from becoming global by using the following syntax: (function ($, undefined) { })(jQuery); Rec ...

Passing data from a method callback to a function and returning a variable in the same function

Is there a way to properly return the latlon variable from the codeAddress function? The typical 'return latlon' doesn't seem to work, possibly due to scope issues. Any suggestions on how to resolve this? function codeAddress(addr) { ...

How can I convert a PHP array into radio buttons in an HTML form?

I'm looking to develop a survey using HTML, PHP, and Javascript. I have my questions and answers stored in a csv file (which will eventually be transferred to a SQL server). My main concern is how to convert my answers into radio button types so that ...

Passing a null value to the server through jQuery AJAX is not possible. Instead, the server receives the string "null" as the value

Recently, I've been working on updating a javascript/php/ajax application to incorporate jQuery so that it can function smoothly across all browsers, not just Firefox. However, I've hit a snag when trying to pass true, false, and null values usi ...

Utilizing AngularJs to differentiate between arrays and strings within an HTML template

I'm currently facing a challenge with creating a dynamic HTML template. In order to present data in a table, I need to distinguish between a regular String and an Array. Firstly, the HTML template is embedded within another template using the data-ng- ...