Is there a way to create a sequence where text fades in only after the previous text has completely faded out?

Currently, I am using JQuery to create a continuous slideshow of text values. However, after some time, multiple texts start to display simultaneously, indicating a timing issue. Even when hidden, the problem persists. My code includes 3 strings of text.

<h3 class="s1" style="display:none;"> ONE! </h3>
<h3 class="s2" style="display:none;"> TWO! </h3>
<h3 class="s3" style="display:none;"> THREE! </h3>

The function in my code looks like this:

setInterval(function(){
    $(".s1").fadeIn(1000);
    $(".s1").fadeOut(1000,function(){
        $(".s2").fadeIn(1000);
        $(".s2").fadeOut(1000,function(){
            $(".s3").fadeIn(1000);
            $(".s3").fadeOut(1000); });
    }); },6000);

Initially, the script works smoothly but after a while (around 30 seconds or more), the strings start overlapping. Ideally, the output should look like:

0:01 --> ONE!
0:02 -->
0:03 --> TWO!
0:04 -->
0:05 --> THREE!
0:06 -->
0:07 --> ONE!

However, what actually happens is something like:

0:01 --> ONE!
0:02 -->
0:03 --> TWO!
0:04 -->
0:05 --> THREE!
         ONE!
0:06 -->
0:07 --> TWO!
         ONE!
...  --> ONE!
...  --> TWO!
...  --> THREE!

How can I modify the code so that each string appears only after the previous one has disappeared completely?

Answer №1

UPDATE: I overlooked the last requirement in your question about fading only once the other has faded. I have made the necessary changes to reflect this.

Just like there are multiple ways to approach a problem, there are different methods to achieve the desired outcome. Although I am not entirely sure of the context of your project, the following solution may offer some flexibility and scalability:

.js

var vl = [];

vl.interval = 1000;
vl.fadeSpd = 300;
vl.slide = $('.slider .slide');
vl.cntSlides = vl.slide.length;

function startSlider() {
    setInterval( function() {
        changeSlide();
    },vl.interval);
}

function getNextSlide() {
    active = $('.slider .active').index();
    if(active == (vl.cntSlides - 1)) {
        nextSlide = 0;
    } else {
        nextSlide = active + 1;
    }
    return nextSlide;
}

function changeSlide() {
    nextSlide = getNextSlide();
    $('.slider .active').fadeOut(vl.fadeSpd).removeClass('active');
    setTimeout( function() {
        vl.slide.eq(nextSlide).fadeIn(vl.fadeSpd).addClass('active');
    },vl.fadeSpd);
}


startSlider();

The code allows for the addition of new items or slides without the need for extensive modifications. The slider initiates with 'startSlider', defining the interval time. 'changeSlide()' facilitates the transition between slides, determining the next slide and handling the fade animations.

.css

.slider {
    position: relative;
    text-align: center;
    width: 300px;
}
.slide {
    position: absolute;
    display: none;
    width: 100%;
    top: 0;
    left: 0;
}
.active {
    display: block;
}

The CSS styling positions each item on top of one another within a relative container such as 'slider'. Modify the container's dimensions as needed; in this example, a width of 300px is utilized. Additional styling options can be explored to customize the slider further!

Main Page

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="slider">
    <h3 class="slide active">One!</h3>
    <h3 class="slide">Two!</h3>
    <h3 class="slide">Three!</h3>
</div>

Introducing the container ensures that the stacked slides maintain their positioning parameters. Feel free to adjust the layout based on your requirements.

I hope this information proves useful for your project. While it may not directly address your specific needs, others might find value in these insights. Enjoy experimenting with the functionalities! :)

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

Maintain the central alignment of the entire page (including the horizontal scrollbar) while zooming in

