Skip to content
Advertisement

How to replicate jquery animation sequence in vanilla js/css

As the title says, I would like to replicate the animation bellow. the jquery API https://api.jquery.com/toggle/ decibels this default behavior as so:

easing (default: swing)
Type: String
A string indicating which easing function to use for the transition.

but I don’t understand how the transition works. I have tried changing the opacity, translating the element, ect, but obviously no luck. If it is impossible to do this in a simple way without jquery, an answer for the transition effect without the toggle function is also acceptable (but not hide() and show() as I have already tried those and couldn’t get it to work properly). And yes, I would prefer a swing transition if possible. any help is appreciated.

document.addEventListener('click', ()=>{
$('#elem').toggle('.hide');
});
.hide{
display:none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id='elem' class= 'hide'>
easing text transion
</div>

Advertisement

Answer

I donĀ“t know if I understood your question correctly but you want

document.addEventListener('click', ()=>{
$('#elem').toggle('.hide');
});

in normal JS?

You have two options: set an data attribute to #elem or you check if #elem has the class .hide. But its easier to just add the css to the element

With data attribute:

<div id='elem' data-status='inv' class='hide'>
easing text transion
</div>
let toggleFunction = function() {
  let elem = document.querySelector('#elem');
  if (elem.dataset.status == "inv") {
    elem.className = "";
    elem.dataset.status = "vis";
  } else if (elem.dataset.status == "vis") {
    elem.className = "hide";
    elem.dataset.status = "inv";
  }
}

document.addEventListener('click', toggleFunction);

Or with css:

<div id='elem' style='display: none;'>
easing text transion
</div>
let toggleFunction = function() {
  let elem = document.querySelector('#elem');
  if (elem.style.display == 'none') {
    elem.style.display = 'inherit';
  } else {
    elem.style.display = 'none';
  }
}

document.addEventListener('click', toggleFunction);

If you still want the animation:

<div id='elem' style='height: 0px;'>
easing text transion
</div>
#elem {
  transition: 1s ease-in-out all;
  overflow-y: hidden;
}
let toggleFunction = function() {
  let elem = document.querySelector('#elem');
  if (elem.style.height == '0px') {
    elem.style.height = '18px';
  } else {
    elem.style.height = '0px';
  }
}

document.addEventListener('click', toggleFunction);

I hope I could help

Advertisement