Continuously update the content within a paragraph using jQuery

After searching for a jQuery animation that would constantly change text within a paragraph, I stumbled upon a solution at this link : Text changing with animation jquery. However, I encountered a challenge as I wanted to include a bootstrap button beneath the paragraph. The issue arises when the button starts moving up and down while the opacity is null.

var words = ["text1", "text2", "text3","text4","text5"];
var idx = 0;

$("#description").fadeOut("slow");

setInterval(function(){
    $("#description").stop().html(words[idx]).fadeIn("slow",function(){
        idx++;
        $("#description").delay(400).fadeOut("slow");
        if (idx == 5) {
            idx = 0;
        };
    });
},1800);
<p id="description"></p>
 <p>Hello world</p>

You can experience the issue on a fiddle here: https://jsfiddle.net/km19e3jf/2/

Answer №1

When using the fadeOut and fadeIn functions, the display property of the element is changed from block to hide, causing #description to completely lose its height upon calling fadeOut.

A different approach that doesn't require additional updates outside of the existing code can be implemented:

var content  = [ "content1", "content2", "content3", "content4", "content5" ];
var current = 0;

$("#description").fadeTo( 1, 0 );

setInterval( function(){
    $( "#description" ).stop().html( content[ current ] ).fadeTo( 500, 1, function(){
        current++;
        $( "#description" ).delay( 400 ).fadeTo( 500, 0 );
        if ( current == 5 ) {
            current = 0;
        };
    } );
}, 1800 );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
     <p id="description">text 1</p>
</div>

To avoid changing the display property and instead alter the opacity, consider using fadeTo in your script:

View the working example on this fiddle here.

Answer №2

To create a fixed height around your text, consider adding a container.

Using the fadeOut and fadeIn functions will toggle the display of elements between block and hidden (hide).

This movement affects the elements below it.

var text = ["text1", "text2", "text3","text4","text5"];
var index = 0;

$("#description").fadeOut("slow");

setInterval(function(){
    $("#description").stop().html(text[index]).fadeIn("slow",function(){
    index++;
        $("#description").delay(400).fadeOut("slow");
    if (index == 5) {
        index = 0;
    };
    });
},1800);
.container{
  height:25px;
}

#description{
  margin:0;
  padding:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<p id="description"></p>
</div>

<p>Hello world</p>

Answer №3

When applying the fadeOut function, it sets the element to display none after the animation, causing a noticeable jump. Instead of using fadeOut, opt for .css to adjust the opacity smoothly.

Try this code:

$("#description").delay(400).css({'opacity': 0});

To animate the transition, include transition-duration: 400ms; in your CSS for #description.

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 using debounce with $scope.$apply a logical choice?

In my experience, I have come across a method that claims to decrease the number of $digest loops by incorporating debouncing into the $scope.$apply process. It looks something like this: $scope.$apply = _.debounce($scope.$apply, 250); Is this approach v ...

Using Javascript, when the command key is pressed, open the link in a new window

