Pedro Estevao Pedro Estevao - 1 year ago 104
HTML Question

Slider of images with undefined height

I'm trying to create a slider of images (previous/next) so the images slide to the left when I click "previous" and to the right when I click "next" with 0.5s of slowness, so it takes some animation. And when I reach the last image and click "next", I want images to "run backwards" to the first one, the same when I'm in the first one and click "previous", so it "run forward" until the last one.

I want the same behaviour this JSFiddle shows. (but I don't need the timer to move images automatically and don't need the "triggers" buttons, just "previous" and "next").

The problem here is that my images don't have fixed size. I define a width in percentage and can't define a height because I have responsive design, the image resizes as I resize the browser window.

The jQuery to previous/next actions is pretty easy, but I just can't find a way to add this animation when I remove/add the "active" class to my images (so they become visible or not).

I have already tried putting all images side by side and showing only the first one (setting container width equals to image width), so when I click "next" I just "move" the container to the left so it begins to display the next image, but it doesn't work because once I can't define the height of the images, they will appear underneath each other, not side by side.



<div class="images">
<img class="active" src="1.jpg">
<img src="2.jpg">
<img src="3.jpg">

<div class="previous">previous</div>

<div class="next">next</div>


img {
width: 100px;
display: none;
float: left;
} {
display: block;


$('.next').on('click', function() {
var active = $('');
var next ='img');

if (next.length) {
} else {
$('.images img:first').addClass('active');

Answer Source

I finally got there.

HERE is the fiddle with the solution I developed.

The main problem in the implementation of this image slider was that images, althought were all the same size, have dynamic width (defined in % on CSS) and dynamic height (not defined on CSS).

The solution was basically put an "fake" image (with opacity: 0) inside my container so the container get the actual size of images I will use in the slider; put a div to "hold" the real images with position: absolute and give it a width calculted by number of images * 100%; and for last, give each image in my slider a width of x%, based on number of images.

In the jQuery, I "move" the "images holder div" always by %, never by static values, once the width of everything can change if I resize the window.

If you start to slide the images to the left and right and then resize the window, you will see that it continues to work perfectly.