jQuery animation not executing as expected due to transition issues

I'm looking to create a cool effect where the previous quote disappears and a new one appears when I click on a button, all with a smooth transition effect.

In my attempt below using jQuery .animate and opacity property, I'm struggling to make it work as intended. It just inserts the new quote without any animation effects.

$(function() {

  $('.btn').on('click', function() {
    var letters = '0123456789ABCDEF';
    var $body = $('body');
    var $h1 = $('h1');
    var $innerhtml = $('.innerhtml');
    var color = '#';
    for (var i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    $body.css('background', color);
    $h1.css('color', color);
    $innerhtml.css('color', color);

    var link = 'https://gist.githubusercontent.com/rat395/9de1f8ad52f53170f90d9d8a204ee9ad/raw/e3ba3cf835cba8ecf8fa8da1e513bb40059f9355/quotes.json';
  
    $.getJSON(link, function(data) {

      var random = data[Math.floor((Math.random() * data.length) + 1)];
      $innerhtml.animate({ //This part is causing issues, not working properly
          opacity: 0
        }, 500,
        function() {
          $(this).animate({
            opacity: 1
          }, 500);
          $(this).html('<p>"' + random[0] + '"</p>' + '<br>' + random[1]);
        });
    })
  });

});
body {
  transition: all ease-in-out 1.5s;
}

.innerhtml {
  transition: all ease-in-out 1.5s;
}

.flex {
  margin-top: 100px;
  display: flex;
  height: 300px;
  justify-content: center;
  align-items: center;
}

.wrapper {
  border-radius: 5px;
  padding: 20px;
  background: white;
  width: 50%;
}

.text-in {
  display: flex;
  justify-content: center;
}

.buttons {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
}

.btn {
  height: 40px; 
}

.innerhtml {
  text-align: center;
  margin-top: 20px;
  margin-bottom: 30px;
  line-height: 30px;
  font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flex">
  <div class="wrapper">
    <div class="innerhtml"></div>
    <div class="buttons">

      <button class="btn btn-default off"><span class="glyphicon glyphicon-off"</span></button>
      <button class="btn btn-default quote">New quote</button>
      
    
    </div>
  </div>
</div>

Answer №1

Simply update

.innerhtml {
  transition: all ease-in-out 1.5s;
}

with

.innerhtml {
  transition: color ease-in-out 1.5s;
}

for instance: https://jsfiddle.net/edxn2frq/

Answer №2

Implemented .toggleClass() on the body and .innerhtml

$body.css('background', color).toggleClass('act die');
$innerhtml.css('color', color).toggleClass('act die');

Then established the definitions for the two classes: .act and .die as shown below:

 body.act {
    background: currentColor;
    transition: all ease-in-out 1.5s;
  }
  body.die {
    background: currentColor;
    transition: all ease-in-out 1.5s;
  }

.innerhtml.act {
  text-align: center;
  padding: 10px;
  margin: 0 auto;
  line-height: 20px;
  font-size: 16px;
  transition: all linear 2s;
}
.innerhtml.die {
  line-height: 0;
  font-size: 0;
  transition: all linear 1s;
}

The transition property requires the actual properties to be within the same ruleset so it can determine what to animate. To accommodate a variable color property, background:currentColor was used. Some adjustments in the basic layout were made to ensure smooth transitions without any abrupt jumps.

SNIPPET

$(function() {

  $('.btn').on('click', function() {
    var letters = '0123456789ABCDEF';
    var $body = $('body');
    var $innerhtml = $('.innerhtml');
    var color = '#';
    var i;
    for (i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    $body.css('background', color).toggleClass('act die');
    $innerhtml.css('color', color).toggleClass('act die');
    var link = 'https://gist.githubusercontent.com/rat395/9de1f8ad52f53170f90d9d8a204ee9ad/raw/e3ba3cf835cba8ecf8fa8da1e513bb40059f9355/quotes.json';

    $.getJSON(link, function(data) {

      var random = data[Math.floor((Math.random() * data.length) + 1)];
      $innerhtml.animate({ //Here is the problem, its not working
          opacity: 0
        }, 500,
        function() {
          $(this).animate({
            opacity: 1
          }, 1000);
          $(this).html('<p>"' + random[0] + '"</p>' + random[1]);
        });
    });
  });

});
body.act {
  background: curentColor;
  transition: all ease-in-out 2s;
}
body.die {
  background: curentColor;
  transition: all ease-in-out 2s;
}
.wrapper {
  border-radius: 5px;
  padding: 20px;
  background: white;
  width: 50%;
  min-height: 50vh;
  margin: 0 auto;
}
.buttons {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.btn {
  height: 40px;
}
.innerhtml.act {
  text-align: center;
  margin: 20% auto 5%;
  line-height: 20px;
  font-size: 16px;
  transition: all linear 2s;
}
.innerhtml.die {
  line-height: 0;
  font-size: 0;
  transition: all lineaer 1s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body class='act'>
  <div class="wrapper">
    <div class="innerhtml die"></div>
  </div>

  <div class="buttons">


    <button class="btn btn-default quote">New quote</button>

  </div>
</body>

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

Incorporating Chip into a Material-UI DataGrid column

I'm having trouble displaying data of a specific column inside a chip. I attempted to use the Chip component in my code: StackBlitz Demo Web Link: Live Demo I tried to incorporate it using: import Chip from '@mui/material/Chip'; but c ...

Dealing with a 404 Error in Node.js and Express Routing

After successfully creating a Node/Express app tutorial earlier, I encountered issues when trying to replicate it for a new project on both Ubuntu and Windows. The basic routing consistently fails and results in 404 errors, which is incredibly frustrating! ...

What causes the "v-col" width to suddenly alter after adding the "bg-red rounded" class?

I'm struggling to organize the data into blocks using Vuetify. When I apply the "bg-red rounded" class to the "v-col", it alters the width of the column, resulting in an undesired grid structure. Here is the template section of my Vue file. Some data ...

Tips for preventing duplicate Java Script code within if statements

In my function, there are various statements to check the visibility of fields: isFieldVisible(node: any, field: DocumentField): boolean { if (field.tag === 'ADDR_KOMU') { let field = this.dfs_look(node.children, 'ADDR_A ...

Ensure that the token remains current with each axios operation

I need to access an Express REST API that demands a valid json web token for certain routes. In order to include the token from localstorage every time I needed, I had to create an "Axios config file". My http.js file includes the code below: import Vue ...

How can I maintain focus selection while replacing HTML with text in a contenteditable div without losing it?

When working with a div tag that needs to be editable, the goal is to prevent users from entering any HTML into the tag. However, despite efforts to restrict input, when users copy and paste content, it often includes unwanted tags. To address this issue, ...

Having trouble with Vue.js implementation of Bootstrap tab navigation?

I am currently working on a vue.js application that consists of 2 routed components. I recently attempted to integrate a bootstrap tab navigation into the first component, but unfortunately, the tab contents are not being properly displayed. <templat ...

Using a combination of Ajax and jQuery in Rails4 to showcase a date in the %m/%d/%yyyy format ultimately results in a split

Recently, I encountered an issue with an ajax call that retrieves a date from the database. The date is stored as a double in the database and then converted to a string. I used Date.parse to change it into a date object and used strftime to format it. How ...

Steps to prevent submission of input field until all necessary fields and checkboxes are filled, disabled the submit button

Check out my basic web application on this sandbox link: codesandbox.io/s/eager-kalam-v1lpg I need assistance with how to prevent the submit button from being enabled until all required fields and checkboxes are filled in. I am fairly new to working with ...

What is the best way to center a rotated element and have it aligned to the top?

* { box-sizing: border-box; } body { font-family: 'Poppins', sans-serif; margin: 0px; } .we-adopt { background-color: #8a8484; color: #ffffff; padding: 88px 0px; height: 100px; } .we-adopt-list span { display: i ...

Troubleshooting issue with changing class based on input values

It appears that there is an issue with the functionality when switching values on page load. Initially, I was able to make it work for a single switch, but now that there are multiple switches on the page, toggling affects all of them. How can I modify it ...

Fixing the issue with animated scrolling in React Native's Flatlist component

I attempted to customize the default refresh indicator for a Flatlist in React Native. My goal was to create something similar to Snapchat, Instagram, or the default iOS refresh indicator instead of the unattractive Android indicator. This is what I tried: ...

Adjustable Text Size with HTML5 and CSS3

Looking to enhance the accessibility of a website by implementing text size adjustment buttons ' A A A ' using just HTML5 and CSS3. Avoiding the use of jQuery or Javascript for this task. Inspiration drawn from this link. Appreciate any assistan ...

What is the best way to retrieve the value of the "Observer" object?

I am a user of Vue.js and I have the following data in this.suspendedReserveMemo: this.suspendedReserveMemo [__ob__: Observer]650: "memo3"651: "memo4"652: ""653: ""654: ""655: ""656: ""657: ""658: ""659: ""660:""661: ""662: ""length: 663__ob__: Observer {v ...

Choosing the right CSS selectors for elements within other elements

I'm trying to add a stagger effect to the fade-in animations of images within a gallery. After looking over my code, I believe the issue lies in how I am setting the animation-delay in the CSS selector. I am not sure if SCSS is supported in this snipp ...

What is the reason for making the position of bg-container absolute?

Discover more about the "position: absolute" attribute Remove the position property for troubleshooting After testing this page in Chrome, I encountered a confusion regarding the usage of the position property within the bg-container. To my surprise, del ...

[Vue alert]: Issue in created function: "TypeError: Unable to assign value to undefined property"

I'm currently in the process of developing a VueJS application where I have implemented a child component called Child.vue that receives data from its parent. Child.vue export default{ props:['info'], data: function(){ ...

Unneeded return is necessary when utilizing recursion and restarting the application

Recently, I successfully recreated the 2048 game in Java, which was a pleasant surprise to me as I didn't expect to create something this "advanced." During the game, when tiles are moved, a new square/tile/number needs to be generated. To find an av ...

Automatic keyboard suggestions not working for HTML search input using Ajax

I am currently working on a PHP web application that uses a MySql database. I have implemented a search suggestion box using ajax. The issue I am facing is that the suggestions can be selected with the mouse and auto-completed, but not when using the keybo ...

Create visual representations using the data displayed in charts generated by Chart JS

Good evening. I am currently utilizing Chart JS in my project to visualize the total count per column in a bar graph. My backend framework is Laravel, and I pass the data from the controller using the variable $datacount. This snippet shows the query in ...