Show with animation the content added with JavaScript

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 107

Show with animation the content added with JavaScript

The idea is that when i click on a button, old content gets replaced by new HTML content added with javascript.
I want that new content to appear with animation; to fade in from the right (a css transition) every time i click the button.

Here is a snippet of what i have in mind, but I don't know how to add with animation (the transition):

Code: Select all

<style>
#pag_cnt p {
  font-size: 40px;
}
</style>

<div id='pag_cnt'>
  <p>Hello world!</p>
</div>
<button onclick='add_anim()'>Click here</button>

<script>
let new_cnt = `<p>It's me again!</p>`;

function add_anim() {
  let pag_cnt = document.getElementById('pag_cnt');
  pag_cnt.innerHTML = new_cnt;
}
</script>

Admin Posts: 805
To trigger a CSS transition, change the CSS state after you inserted the HTML. You can do this by changing a class (on the container or an inserted element).
Then make a CSS animation and play that whenever you click the button.

Study and test the following code:

Code: Select all

<style>
#pag_cnt p {
  font-size: 40px;
}

.add_anim {
  animation: fadeIn 500ms ease-out backwards;
}

@keyframes fadeIn {
  from {
    transform: translateX(280px);
    opacity: 0;
  }
  to {
    transform: translateX(0px);
    opacity: 1;
  }
}
</style>

<div id='pag_cnt'>
  <p>Hello world!</p>
</div>
<button onclick='add_anim()'>Click here</button>

<script>
let new_cnt = `<p>It's me again!</p>`;
let pag_cnt = document.getElementById('pag_cnt');

function add_anim() {
  pag_cnt.innerHTML = new_cnt;
  
  pag_cnt.classList.add('add_anim');
  
  setTimeout(function() {
    pag_cnt.classList.remove('add_anim');
  }, 500); // 500 is the same time as the CSS animation
}
</script>
- Demo:

Hello world!


Similar Topics