I am trying to create a vertical carousel using vanilla JavaScript and CSS. I know that jQuery has a carousel library but I want to have a go at building this from scratch using no external libraries. I started off by just trying to move the top image and then I planned to move on to making the next image move. I got stuck on the first image. This is where I need your help, StackOverflowers.
My HTML:
<div class=slider vertical >
<img class=first opened src=http://malsup.github.io/images/beach1.jpg>
<img class=opened src=http://malsup.github.io/images/beach2.jpg>
<img src=http://malsup.github.io/images/beach3.jpg>
<img src=http://malsup.github.io/images/beach4.jpg>
<img src=http://malsup.github.io/images/beach5.jpg>
<img src=http://malsup.github.io/images/beach9.jpg>
</div>
<div class=center>
<button id=prev>∧ Prev</button>
<button id=next>∨ Next</button>
</div>
JavaScript:
var next = document.getElementById('next');
var target = document.querySelector('.first');
next.addEventListener('click', nextImg, false);
function nextImg(){
if (target.classList.contains('opened')) {
target.classList.remove('opened');
target.classList.add('closed');
} else {
target.classList.remove('closed');
target.classList.add('opened');
}
}
CSS:
div.vertical {
width: 100px;
}
.slider {
position: relative;
overflow: hidden;
height: 250px;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
-ms-box-sizing:border-box;
box-sizing:border-box;
-webkit-transition:-webkit-transform 1.3s ease;
-moz-transition: -moz-transform 1.3s ease;
-ms-transition: -ms-transform 1.3s ease;
transition: transform 1.3s ease;
}
.slider img {
width: 100px;
height: auto;
padding: 2px;
}
.first.closed{
/* partially offscreen */
-webkit-transform: translate(0, -80%);
-moz-transform: translate(0, -80%);
-ms-transform: translate(0, -80%);
transform: translate(0, -80%);
}
.first.opened{
/* visible */
-webkit-transform: translate(0, 0%);
-moz-transform: translate(0, 0%);
-ms-transform: translate(0, 0%);
transform: translate(0, 0%);
}
My mode of thinking was:
- use classes to move and show content
- use JavaScript to add and remove classes
I think I may not have broken the problem down properly.
This is how I would like it to look: http://jsfiddle.net/natnaydenova/7uXPx/
And this is my abysmal attempt: http://jsfiddle.net/6cb58pkr/