I'm building a multi-screen jQuery feature which is essentially a slideshow with content on each slide. The slides are positioned inline-block and moved using css's left property. However, the positioning is inaccurate, and causes the slides to graudally shift out of position when moving through them. I've removed the animation in order to show the shift a bit more clearly. See here:
var curr = 0;
$('.next').on('click', function(){
curr++;
$('.items').css('left', (curr*-140) + 'px')
})
$('.back').on('click', function(){
curr--;
$('.items').css('left', (curr*-140) + 'px')
})
http://jsfiddle.net/S8pdH/1/
Any help would be much appreciated!
You're only moving the items left by the amount of the width of the elements, but you're ignoring the space between the items.
The spacing between the items are 4 pixels wide, and I have changed it in your fiddle here.
Basically, you just have to find the width of the elements and the spacing and move the div left by that amount.
$('.next').on('click', function(){
var distanceBetweenDivs = ($($(".item")[1]).offset().left - ($($(".item")[0]).offset().left)); //144
curr++;
$('.items').css('left', (curr*-distanceBetweenDivs)+ 'px')
})
$('.back').on('click', function(){
var distanceBetweenDivs = ($($(".item")[1]).offset().left - ($($(".item")[0]).offset().left)); //144
curr--;
$('.items').css('left', (curr*-distanceBetweenDivs) + 'px')
})
(Edit: If you always have the same spacing between the .item
elements and you want to not use a static position change, you can find the exact difference between them doing as I have shown in this updated JSFiddle.)
If there is any space between the div opening and closing tags (slides) in the HTML document and they are positioned inline-block
there will be also space between them visible on the webpage.
Solution: remove white-space between tags
<div class="item">
...
</div><div class="item"> <!-- no space between closing and opening tag -->
...
</div>
Another, IMHO less elegant solution is to set font-size: 0
for the parent and then reset it for single item
.items {
font-size: 0;
}
.items .item {
font-size: 16px; /* or whatever you want */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With