Skip to content
Advertisement

How can i make div content appear with animation when clicking a button that injects HTML?

I am currently learning on my own some CSS & JS and i’m stuck on a part i really want to work on but have trouble finding the right answers online as there seem to be a tons of methods yet i couldn’t make any of them work.

Here is a snippet of what i have in mind :

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

function animation() {
  let content = document.getElementById("content");
  content.innerHTML = "";
  content.innerHTML = htmlcontent;
}
#content p {
  font-size: 100px;
}
<div id="content">
  <p>
  Hello world!
  </p>
</div>
<button onclick="animation()">
  Click here
</button>

The idea is that when i click on the button, old content gets replaced by new HTML content and i want that new content to fade in from the right (a transition) every time i click the button.

I’m sorry if my question is bad/weird, english isn’t my primary language and i have no one else to ask at the moment. Thank you for your patience.

Advertisement

Answer

You could just make a CSS animation and play that whenever you click the button.

let htmlcontent = `<p>It's me again!</p>`;
let content = document.getElementById("content");

function animation() {
  content.innerHTML = htmlcontent;
  
  content.classList.add("animate");
  
  setTimeout(function() {
    content.classList.remove("animate");
  }, 500); // 500 is the same time as the CSS animation
}
#content p {
  font-size: 100px;
}

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

@keyframes fadeIn {
  from {
    transform: translateX(250px);
    opacity: 0;
  }
  to {
    transform: translateX(0px);
    opacity: 1;
  }
}
<div id="content">
  <p>
  Hello world!
  </p>
</div>
<button onclick="animation()">
  Click here
</button>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement