How to Create Smooth Transitions for Text Arrays using jQuery's Fade In and Fade Out Features

I need to loop through an array of text and apply jQuery's fadeIn and fadeOut functions to each element.

var greetings = ["hi, I'm", "bonjour, je m'appelle", "hallo, ich heiße"]

The HTML structure I want is as follows:

<h2><span id="greetings"></span>Ch1maera</h2>

On the homepage of my website, I want it to display something like "hi, I'm Ch1maera" and then transition between the different greetings by fading them in and out, all while keeping "Ch1maera" on the screen without moving based on the length of the greetings. How can I achieve this?

Answer №1

To prevent Ch1maera from being affected by the greetings, adjust the text-align property of h2 to be set to right.

var hellos = ["hi, i'm", "bonjour, je m'appelle", "hallo, ich heiße"];
var index = 0;                                // index of the currently displayed hello
$("#hellos").text(hellos[0]);                 // start by showing a hello

(function animate() {                         // the function responsibe for the animation
  $("#hellos").fadeOut(1000, function() {     // first fadeOut #hellos
    index = (index + 1) % hellos.length;      // when fadeOut complete, increment the index (check if go beyond the length of the array)
    this.textContent = hellos[index];         // change text accordingly
  }).fadeIn(1000, animate);                   // then fadeIn. When fadeIn finishes, call animate again
})();
h2 {
  text-align: right;
  padding-right: 40%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2><span id="hellos"></span> Ch1maera</h2>

Answer №2

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8>

  
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
  <script>
    var messages = ["Message One", "Message Two", "Message Three"];

$( document ).ready(function(){
    displayMessage();
    setInterval(displayMessage, 5000);
});

var index = 0;
function displayMessage() {
  $('#message').fadeOut(1000, function() {
    index++;
    if(index >= messages.length)
    {
        index = 0;
        
    }
    $('#message').html(messages[index])
    $('#message').fadeIn(1000)
 
  });
}
    
    
    </script>
</head>
<body>
    <div id="message" style="display:none;">DEFAULT MESSAGE</div>

</body>
</html>

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

Utilizing the closest method to retrieve the form element

As I review code written by another developer, I came across a surprising method used to retrieve a form object. HTML for Login Form <form id="frm_login" action=""> <input type="text" name="username" id="username"> <input type="passwor ...

I encountered an issue while iterating through Object HTMLDivElement and applying ChileNode style z-index, resulting in an undefined output in both Firefox and Chrome browsers

function adjustPosition(currentDiv) { try { for (var i = 0; i < document.getElementById("parentContainer").childNodes.length; i++) { document.getElementById("parentContainer").childNodes[i].style.zIndex = 0; ...

What are the options for transferring information between HTMX and Flask using JSON or another format aside from HTML?

So I am currently working on an app using Flask and HTMX. While I understand that htmx requires data in HTML format to swap with a specific target element, I am wondering if there is a way to update the current page using different formats such as dictiona ...

PHP Foreach Loop doesn't execute JavaScript Sum Function as expected

Currently, I have a JavaScript function implemented that utilizes the IDs of 3 textboxes to retrieve their numeric values, sum them together, and display the result in the fourth textbox. In addition, I am fetching a list of individuals from my database an ...

The JQuery code that I designed is causing a significant decrease in performance specifically in IE7, while other browsers are not

As this is my first time asking a question on this platform, I apologize if I come across as inexperienced with the rules (even though I quickly familiarized myself with them). Now, onto the issue at hand. I have created a customized menu in SharePoint 2 ...

Experiencing difficulties when establishing a connection between MongoDB and Node.js

I'm encountering an issue when attempting to connect MongoDB and Node.js on my local server. Can anyone assist me with solving this problem? Below is my JavaScript code: const mongodb = require("mongodb"); // Provide the function to connect to the d ...

Comparing the use of jQuery's data() method versus directly accessing attributes with native JavaScript using get

I want to retrieve general information from my website using javascript. I have a few different options available: I could use an html element: <input type="hidden" value="MyValue"/> Another option is to use a custom attribute in an existing h ...

Apply a 2 pixel top border to an HTML table

Is there a way to add a double border at the headcell without using background images? Currently, I have a white color border top and want to add a grey color border on top of the white one. Is it possible to achieve something like #ccc and #fff for borde ...

Insert elements to an XML document in Node.js using libxmljs

I've been working on updating an XML file by adding a new child node using the code below: var libxml = require('libxmljs'); var xml = '<?xml version="1.0" encoding="UTF-8"?>' + '<root>' + ...

"Obtain a DOM element within an Angular directive by using the jQuery find method

When inspecting the DOM, I can see the element anchor tag present but cannot retrieve it using jquery.find(). The console returns a length of 0, preventing me from initializing angular xeditable on that element. angular.module('built.objects') ...

Encountered an issue while trying to update a ServiceWorker for scope - Received a HTTP error

I encountered a puzzling issue with my Vue PWA app, as our error logs are flooded with instances of a particular user experiencing an error that myself and another person cannot reproduce. Failed to update a ServiceWorker for scope ('https://myapp.com ...

Apologies, we are experiencing a server error. TypeError: Unable to access the 'map' property of an undefined

I'm struggling to grasp the concept of fetching external data using server-side rendering with the getServerSideProps method. In particular, I am facing difficulties with the search functionality and how to handle the returned data. As someone who is ...

A method for consolidating multiple enum declarations in a single TypeScript file and exporting them under a single statement to avoid direct exposure of individual enums

I am looking to consolidate multiple enums in a single file and export them under one export statement. Then, when I import this unified file in another file, I should be able to access any specific enum as needed. My current setup involves having 2 separ ...

The concept of the "Centering Effect" refers

Check out the code I have below: http://jsfiddle.net/G8Ste/577/ I want the effect to expand in all directions, not just to the right and bottom. I've experimented with margin: 0, auto, and other CSS and HTML styles to center it, but nothing seems t ...

Converting strings into time formats in MongoDB

My string appears as follows: schedule_time = { start_time : "13:00", end_time : "14:10" } Now I need to convert it into time in MongoDB. I attempted using dateFromString but encountered some issues. The aggregation query: db.getCollection('appoi ...

sort jquery alphabetical characters

I have created some html and jQuery code that allows me to hide elements based on class name when I click on specific buttons in the filter div. However, I am now looking to add functionality to sort the elements alphabetically by class name when I press ...

Converting XML schema to JSON format using Node.js

I am attempting to loop through or access keys of a JSON object that was created from an XML object in node.js. Here is my current code: var fs = require('fs'); var parser = require('xml2json'); var xsd = require('libxml-xsd&apos ...

The process of adding a tooltip icon to a Select component in Material-UI

I'm currently working with the material UI tooltip component and I want to position my tooltip to the right of a dropdown, right next to the down arrow as shown in the image below: https://i.stack.imgur.com/O2gwh.png However, the way it is set up no ...

Padding problem arises when you wrap an image with an anchor tag

I'm having an issue with a div containing an anchor-wrapped image, as there seems to be extra padding at the bottom of the div. How can I remove this? HTML: <div id="lineup"> <div class="line-up-click"> ...

New to React: Arrow Function Example that Might Puzzle You

As a beginner in React/ES6, I came across this code snippet for handling a checkbox within a custom component that contains a material-ui CheckBox. My goal is to expand the custom component by adding more fields, such as a textbox where users can provide a ...