I have successfully centered elements, but now I am trying to center the entire page (i.e. have the horizontal scrollbar in the middle) when zooming in. Currently, the scrollbar stays at the very left end as I zoom in. * { margin: 0; padding: 0; box ...

When using jQuery without $.ajax, the combination of $.POST and json functions will return "null" when retrieving data from PHP's json_encode

Although I am writing for the first time, I have been a part of this community before. I decided to post my query here because none of the similar questions seemed to offer a clear solution to my specific issue. I am currently working on a tic-tac-toe gam ...

How can the id of the parent element be retrieved within this function?

Is there a way to retrieve the ID of the parent element within the same function and log it in the console? I attempted to obtain the ID of the parent element that I bound the function to. $('#customized-player').mediaelementplayer({ al ...

Utilizing ng-repeat, filter, and the uib-popup-datepicker to refine and display specific data within a table column

I'm currently facing a common scenario in my Angular application where I need to filter items from an ng-repeat using an HTML5 input of type 'date' or Angular-UI-Bootstrap's 'uib-popup-datepicker'. Despite extensive research, ...

Pass an array of files from a Jquery ajax request to a controller action

I am facing an issue where I can successfully pass a single file as System.Web.HttpPostedFileBase, but when attempting to pass an array of files, the controller's action receives null. I have attempted sending an array of files. HTML: <i ...

Effortless code formatting with VS Code for TypeScript and JavaScript

Does anyone know of any extensions or JSON settings that can help me format my code like this: if(true) { } else { } Instead of like this: if(true){ } else { } ...

Trouble with jQuery script causing initial word count issue in textarea upon page load

I have implemented a word count textarea jQuery script and I am trying to figure out how to update the word count onload to 2 when the text area initially displays "this example". Currently, it shows 0 words. Although I can set focus on it and move the c ...

Having trouble retrieving user data that is being passed as a context value using React's useContext

Currently, I am integrating Google login into my React application and facing an issue with passing the response data from Google login (i.e. user data) to other React components using the useContext hook. Unfortunately, I am unable to retrieve the user da ...

Unlocking the Secrets of Launching a Modal with Javascript

I currently have an HTML code that includes a fabulous floating button. When I click on this button, I would like to open a modal popup window but unfortunately, I am unsure of how to achieve this. index.html <html> <head> <link rel="s ...

Passing an object in an ajax call to a function: a comprehensive guide

@model IEnumerable<HitecPoint.BlackBox.Models.SMSReportModal> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"> </script> <script type="text/javascript"> var MyAppUrlSettin ...

What is the best way to automatically assign a class attribute to all form widgets in Django?

Whenever I create a form using Django, I want the input tag to automatically include a specific CSS class (form-control). Currently, I have to manually add lines of code in my forms.py file for each field like this: class InsertItem(forms.ModelForm): ...

What is the reasoning behind the presence of hidden elements on the Google Search Result Page?

While using the debugging feature, I stumbled upon some hidden elements on the page. Can anyone shed some light on why these elements are present with a display attribute of none? The first one on the left is an iframe, followed by multiple text areas. ...

Using Javascript within AEM to update a class upon checkbox selection

I need assistance targeting the 'horizontal-video' class within a div in an AEM component. I am attempting to add a second class called 'flipped' to the div if the author clicks on a checkbox with the ID of 'coral-id-540'. Unf ...

Having issues with handling ajax response in a Node.js application?

I am encountering an issue with my ajax post request to my node js backend. After sending the request and receiving a response, instead of updating just the resulttoken in the view, the entire HTML page seems to be loaded according to the console. I am see ...

What are the recommended methods for updating data using mongoose?

There are two methods for updating data with mongoose. Using model methods, such as User.updateOne({username}, {$set: {age}}) Finding the document, making changes to its properties, and saving it. Like this: const user = await User.findById(userId) user. ...

Is it possible to use jQuery to identify when an item is located on a new line within a textarea?

I am looking to create an array from the content within a textarea. The textarea holds a varying list of names, each consisting of only one word without any spaces. Currently, I have the following code in place. However, my issue lies in the fact that the ...

Exploring the functionalities of Stripe's latest Search API integrated with metadata features

I'm currently working on a project to showcase products stored in the Stripe Database. I attempted to implement this using if statements, filters, and the new Search API of Stripe, but unfortunately, my attempts were unsuccessful. Any ideas on what el ...

Is the provided code snippet considered a function-statement, function-expression, and function-expression-statement?

Currently, I am examining some code snippets from the EcmaScript.NET project. Specifically, I am delving into the definitions within FunctionNode.cs file. The comment above the definitions provides a detailed explanation of the three types of functions tha ...

Customize the Kendo UI by integrating it with HTML tables and dropdown lists

I am trying to utilize an HTML table as the data source for kendo-ui jQuery, and also enable inline editing with a drop-down list. To achieve this, I have written the code below: However, my issue arises when a user double clicks on a row of the table to ...

Error message in Ionic 2: "Property is not found on type"

Currently, I am working on a project in Ionic 2 and have encountered a stumbling block with a seemingly simple task. My issue lies with a Textbox where I aim to input text that will then be displayed. I found some code on a website (http://www.tizag.com/j ...