After researching HTML5 transitions and adapting some examples, I finally achieved the desired effect.
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 50px;
height: 50px;
}
div.myDiv {
position: absolute;
-webkit-transition-property: top, opacity;
-webkit-transition-duration: 1s, 1s;
-webkit-transition-timing-function:ease-in-out, ease-in-out;
-moz-transition-property: top, opacity;
-moz-transition-duration: 1s, 1s;
-moz-transition-timing-function:ease-in-out, ease-in-out;
-o-transition-property: top, opacity;
-o-transition-duration: 1s, 1s;
-o-transition-timing-function:ease-in-out, ease-in-out;
transition-property: top, opacity;
transition-duration: 1s, 1s;
transition-timing-function:ease-in-out, ease-in-out;
}
#one {
top: 0px;
background-color: blue;
opacity: 1;
}
#two {
top: 50px;
background-color: green;
opacity: 0;
}
#three {
top: 100px;
background-color: red;
opacity: 0;
}
#container {
width: 50px;
height: 150px;
position: relative;
overflow:hidden;
}
</style>
<script>
function one() {
document.getElementById('one').style.top = "0px";
document.getElementById('two').style.top = "50px";
document.getElementById('three').style.top = "100px";
document.getElementById('one').style.opacity = "1";
document.getElementById('two').style.opacity = "0";
document.getElementById('three').style.opacity = "0";
}
function two() {
document.getElementById('one').style.top = "-50px";
document.getElementById('two').style.top = "0px";
document.getElementById('three').style.top = "50px";
document.getElementById('one').style.opacity = "0";
document.getElementById('two').style.opacity = "1";
document.getElementById('three').style.opacity = "0";
}
function three() {
document.getElementById('one').style.top = "-100px";
document.getElementById('two').style.top = "-50px";
document.getElementById('three').style.top = "0px";
document.getElementById('one').style.opacity = "0";
document.getElementById('two').style.opacity = "0";
document.getElementById('three').style.opacity = "1";
}
</script>
</head>
<body>
<div id='container'>
<div class="myDiv" id='one'>
</div>
<div class="myDiv" id='two'>
</div>
<div class="myDiv" id='three'>
</div>
</div>
<input type='button' onclick='one();' value='one!'></input>
<input type='button' onclick='two();' value='two!'></input>
<input type='button' onclick='three();' value='three!'></input>
</body>
</html>
I came across advice that it's not recommended to change CSS properties with JavaScript. It's considered a bad practice. Is there a more elegant and effective way to achieve this?
Any idea? (fiddle here)