Currently, I am working on a Javascript function that opens links in a new tab only when the "command" key is pressed on an Apple computer. Here is what I have so far: $(document).on('click','a[data-id]',function(e){ if(e.ctrlKey|| ...

What is the best method for establishing a page location during rendering/onload?

It seems like there is a JavaScript event happening here using the onload attribute. But for the life of me, I can't seem to crack this code. <body onload="moveToHere('reference')"> I'm stuck and could really use some assistance ...

Ways to improve the quality of a blurred photo

I've recently put together a test landing page using bootstrap: Upon visiting the site and viewing the iPhone screenshot, it's clear that the text on the screen is quite blurry. Interestingly, by simply resizing the browser window and then maxi ...

Transforming a string into JSON format for the purpose of implementing JSON Patch

I am encountering an issue while attempting to retrieve a request using postman for a JSON string in order to apply a JSON patch. Unfortunately, I am facing difficulties in converting the string to JSON once the data is posted through a variable. Each time ...

React: I am looking to incorporate two API calls within a single function

I am currently learning ReactJS and focusing on implementing pagination. My goal is to fetch page data from a server using an API, with Loopback being the tool for API integration. The initial setup involves displaying a list of 10 entries on the first pag ...

Image failing to appear in .php document

I am experiencing an issue with my basic webpage where images are not appearing when I link to them locally. Oddly enough, when using a full URL linking to an external site, the image displays perfectly fine. Here is the code snippet in question: <html ...

unable to submit form using angular and express

I am encountering an issue with a post request in AngularJS to express. The HTML form on the client side is defined as follows: <div ng-controller="LoginCtrl"> <form ng-submit="login()"> <div> <label>Username</lab ...

How to troubleshoot syntax errors when using the delete function in Three.js within Eclipse

When using the Javascript Library Three.js, it is important to note that the delete keyword can be used as an object property. While this is valid under ECMAScript 5 standards, Eclipse currently only supports ECMA 3. As stated in the Mozilla reference, re ...

How can I align a sub-submenu horizontally using CSS?

I've built a nested menu using the ul/li tags, and I'm looking to align the second and third sub-menus horizontally with the first submenu. Here is my current visual layout: , and this is what I want it to look like: CSS/HTML: body { back ...

transferring data from the interface to the processor

I'm encountering an issue with sending dropdown list values to a new page for display. When I try to load the page after selecting a building from the dropdown menu, I receive an error message. I'm unsure about what mistake I might be making. Be ...

Building a dynamic form in React: Fetching select data from an API, posting to another API, and automatically clearing fields upon submission

I am currently working on a form that utilizes a GET request to retrieve data from an API endpoint and then proceeds to make a POST request to another endpoint. Although I have been successful in achieving this function, I am facing challenges with reset ...

Error: The function registerUser from require(...) is not defined

I am facing an issue where I am trying to import the registerUser function inside router.post within the same file that houses its exported function (registerUser). However, when attempting to use it outside of this module, I receive the following error: ...

Retrieving HTML code as a variable using Python

I am attempting to output HTML code as a variable in my Python script, but it's not working properly. What could be causing this issue? Here is an example of my code: return render_template("dashboard.html", services = "<h1>Service 1</h1> ...

Issues with the directory for Chrome

Currently, I am utilizing jQuery and running an HTML file on my local machine without a server. Interestingly, the code works perfectly fine on Firefox but encounters issues on Chrome: $('#result').load('test.html'); It appears that t ...

Next.js - utilizing dynamic API routes within nested folders

Currently, I am working on developing a basic API that reads a local JSON file. My goal is to create a dynamic API that can adjust based on the specific calls it receives. Within my API folder structure, I have: api --book ---[id].js ----content -----[id ...

Using the Mongoose $or operator with a nested array in query conditions

Here are the schemas I am using: //ProjectModel const ProjectSchema: Schema = new Schema( owner: { type: Schema.Types.ObjectId, ref: "User" }, users: [{type: Schema.Types.ObjectId, ref: "ProjectUser", unique: true }] ); //Project Use ...

I'm looking for a way to display the value stored in a variable within an ejs template. Any suggestions

I am experiencing an issue with my ejs template that should greet the user by displaying their name when the page loads, but it is not showing anything. Here's a snippet of my template: <!DOCTYPE html> <html> <head> < ...

Utilizing the principles of object orientation in Javascript to enhance event management

After attempting to modularize my JavaScript and make it object oriented, I found myself struggling when dealing with components that have multiple instances. This is an example of how my code currently looks: The HTML file structure is as follows: & ...

Customizing a toggle checkbox in Bootstrap 5: A guide to personalization

I am attempting to modify a toggle switch in Bootstrap 5.2. <!DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8> <meta http-equiv="X-UA-Compatible" content="IE=edge> <meta name="viewport" content="wid ...