Toggle transform/opacity via transition
Toggle transform and opacity using transition by adding and removing specific class from the element using JS.
by Konstantin Rouda
HTML
<button id="toggle-btn">
Toggle class
</button>
<section class="container">
<div class="elem" id="elem"></div>
</section>
CSS
.container {
max-width: 70%;
padding: 2rem;
border: 1px solid;
overflow: hidden;
}
.elem {
width: 100%; height: 200px;
margin: 0 auto;
background: cornflowerblue;
opacity: 1;
transition: transform 1s ease-in-out, opacity .7s .1s ease-in-out;
}
.elem.is-open {
opacity: 0;
transform: translateY(120%);
}
JavaScript
;(function () {
"use strict";
const btn = document.getElementById("toggle-btn");
const elem = document.getElementById("elem");
btn.addEventListener("click", onBtnClick);
function onBtnClick (e) {
elem.classList.toggle("is-open");
/*
// if toggle doesn't supported this can be used instead
const currentMethod = elem.classList.contains("is-open") ? "remove" : "add";
elem.classList[currentMethod]("is-open");
*/
};
})();