Guide for implementing smooth fade in and out effect for toggling text with button click

I have this code snippet that toggles text on button click:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function toggleText(){
    if ($("#txt-1").css("display") != "none") {
        $("#txt-1").css("display", "none");
        $("#txt-2").css("display", "block");
        $("#txt-3").css("display", "none");
    } else if ($("#txt-2").css("display") != "none") {
        $("#txt-1").css("display", "none");
        $("#txt-2").css("display", "none");
        $("#txt-3").css("display", "block");
    } else {
        $("#txt-1").css("display", "block");
        $("#txt-2").css("display", "none");
        $("#txt-3").css("display", "none");
    }
};
</script>
</head>
<body>

<button onclick="toggleText()">Toggle</button>

<p id="txt-1">Hello</p>
<p id="txt-2" style="display: none;">How are you?</p>
<p id="txt-3" style="display: none;">See you soon!</p>

</body>
</html>

Currently, there is no smooth transition between the text changes when the button is clicked. I'm unsure whether to use CSS or jQuery for this effect.

I attempted to create a CSS class named smooth-fade:

.smooth-fade {
    -webkit-animation: fadeIn 1s;
    animation: fadeIn 1s;
}

I then applied this class to all p tags but it didn't produce the desired result. What would be the best approach to achieve a smooth transition in this scenario?

Answer №1

If you're looking to achieve this effect, consider utilizing jQuery:

  $( "#txt-1" ).fadeOut( "slow", function() {
     $("#txt-2").fadeIn();
  });

Start by fading out the desired elements, then trigger the callback function to fade in the others.

