Home > Net >  Animate a tag when display after clicking
Animate a tag when display after clicking

Time:11-08

How to give an animation to the div tag when it is displayed (click on button)?

function toggle_div_fun(id) { 
  var divelement = document.getElementById(id); 
  if (divelement.style.display == 'flex') divelement.style.display = 'none'; 
  else divelement.style.display = 'flex';
}
<button  onclick="toggle_div_fun('sectiontohide');">Click here</button>
<div id="sectiontohide">This is the div to hide</div>

CodePudding user response:

// I'm going to use jQuery since it has the toggle animation for this
function toggle_div_fun(id, usejQuery = true) {
  if (usejQuery) {
    const divelement = $(id);
    // 200 is ms it takes to complete animation
    divelement.toggle(200)
    return;
  }
  document.getElementById("sectiontohideNojQuery").classList.toggle("hideDiv");

}
.showDiv {
  opacity: 1;
  animation: showMe 1s forwards;
}

.hideDiv {
  animation: hideMe 1s forwards;
}

@keyframes showMe {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@keyframes hideMe {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<button  onclick="toggle_div_fun('#sectiontohide');">Click here</button>
<div id="sectiontohide">This is the div to hide</div>
<button  onclick="toggle_div_fun('#sectiontohideNojQuery', false);">Click here No JQuery</button>
<div  id="sectiontohideNojQuery">This is the div to hide not using jQuery</div>

CodePudding user response:

You can give this a style and then transition to the new style when you add a class. Here for example I transition the height and font size with css.

function toggle_div_fun(event) { 
  let animateMe = event.currentTarget.dataset.animatetarget;
  let divelement = document.getElementById(animateMe); 

  const isfoo = divelement.classList.contains("foo");
  // console.log(isfoo);
  divelement.classList.toggle("addedclass", isfoo);
  divelement.classList.toggle("foo", !isfoo);
}
let el = document.querySelector('.eco-btn')
  .addEventListener("click", toggle_div_fun);
.fun-target {
  overflow: hidden;
  background-color: #0000ff;
  color: #fff;
  display: flex;
  height: 0;
  padding: 0 2em;
  width: 100vw;
}

.fun-target {
  -webkit-transition: all .5s ease;
  -moz-transition: all .5s ease;
  transition: all 2s ease;
}

.fun-target.addedclass {
  height: auto;
  padding: 2em 1em;
  font-size: 3em;
  background-color: #DDffff;
  color: #0000FF;
}
<button  data-animatetarget='sectiontohide'>Click here</button>
<div id="sectiontohide" >This is the div to hide</div>

  • Related