CSS - Animate display none, block and opacity
Posted: 13 Jan 2015, 13:21
I have a Div and a Button that uses JavaScript to alternate the class of the Div to "hide" and "show". The "hide" class has "display:none;" to hide the Div (and opacity 0), and the "show" class has "display:block;" to show the Div (and opacity 1).
Is it possible to animate the display none /block and opacity using only CSS?
This is the code:
Is it possible to animate the display none /block and opacity using only CSS?
This is the code:
Code: Select all
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Title</title>
<style>
#cnt1 {
position: relative;
margin: 4px auto;
background:#eee;
}
#cnt1.hide {
opacity : 0;
display: none;
}
#cnt1.show {
opacity:1;
display: block;
width: 75%;
height: 150px;
}
</style>
</head>
<body>
<div id="cnt1" class="show">
<p>Content to be displayed</p>
<p>Other paragraph with content to be displayed</p>
</div>
<button id="btn1">Hide</button>
<script>
// get the htmll elements
var cnt1 = document.getElementById('cnt1');
var btn1 = document.getElementById('btn1');
// register click event to #btn1 that alternate class to #cnt1, and changes #btn1 text
btn1.addEventListener('click', function() {
if(cnt1.className == 'show') {
cnt1.className = 'hide';
btn1.innerHTML = 'Show'
}
else {
cnt1.className = 'show';
btn1.innerHTML = 'Hide';
}
});
</script>