function toggleText(){
  $( "#txt-1" ).fadeOut( "slow", function() {
     $("#txt-2").fadeIn();
  });
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<button onclick="toggleText()">Toggle</button>

<p id="txt-1">Hello</p>
<p id="txt-2" style="display: none;">How are you?</p>

Answer №2

Your coding skills could benefit from a more organized approach. Consider the following steps for better reusability:

  1. Encapsulate all content within a wrapper element.
  2. Apply the .active class to identify visible elements.
  3. Utilize the custom jQuery function nextOrFirst().

function toggleText() {
  var $active = $('.active');
  $active.removeClass('active').fadeOut(500, function() {
    $active.nextOrFirst().fadeIn().addClass('active');
  });
};

// Adapted 'Next or first' function from: https://stackoverflow.com/a/15959855/559079
$.fn.nextOrFirst = function(selector) {
  var next = this.next(selector);
  return (next.length) ? next : this.prevAll(selector).last();
};

$.fn.prevOrLast = function(selector) {
  var prev = this.prev(selector);
  return (prev.length) ? prev : this.nextAll(selector).last();
};
<!DOCTYPE html>
<html>

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

<body>

  <button onclick="toggleText()">Toggle</button>

  <div class="wrapper">
    <p id="txt-1" class="active">Hello</p>
    <p id="txt-2" style="display: none;">How are you?</p>
    <p id="txt-3" style="display: none;">See you soon!</p>
  </div>

</body>

</html>

Answer №3

Your code needs a bit of organization.. It's recommended to use addClass or classList.add methods when changing styles of an element with JavaScript instead of directly modifying style properties.

Check out this example =>

HTML

  <button onclick="toggleText()">Toggle</button>
  <p id="txt" class="fader">
    Hello
  </p>

CSS

.fader {
  opacity: 1;
  visibility: visible;
  transition: all  1s ease-in-out;
}
.fade-in {
  opacity: 0;
}

JS

  let textArray = ["Hello", "How are you ? ", "See you soon ! "]
  let id = 1;
  const text = document.querySelector('#txt');
  
  function toggleText() {
    if (id > textArray.length - 1) {
      id = 0;
    }
    text.classList.add('fade-in');
    setTimeout(function () {
      text.innerText = textArray[id]
      text.classList.remove('fade-in')
      id++
    }, 1000)
  };

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

How can Vue be used to dynamically change the input type on focus?

What Vue method do you recommend for changing an input element's type on focus? e.g. onfocus="this.type = 'date'" I am specifically looking to switch the input type from text to date in order to utilize the placeholder property. ...

Managing the AJAX response from a remote CGI script

I'm currently working on a project that involves handling the response of a CGI script located on a remote machine within a PHP generated HTML page on an apache server. The challenge I am facing relates to user authentication and account creation for ...

Adjust the size of the font in an image created from text using a dynamic function

Creating stencil art is a fascinating process. I have successfully converted text to images, with each text box generating a separate line of the image on the browser. However, I am facing a challenge in implementing three different font sizes for each con ...

What's the best way to place the text or operator from a button into an input field?

Hello, I am currently working on developing a calculator. However, I have encountered an issue where clicking on operator buttons such as +, -, /, *, and the dot button does not add them to my input field. Additionally, when these buttons are clicked, the ...

Struggling to make jQuery code function properly in Wordpress, despite attempting to use noConflict

I have created a custom image grid gallery in WordPress using HTML and CSS, complete with popups and sliders. I had to code it myself because I couldn't find a suitable plugin that matched my design preferences. I have tested the functionality on my ...

Vue: Conditionally display a division depending on v-if, excluding cases where the div returns null

Within my HTML, I have implemented conditional rendering using v-if <div v-if="showdiv"> <p>Content 1 appears here</p> </div> <div v-if="!showdiv"> <p>Content 2 appears here</p> < ...

Can someone explain the significance of this CSS code (specifically regarding font-size division)?

Forgive me, but I'm struggling to come up with a more suitable title for my query. I've come across this piece of code font: 9pt/18px Tahoma; Can anyone shed some light on what it signifies? ...

Hacking through external script injections into the browser

Curious about how certain software or programs are able to inject html,css,js into a web browser without the need for installing any extensions. Every time I open Chrome or Firefox, I'm bombarded with ads on popular sites like Google homepage, Faceboo ...

Is it possible to implement a real-time data update feature in a Gridview using ajax in C#

I've been working on updating my gridview automatically with the latest data using ajax in c#. I attempted to create an ajax post that calls my c# method, fetches the updated data, and then binds it to the gridview. However, I'm facing an issue w ...

The Cross-Origin Resource Sharing request using the PUT method has been denied due to restrictions set by the

I am currently using CORS requests to communicate between my client and server located on different domains. I have configured my Apache HTTP server to use SSL in the following manner: // Utilizing AJAX withCredentials=true (sending cookies, allowing SSL ...

Identify if a process operates synchronously or asynchronously

Can you identify in node.js, with the help of a function, if a method is synchronous or asynchronous? I am interested in creating a function that achieves the following: function isSynchronous(methodName) { //check if the method is synchronous, then ...

Unable to invoke any fineUploader functions within a callback function

My autoUpload is currently set to false because I prefer uploading the images manually to my backend. To achieve this, I need the file object first. In the onSubmitted event callbacks, I am attempting to pass the image's ID to the getFile method to re ...

Encountering an issue with importing createSagaMiddleware from 'redux-saga' while working on my create-react-app project

Within my create-react-app, I have the following import: import createSagaMiddleware from 'redux-saga'; However, there seems to be an issue with importing createSagaMiddleware in my system. The versions I am currently using are: node 12.13.0 n ...

Is it feasible to incorporate one iOS app within another iOS app through in-app purchasing or subscription?

Simply put, we are creating interactive content in Flash that we want to distribute through an iOS app either by in-app purchase or subscription. In our testing, we have found that Flash can produce standalone iOS apps that work well for our needs. Instea ...

Discrepancies in Span Element Behavior Between Firefox and Chrome

Seeking assistance with a tooltip feature that reveals extra information when a user hovers over a span. The issue arises when the span is split across two lines, causing the extra information to appear in different positions on Firefox and Chrome browsers ...

An animation in CSS where an element moves off the screen to the right in absolute position and then returns from the

I am currently working on a website featuring moving clouds traveling across the screen from left to right. Although I have successfully implemented the animation for the clouds, there is one specific issue that has me stuck. My goal is to display some of ...

What is the best way to switch out the characters 'a' and 'b' in a given string?

Let's say we have the following text. Lorem ipsum dolor sit amet The revised text should look like this: merol merol merol merol Is there a predefined function in JavaScript that can help us replace characters like this within a string? ...

Establishing headers in hapi.js

Seeking guidance on setting up custom variables for individual routes in hapi.js. How can I configure these variables to be accessible on 'onPreHandler'? Additionally, looking for a way to include headers right before calling reply.continue. Any ...

Input form with multiple fields. Automatically display or hide labels based on whether each field is populated or empty

I am attempting to create a form where the placeholders move to the top of the input when it is focused or filled. However, I have encountered an issue with having multiple inputs on the same page. Currently, my JavaScript code affects all inputs on the pa ...

Rest assured, with Ajax Security, your protection is in good

I am currently developing a browser game that heavily utilizes AJAX instead of page refreshes. The combination of PHP and JavaScript is being employed for this project. However, during the course of my work, I became aware of the potential security vulnera ...