Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animation: Fade in when creating an element and fade out when deleting

I'm having trouble with the following situation.

I have a button which acts like a normal toggle. When I click on the "Animate" button, I want the <p>This is new Div</p> to fade in when I again click on the Animate button, this <p> should fade out.

How can I achieve this?

const main = document.getElementById('main');
const btn = document.getElementById('btn');

let show = false;
btn.addEventListener('click', () => {
  if(show) {
    const newDiv = document.getElementById("new-div");
    newDiv.remove();
    show = false;
  } else {
    const newDiv = document.createElement('div');
    newDiv.id = "new-div";
    newDiv.innerHTML = "<p>This is new Div</p>";
    main.appendChild(newDiv);
    show = true;
  }
})
#new-div {
  transition: all 2s ease-in-out;
}
<div id="main">
  <button id="btn">Animate</button>
</div>

I'm actually building a gallary layout app, which requires to fade in when clicked on a image + show in full screen, then fade out to its original position when clicked. Since there will be many images, I want to use JS to dynamically work on this.

And the biggest hurdle so far is to implement fade-out, because the element is being deleted.

like image 627
cdadityang Avatar asked Jan 02 '26 02:01

cdadityang


1 Answers

Based on your information I've made a refined version, pls see fiddle and code below: https://jsfiddle.net/Kenvdb/8nsbp16o/

JavaScript:

const main = document.getElementById('main');
const btn = document.getElementById('btn');

let toggledDiv = null;

btn.addEventListener('click', () => {
  if (!toggledDiv) {
    show();
  } else {
    hide();
  }
})

const show = () => {
  toggledDiv = document.createElement('div');
  toggledDiv.id = "content";
  toggledDiv.style.opacity = "1";
  toggledDiv.innerHTML = "<p>This is new Div</p>";

  main.appendChild(toggledDiv);
}

const hide = () => {
  toggledDiv.style.animation = "fade-out 0.5s ease-in";
  toggledDiv.style.opacity = "0";
  toggledDiv.addEventListener('animationend', remove);
  toggledDiv.addEventListener('webkitAnimationEnd', remove);
}

const remove = () => {
  toggledDiv.remove();
  toggledDiv = null;
};

CSS:

#content {
  opacity: 0;
  animation: fade-in 0.5s ease-in;
}

@keyframes fade-in {
    0% { opacity: 0; }
    100% { opacity: 1; }
}

@keyframes fade-out {
    0% { opacity: 1; }
    100% { opacity: 0; }
}

HTML:

<div id="main">
  <button id="btn">Animate</button>
</div>
like image 99
KennyDope Avatar answered Jan 03 '26 16:01

KennyDope



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!