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

Having trouble properly wrapping divs using nextUntil() method

I am facing an issue with wrapping elements in HTML. The code snippet I have tried is not giving me the desired result. $('.cards .card-image').each(function() { $(this).nextUntil(".card-description").addBack().wrapAll("<div class='c ...

FadeToggle is a jQuery function that allows you to toggle the visibility of an

I'm struggling with creating a dynamic question and answer system on my website. I want the answers to fade in when a user clicks on a specific question, and then fade out when another question is clicked. I was able to achieve this for one paragraph ...

Content towering over the footer

Can anyone help me figure out how to create a footer that appears behind the content when you scroll towards the end of a website? I've tried looking for tutorials online, but haven't found exactly what I'm looking for. Most of what I'v ...

The issue arises when d3.scaleLinear returns NaN upon the second invocation

My journey with d3.js is just beginning and I'm taking it slow. Currently, I'm focused on creating a bar chart where data is loaded from a json file. When I click on the bars, the data changes to another column in the json. This is how my json f ...

The Image component in a test within Next.js was not wrapped in an act(...) during an update

After setting up a basic NextJS app with create-next-app and integrating Jest for testing, I encountered an error message stating "An update to Image inside a test was not wrapped in act(...)". The issue seems to be related to the Image component in NextJS ...

Animate the sliding of a div from the right side to the left side with the animate

I am interested in implementing an animation effect where a div with the class '.whole' slides from right to left. This can be achieved using jQuery: $('#menu').click(function() { $('.whole').toggleClass('r2' ...

What are some ways to troubleshoot the UI of a Nativescript app?

As a newcomer to NativeScript technology, I often encounter challenges while developing applications. Whether it's troubleshooting why a textview is not displaying properly, identifying layout overlaps, or detecting other distortions in the UI, debugg ...

Easy steps to dynamically add buttons to a div

I need help with a JavaScript problem. I have an array of text that generates buttons and I want to add these generated buttons to a specific div element instead of the body. <script> //let list = ["A","B","C"]; let list = JSON.p ...

Experiencing a blank page error when trying to render a partial view using Angular.js

Can someone assist me? I am encountering an issue where the partial view is not rendering properly using ui-router in Angular.js. Below is my code snippet. <!DOCTYPE html> <html lang="en" ng-app="Spesh"> <head> <meta charset="utf- ...

Any tips for filtering an array within an array of objects using the filter method?

I have an array of products and models that I am currently filtering based on 'id' and 'category'. var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.products = [{ 'id': 1, ...

Utilize the event bus by calling `this.$root.$emit` command

I recently implemented a basic Event bus in my application to dynamically change styles on a page, and it's functioning correctly. The event bus is triggered using the $emit and $on methods as shown below: EventBus.$on and EventBus.$emit('call ...

I am unable to pass a variable through a callback, and I cannot assign a promise to a

Currently, I am facing a challenge with my code where I need to loop through a hard-coded data set to determine the distance from a user-entered location using Google's web API. The issue lies in passing an ID variable down through the code so that I ...

Having trouble running tests on the Express.js server

I'm struggling to run basic tests on my expressjs server and close it immediately. I have exported the server as a promise, but can't seem to figure out how to achieve this. Below is the code for my server file : index.js const config = require( ...

Testing Restful API Endpoints and Code Coverage with Node.js using Mocha

My time in Istanbul has been delightful, and I've been dabbling in different Node.js coverage libraries. However, I'm facing a challenge. Most of my unit tests involve making HTTP calls to my API, like this: it('should update the custom ...

Unable to append Jquery attribute to a div component

My code snippet is creating a div with specific classes and elements: '<div class="ctrl-info-panel col-md-12 col-centered">'+ '<h2>You do not have any projects created at the moment.</h2>'+ '<div id="t ...

Utilizing data attributes for storing and selecting dual prices on an option

I need help creating a form with options that have two potential values. The user will first choose between "Low Price" (lp) or "High Price" (hp), and then select either Type 1 or Type 2, both of which have data attributes for "hp" and "lp". My goal is to ...

Using Vue.js along with vuex and axios allows for data retrieval only upon the second load

After creating a Vue.js app with vuex as a central store and using axios for basic API calls, I implemented the following store action: loadConstituencyByAreaCodeAndParliament({commit}, {parliament_id, area_code}) { axios.get('/cc-api/area-code/ ...

Unable to utilize ES6 syntax for injecting a service

I am encountering some issues while trying to implement a service into a controller using ES6 syntax. CategoriesService.js export default class CategoriesService { constructor() { this.getCategories = function ($q) { var deferred ...

The reason for setting a variable as void 0 in JavaScript

Currently, I am delving into the libraries referenced in this particular article as well as other sources. There are some truly mind-boggling concepts contained within these resources, one of which is highlighted by the following line: var cb = void 0; I ...

An issue occurred while calling the Selenium web driver: the driver.get() function couldn't access the attribute "href" of the linked_url, resulting in a stale element reference

Currently, I am utilizing Python with Selenium to work on extracting links from Google search results. After successfully accomplishing this task, I am now attempting to navigate through these links one by one using a for loop and the driver.get() method: ...