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

Is it possible to trigger the setState() function of a parent component when a child component is clicked?

Hey there, I'm a new developer diving into the world of Reactjs. I've been working on setting up a Todo app but struggling to configure it just right. My main challenge is getting a button to add items to the list when submitted. I think I'm ...

Guide on shifting an element into a different one with the help of jQuery

I'm attempting to relocate an element within another in order to enable a css :hover effect. <ul> <li id="menu-item"> //move into here </li> </ul> <div class="tomove">...</div> 'tomove' is set to dis ...

access the content of a div element by its class attribute

Within the div element, a value has been set and I am attempting to retrieve this value using its class. However, the code below does not return the desired value. What mistake am I making here? How can I resolve this issue? <div title="Find on Amazo ...

Pass the most recent properties to the mousemove event handler

I am currently developing a click-and-drag feature, which involves: setting up a moveListener on the onMouseDown event having the moveListener trigger an action that updates certain props of the component (props.whichChange) cleaning up the mouseUp event ...

Refining the nodes and connections within a directed graph by implementing a filter triggered by clicking a button

I have successfully implemented a force-directed graph. My next step is to incorporate buttons in the main HTML data to enable further filtering. Unfortunately, I haven't been able to make it work yet. I would greatly appreciate any suggestions or gui ...

JSON object fails to iterate with ng-repeat

It must be the scorching temperature... Having a json object that I'm eager to loop through using ng-repeat, it should be straightforward, but alas! it's just not cooperating. Here's the HTML snippet: <a data-ng-repeat="x in template.m ...

Setting a header with the Axios module and Vue.js in Nuxt: A step-by-step guide

I've been attempting to set up an "Accept-Language" header for my SPA using vue.js (along with nuxt). Here's the approach I took, but unfortunately, it's not functioning properly. I specified that I am utilizing the axios module for nuxt. ...

Issues with $.ajax post not functioning as expected

I'm currently working on implementing a basic liking system for my website. Unfortunately, I've encountered an issue with the jQuery post function not performing as expected. The data values are not being inserted into the database tables, and t ...

Applying a Webkit Scroll Bar to a specific element on the webpage

I've been attempting to apply the Scroll Bar webkit styling to a particular element but haven't had any success. Despite searching extensively, I have come across 2 threads on Stack Overflow that do not provide a solution. Most of the available ...

Having difficulty sending a value with %45 to a REST API

Currently, I'm encountering an issue within my ASP.NET MVC 5 application. The problem arises when I send the following JSON data to a third-party API, which includes a password field: "{\"operation\":{\"Details\":{\"RESOURCE ...

Is there a way to target a child element for hover effect in CSS without affecting the parent element?

Is it feasible to hover over a nested child element without activating a hover effect on the parent element? In the demonstration below, you'll notice that even when hovering over the child, the hover effect on the parent is still in place. I am int ...

Executing a custom object function in AngularJS by using the ng-click directive

As I navigate my way through AngularJS, I find myself grappling with the concept of calling a custom method of an object and wonder if there's a simpler approach: https://jsfiddle.net/f4ew9csr/3/ <div ng-app="myApp" ng-controller="myCtrl as myCtr ...

Ways to pinpoint a particular division and switch its class on and off?

Consider this scenario, where a menu is presented: function toggleHiddenContent(tabClass) { let t = document.querySelectorAll(tabClass); for(var i = 0; i<t.length; i++) { t[i].classList.toggle="visible-class"; } } .hidden-conten ...

The Quickest Way to Retrieve Attribute Values in JavaScript

I'm trying to access a specific attribute called "data-price". Any tips on how I can retrieve the value of this attribute using this syntax: Preferred Syntax div[0].id: 48ms // appears to be the quickest method Alternative Syntax - Less Efficient ...

The correct way to extract a jwt token from headers and integrate it into an express application

After successfully implementing both the frontend and backend in express.js with authentication and authorization using JWT, I have confirmed that the JWT token is being properly set upon login. You can see the auth-token key in the image below: https://i ...

Put a watch on a variable as soon as it is set

When initializing a variable, I want to use the $watch function in Angular without it automatically initializing right away. Is there a way to accomplish this? $watch $scope.$watch(function () { return $scope.character.level; }, function (ne ...

Double dragenter events triggered before dragleave in HTML5 drag and drop functionality

Currently, I'm researching HTML5 Drag and Drop functionality by using this resource. However, I've encountered an issue with the dragenter event that seems to fire twice for child elements before the dragleave event. Because of this, the dashed b ...

"Enhance your online shopping experience with the dynamic 'Add to Cart' feature integrated into

I recently discovered DataTables and found it to be incredibly helpful with its built-in pagination and item display options. However, I encountered a challenge when trying to add a "Add to Cart" button at the end of the table. My goal is to use AJAX to ad ...

Tips for setting a checkbox as checked by default using AngularJS

I would like the checkbox to be checked by default. HTML : <div class="form-group col-sm-6" ng-class="{ 'has-error': pForm.caddress.$dirty && pForm.caddress.$error.required }"> <label class="contro ...

Strange behavior observed in fading slides using jQuery

I have been experimenting with jQuery to create a slide feature. However, I am encountering an issue where the next slide fades in before the previous one completely fades out when I click the next arrow. Does anyone know how to fix this problem? <ht ...