È possibile attivare le transizioni CSS anche senza utilizzare dinamicamente le classi. Infatti è sufficiente modificare gli stili CSS di un elemento tramite JavaScript.
Partiamo dai seguenti stili CSS:
#test {
width: 150px;
height: 150px;
background-color: green;
transition: all 500ms ease-out;
}
Quindi definiamo una funzione di utility per gli stili CSS:
function css( element, styles ) {
if( typeof styles === "object" && element !== null ) {
for( var prop in styles ) {
element.style[prop] = styles[prop];
}
}
}
Esempio pratico:
document.addEventListener( "DOMContentLoaded", function() {
var test = document.getElementById( "test" );
test.addEventListener( "click", function() {
css( this, {
opacity: 0,
width: "0px",
height: "0px"
});
}, false);
});
Demo
See the Pen JavaScript: hide elements with CSS transitions by Gabriele Romanato (@gabrieleromanato) on CodePen.