I have a slideshow that pulls its first image from a div, then pulls the rest of the images from an array of list items. I am following a tutorial exactly from The JavaScript Pocket Guide by Burdette (2010 printing), and while everything else works I cannot get any of the pictures after the first to center or align differently. They float left and to the top of the div.
HMTL:
<!DOCTYPE html>
<hmtl class="no-js">
<head>
<title>Slideshow</title>
<link rel="stylesheet" href="slideshow.css" type="text/css" />
<script type="text/javascript">
(function(d, c) { d[c] = d[c].replace(/\bno-js\b/,"js";})(document.documentElement, "className");
</script>
</head>
<body>
<div id="slideshow">
<div class="slides">
<img src="picture01.jpg" width="450" height="336" alt="stuff" />
</div>
<ul>
<li><a href="picture02.jpg" data-size="350x263"</li>
<li><a href="picture03.jpg" data-size="350x263"</li>
<li><a href="picture04.jpg" data-size="350x263"</li>
</ul>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript">
</script>
<script src="slideshow.js" type="text/javascript">
</script>
</body>
</hmtl>
CSS:
#slideshow {
background-color: #103f1c;
width:500px;
height:450px;
margin-left: auto;
margin-right: auto;
top:0px;
position: relative;
}
#slideshow .slides {
position: relative;
margin-left: auto;
margin-right: auto;
width: 450px;
}
#html.js #slideshow .slides img{
position: absolute;
margin-left: auto;
margin-right: auto;
}
#slideshow .next,
#slideshow .prev {
position: absolute;
top: 50%;
margin-top: -0.5em;
width: 40px;
font-size: 32px;
text-decoration: none;
}
#slideshow .next{
right: -50px;
padding-left:10px;
}
#slideshow .prev {
left:-50px;
padding-right: 10px;
text-align: right;
}
JS:
(function($) {
// Include utility jQuery plug-ins
$.fn.tallest = function(outer, margins) {
var fn = outer ? "height" : "outerHeight";
return Math.max.apply(Math, $.map(this, function(el) {
return $(el)[fn](margins);
}));
};
$.fn.widest = function(outer, margins) {
var fn = outer ? "width" : "outerWidth";
return Math.max.apply(Math, $.map(this, function(el) {
return $(el)[fn](margins);
}));
};
// Declare initial variables
var slideshow = $("#slideshow");
var slides = slideshow.find(".slides");
var currentImageIndex = 0;
// Create images from the link list
slideshow.find("ul a").each(function() {
var link = $(this);
var size = link.attr("data-size").split("x");
$("<img />").attr({
src : link.attr("href"),
width : size[0],
height : size[1],
alt : link.text()
}).hide().appendTo(slides);
});
// Collect all images in one node set and hide the list
var images = slides.find("img");
slideshow.find("ul").hide();
// Resize slides <div> to hold the largest images
var slidesWidth = images.widest();
var slidesHeight = images.tallest();
slides.css({
width : slidesWidth,
height : slidesHeight
});
// Center each image
images.each(function() {
var image = $(this);
image.css({
left: slidesHeight / 2 - image.width() / 2,
top: slidesHeight / 2 - image.height() / 2,
});
});
// Save a reference to the first image
var activeImage = images.eq(currentImageIndex);
// The function to show the next or previous image
function showImage(newIndex) {
currentImageIndex = newIndex >= images.length ? 0 : newIndex;
currentImageIndex = currentImageIndex < 0 ? images.length - 1 : currentImageIndex;
activeImage.fadeOut(0);
activeImage = images.eq(currentImageIndex).fadeIn(150);
}
// Start timer to cycle through images
var interval = setInterval(function() {
showImage(currentImageIndex + 1);
}, 5000);
// Create next and previous controls
$('\u232A').appendTo(slides).bind("click", +1, onClick);
$('\u2329').appendTo(slides).bind("click", -1, onClick);
// The event handler for the controls
function onClick(event) {
event.preventDefault();
clearInterval(interval);
showImage(currentImageIndex + event.data);
}
})(jQuery); // Self-invoking function executes automatically
The main problem here is in your CSS:
#html.js #slideshow .slides img{
position: absolute;
margin-left: auto;
margin-right: auto;
}
Margin: auto; will only work on objects that have a defined width. Since an image is a replaced inline-block, no real width exists. This is made worse by the fact that you've positioned it absolutely, which changes the way margins will work - the item will always pick up its position relative to the determined parent, and apply margins after that outside of the flow, so auto will not be relevant.
first step is to remove the absolute positioning on the image, it's not useful here.
By default, images are a type of inline-block, so simply adding "text-align:center;" to the "#slideshow .slides" selector will center the images.
Alternately, if we just want to edit the images and force them to center themselves, change the above block to:
#html.js #slideshow .slides img{
display:block;
margin-left: auto;
margin-right: auto;
}
and everything should line up like you wanted.
Related
I am making a vanilla js carousel. I have laid out basic previous and next functionality using js along with html and css.
Now I tried to use css-animations (keyframes) to do left and right slide-in/slide-out animations but the code became messy for me. So here I am asking that what minimal changes would be needed to get the same animation effects in this implementation ?
Will you go for pure JS based or pure CSS based or a mix to do the same ?
My goal is get proper animation with minimal code.
(function () {
let visibleIndex = 0;
let carousalImages = document.querySelectorAll(".carousal__image");
let totalImages = [...carousalImages].length;
function makeNextVisible() {
visibleIndex++;
if (visibleIndex > totalImages - 1) {
visibleIndex = 0;
}
resetVisible();
renderVisible();
}
function makePrevVisible() {
visibleIndex--;
if (visibleIndex < 0) {
visibleIndex = totalImages - 1;
}
resetVisible();
renderVisible();
}
function resetVisible() {
for (let index = 0; index < totalImages; index++) {
carousalImages[index].className = "carousal__image";
}
}
function renderVisible() {
carousalImages[visibleIndex].className = "carousal__image--visible";
}
function renderCarousel({ autoplay = false, autoplayTime = 1000 } = {}) {
if (autoplay) {
[...document.querySelectorAll("button")].forEach(
(btn) => (btn.style.display = "none")
);
setInterval(() => {
makeNextVisible();
}, autoplayTime);
} else renderVisible();
}
renderCarousel();
// Add {autoplay:true} as argument to above to autplay the carousel.
this.makeNextVisible = makeNextVisible;
this.makePrevVisible = makePrevVisible;
})();
.carousal {
display: flex;
align-items: center;
}
.carousal__wrapper {
width: 500px;
height: 400px;
}
.carousal__images {
display: flex;
overflow: hidden;
list-style-type: none;
padding: 0;
}
.carousal__image--visible {
position: relative;
}
.carousal__image {
display: none;
}
<div class='carousal'>
<div class='carousal__left'>
<button onclick='makePrevVisible()'>Left</button>
</div>
<section class='carousal__wrapper'>
<ul class='carousal__images'>
<li class='carousal__image'>
<img src='https://fastly.syfy.com/sites/syfy/files/styles/1200x680/public/2018/03/dragon-ball-super-goku-ultra-instinct-mastered-01.jpg?offset-x=0&offset-y=0' alt='UI Goku' / width='500' height='400'/>
</li>
<li class='carousal__image'>
<img src='https://www.theburnin.com/wp-content/uploads/2019/01/super-broly-3.png' alt='Broly Legendary' width='500' height='400'/>
</li>
<li class='carousal__image'>
<img src='https://lh3.googleusercontent.com/proxy/xjEVDYoZy8-CTtPZGsQCq2PW7I-1YM5_S5GPrAdlYL2i4SBoZC-zgtg2r3MqH85BubDZuR3AAW4Gp6Ue-B-T2Z1FkKW99SPHwAce5Q_unUpwtm4' alt='Vegeta Base' width='500' height='400'/>
</li>
<li class='carousal__image'>
<img src='https://am21.mediaite.com/tms/cnt/uploads/2018/09/GohanSS2.jpg' alt='Gohan SS2' width='500' height='400'/>
</li>
</ul>
</section>
<div class='carousal__right'>
<button onclick='makeNextVisible()'>Right</button>
</div>
</div>
Updated codepen with feedback from the below answers and minor additional functionalities = https://codepen.io/lapstjup/pen/RwoRWVe
I think the trick is pretty simple. ;)
You should not move one or two images at the same time. Instead you should move ALL images at once.
Let's start with the CSS:
.carousal {
position: relative;
display: block;
}
.carousal__wrapper {
width: 500px;
height: 400px;
position: relative;
display: block;
overflow: hidden;
margin: 0;
padding: 0;
}
.carousal__wrapper,
.carousal__images {
transform: translate3d(0, 0, 0);
}
.carousal__images {
position: relative;
top: 0;
left: 0;
display: block;
margin-left: auto;
margin-right: auto;
}
.carousal__image {
float: left;
height: 100%;
min-height: 1px;
}
2nd step would be to calculate the maximum width for .carousal__images. For example in your case 4 * 500px makes 2000px. This value must be added to your carousal__images as part of the style attribute style="width: 2000px".
3rd step would be to calculate the next animation point and using transform: translate3d. We start at 0 and want the next slide which means that we have slide to the left. We also know the width of one slide. So the result would be -500px which also has to be added the style attribute of carousal__images => style="width: 2000px; transform: translate3d(-500px, 0px, 0px);"
That's it.
Link to my CodePen: Codepen for Basic Carousel with Autoplay
Try this. First stack all the images next to each other in a div and only show a single image at a time by setting overflow property to hidden for the div. Next, add event listeners to the buttons. When a bottom is clicked, the div containing the images is translated by -{size of an image} * {image number} on the x axis. For smooth animation, add transition: all 0.5s ease-in-out; to the div.
When someone clicks left arrow on the first image, the slide should display the last image. So for that counter is set to {number of images} - 1 and image is translated to left size * counter px.
For every click on the right arrow, the counter is incremented by 1 and slide is moved left. For every click on the left arrow, the counter is decremented by 1.
Slide.style.transform = "translateX(" + (-size * counter) + "px)"; this is the condition which is deciding how much the slide should be translated.
const PreviousButton = document.querySelector(".Previous-Button");
const NextButton = document.querySelector(".Next-Button");
const Images = document.querySelectorAll("img");
const Slide = document.querySelector(".Images");
const size = Slide.clientWidth;
var counter = 0;
// Arrow Click Events
PreviousButton.addEventListener("click", Previous);
NextButton.addEventListener("click", Next);
function Previous() {
counter--;
if (counter < 0) {
counter = Images.length - 1;
}
Slide.style.transform = "translateX(" + (-size * counter) + "px)";
}
function Next() {
counter++;
if (counter >= Images.length) {
counter = 0;
}
Slide.style.transform = "translateX(" + (-size * counter) + "px)";
}
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
.Container {
width: 60%;
margin: 0px auto;
margin-top: 90px;
overflow: hidden;
position: relative;
}
.Container .Images img {
width: 100%;
}
.Images {
transition: all 0.5s ease-in-out;
}
.Container .Previous-Button {
position: absolute;
background: transparent;
border: 0px;
outline: 0px;
top: 50%;
left: 20px;
transform: translateY(-50%);
filter: invert(80%);
z-index: 1;
}
.Container .Next-Button {
position: absolute;
background: transparent;
border: 0px;
outline: 0px;
top: 50%;
right: 20px;
transform: translateY(-50%);
filter: invert(80%);
z-index: 1;
}
.Container .Images {
display: flex;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://fonts.googleapis.com/css2?family=Cabin&family=Poppins&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<title>Carousel</title>
</head>
<body>
<div class="Container">
<button class="Previous-Button">
<svg style = "transform: rotate(180deg);" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M8.122 24l-4.122-4 8-8-8-8 4.122-4 11.878 12z"/></svg>
</button>
<button class="Next-Button">
<svg xmlns="http://www.w3.org/2000/svg" width = "24" height = "24" viewBox = "0 0 24 24"><path d="M8.122 24l-4.122-4 8-8-8-8 4.122-4 11.878 12z"/></svg>
</button>
<div class="Images">
<img src="https://source.unsplash.com/1280x720/?nature">
<img src="https://source.unsplash.com/1280x720/?water">
<img src="https://source.unsplash.com/1280x720/?rock">
<img src="https://source.unsplash.com/1280x720/?abstract">
<img src="https://source.unsplash.com/1280x720/?nature">
<img src="https://source.unsplash.com/1280x720/?trees">
<img src="https://source.unsplash.com/1280x720/?human">
<img src="https://source.unsplash.com/1280x720/?tech">
</div>
</div>
<script src="main.js"></script>
</body>
</html>
Alright. This might sound a little bit complicated. I've got a script which fetches thumbnails from a JSON. It fetches 9 thumbnails and onclick of the #load it fetches 9 more. How can I set the Load more button underneath the thumbnails and how to make it stick to the bottom of them each time you click it? ( I do not want it like it's now, on the side, but right in the middle and underneath them ).
+BONUS question: How can I fixate the thumbnails so they always show up 3 in a row. Since now, when I resize the window they change ( as you can see in the fiddle, there's only 2 per row now ).
jsfiddle.net/z6ge55ky/
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="twitch">
<script src="js/main.js"></script>
<div id="load">
<img class="hvr-pulse" src="http://i.imgur.com/KHIYHFz.png?1">
</div>
</div>
$(function() {
var i=0;
var twitchApi = "https://api.twitch.tv/kraken/streams";
var twitchData;
$.getJSON(twitchApi, function(json) {
twitchData = json.streams;
setData()
});
function setData(){
var j = twitchData.length > (i + 9) ? (i + 9) : twitchData.length;
for (; i < j; i++) {
var streamGame = twitchData[i].game;
var streamThumb = twitchData[i].preview.medium;
var streamVideo = twitchData[i].channel.name;
var img = $('<img style="width: 250px; height: 250px;" src="' + streamThumb + '"/>')
$('#twitch').append(img);
img.click(function(){
$('#twitch iframe').remove()
$('#twitchframe').append( '<iframe frameborder="0" style="overflow:hidden; margin-left: 25px; width:400px; height:250px; position: fixed; top: 0; margin-top: 23.55%;" src="http://player.twitch.tv/?channel=' + streamVideo + '"></iframe>');
});
}
}
$('#load').click(function() {
setData();
});
});
#twitch {
width: 60%;
position: absolute;
left: 20%;
text-align: center;
}
#twitch img {
border: 5px solid rgba(0,0,0,0);
margin: 0 auto;
cursor: pointer;
}
#load {
bottom: 0;
position: absolute;
}
You have declared the width for #twitch 60% remove that and for #load use top:100%
DEMO on jsfiddle
Here is my JsFiddle
I want to apply background-color change property to circle when the window slides. Like in the beginning only first circle will have background-color. and when the images slides to second screen the second circle will have only color.
Can anybody guide me how to achieve that.
JQuery:
$(document).ready(function () {
setInterval(function () {
var A = $('.gallery').scrollLeft();
if (A < 993) {
$('.gallery').animate({
scrollLeft: '+=331px'
}, 300);
}
if (A >= 993) {
$('.gallery').delay(400).animate({
scrollLeft: 0
}, 300);
}
}, 3000);
});
Here's a simple solution of your problem: http://jsfiddle.net/pjvCw/44/ but....
The way you're doing galleries is quite wrong.
You have a really sensitive CSS full of margin bugs (see in CSS code),
you calculate all by hand, which will just complicate your life one day if you'll get to add images, change widths etc...
Your buttons are positioned really wrongly, and again you don't even need to manually add them in your HTML. Let jQuery do all the job for you:
Calculate margins, widths,
Get the number of slides
generate buttons,
Make your buttons clickable
Pause gallery on mouseenter (loop again on mouseleave)
LIVE DEMO
This is the way you should go with your slider:
HTML:
<div class="galleryContainer"> <!-- Note this main 'wrapper' -->
<div class="gallery">
<div class="row">
<!-- ..your images.. -->
</div>
<div class="row">
<!-- ..your images.. -->
</div>
</div>
<div class="content-nav-control"></div> <!-- Let jQ create the buttons -->
</div>
Note the general gallery wrapper, it allows you with this CSS to make your buttons parent not move with the gallery.
CSS:
In your code, using display:inline-block; adds 4px margin to your elements, ruining your math. So you just need to apply font-size:0; to remove that inconvenience.
As soon I did that the math was working and the right width was than 340px, having 5px border for your images and 20px margin.
.galleryContainer{
/* you need that one
// to prevent the navigation move */
position:relative; /* cause .content-nav-control is absolute */
background-color: #abcdef;
width:340px; /* (instead of 350) now the math will work */
height: 265px;
}
.gallery{
position:relative;
overflow: hidden; /* "overflow" is enough */
width:340px; /* (instead of 350) now the math will work */
height: 265px;
}
.gallery .row {
white-space: nowrap;
font-size:0; /* prevent inline-block 4px margin issue */
}
.gallery img {
display: inline-block;
margin-left: 20px;
margin-top: 20px;
}
.normalimage {
height: 80px;
width: 50px;
border: 5px solid black;
}
.wideimage {
height: 80px;
width: 130px;
border: 5px solid black;
}
img:last-of-type {
margin-right:20px;
}
.content-nav-control {
position: absolute;
width:100%; /* cause it's absolute */
bottom:10px;
text-align:center; /* cause of inline-block buttons inside*/
font-size:0; /* same trick as above */
}
.content-nav-control > span {
cursor:pointer;
width: 20px;
height: 20px;
display: inline-block;
border-radius: 50%;
border:1px solid #000;
box-shadow: inset 0 0 6px 2px rgba(0,0,0,.75);
margin: 0 2px; /* BOTH MARGINS LEFT AND RIGHT */
}
.content-nav-control > span.active{
background:blue;
}
And finally:
$(function () { // DOM ready shorty
var $gal = $('.gallery'),
$nav = $('.content-nav-control'),
galSW = $gal[0].scrollWidth, // scrollable width
imgM = parseInt($gal.find('img').css('marginLeft'), 10), // 20px
galW = $gal.width() - imgM, // - one Margin
n = Math.round(galSW/galW), // n of slides
c = 0, // counter
galIntv; // the interval
for(var i=0; i<n; i++){
$nav.append('<span />'); // Create circles
}
var $btn = $nav.find('span');
$btn.eq(c).addClass('active');
function anim(){
$btn.removeClass('active').eq(c).addClass('active');
$gal.stop().animate({scrollLeft: galW*c }, 400);
}
function loop(){
galIntv = setInterval(function(){
c = ++c%n;
anim();
}, 3000);
}
loop(); // first start kick
// MAKE BUTTONS CLICKABLE
$nav.on('click', 'span', function(){
c = $(this).index();
anim();
});
// PAUSE ON GALLERY MOUSEENTER
$gal.parent('.galleryContainer').hover(function( e ){
return e.type=='mouseenter' ? clearInterval(galIntv) : loop() ;
});
});
"- With this solution, What can I do now and in the future? -"
Nothing! just freely add images into your HTML and play, and never again have to take a look at your backyard :)
Try this: http://jsfiddle.net/yerdW/1/
I added a line that gets the scrollLeft and divides it by your width (331px) to get the position and use that to select the 'active' circle:
$(".circle").removeClass("coloured");
position = Math.ceil($(".gallery").scrollLeft()/331 + 2);
if(position > $(".circle").length){
position = 1; // yes...
}
$(".content-nav-control div:nth-child("+position+")").addClass("coloured");
Red background for active circle:
.coloured {
background : red;
}
Note that you should initialise with the first circle already having the .coloured class applied.
Here you go: http://jsfiddle.net/pjvCw/41/
i added new class
.selected
{
background-color: red;
}
and modified some js code
Here is your jsfiddle edited http://jsfiddle.net/pjvCw/45/
var scrolled = 0;
var circles = $(".circle");
var colorCircle = function(index) {
for(var i=0; i<circles.length; i++) {
if(i == index) {
circles.eq(i).css("background-color", "rgba(255, 0, 0, 1)");
} else {
circles.eq(i).css("background-color", "rgba(255, 0, 0, 0)");
}
}
}
$(document).ready(function () {
setInterval(function () {
var A = $('.gallery').scrollLeft();
if (A < 993) {
$('.gallery').animate({
scrollLeft: '+=331px'
}, 300);
colorCircle(++scrolled);
}
if (A >= 993) {
$('.gallery').delay(400).animate({
scrollLeft: 0
}, 300);
colorCircle(scrolled = 0);
}
}, 3000);
colorCircle(0);
});
I added a transition to the .circle class, so it looks a little bit better:
.circle {
width: 20px;
height: 20px;
display: inline-block;
border-radius: 50%;
border:1px solid #000;
box-shadow: inset 0 0 6px 2px rgba(0,0,0,.75);
margin-right: 5px;
transition: background-color 700ms;
-webkit-transition: background-color 700ms;
}
How can I make the carousel center the item I've clicked to the middle? I've looked everywhere for an answer but they're not straight answers... Can someone help me in this, please?
This is what I've done so far: http://jsfiddle.net/sp9Jv/
HTML:
<div id="wrapper">
<div id="carousel">
prev
next
<div class="viewport">
<ul>
<li>Un</li>
<li>Deux</li>
<li>Trois</li>
<li>Quatre</li>
<li>Cinq</li>
<li>Six</li>
<li>Sept</li>
<li>Huit</li>
</ul>
</div>
<!-- viewport -->
</div>
<!-- carousel -->
</div>
<!-- wrapper -->
JavaScript:
var carousel = $('#carousel'),
prev = carousel.find('.prev'),
next = carousel.find('.next'),
viewport = carousel.find('.viewport'),
item = viewport.find('li'),
itemWidth = item.outerWidth(true),
itemNum = item.length,
itemList = viewport.find('ul');
itemList.width(itemWidth * itemNum);
var moveCarousel = function(dir) {
itemList.animate({ left: '-=' + (itemWidth * dir) + 'px' }, 400);
};
//prev
prev.on('click', function(e) {
e.preventDefault();
moveCarousel(-1);
});
//next
next.on('click', function(e) {
e.preventDefault();
moveCarousel(1);
});
//carousel item
item.on('click', 'a', function(e) {
var self = $(this),
selfIndex = self.index(),
distance = itemList.width() / 2,
selfPos = self.position(),
selfPosLeft = selfPos.left,
viewportPosLeft = viewport.position().left;
e.preventDefault();
//move item to middle, but it doesn't work...
if (selfPosLeft > Math.floor(viewport.width())/3) {
itemList.animate({ left: '-' + Math.floor(viewport.width())/3 + 'px' }, 400);
}
if (selfPosLeft < Math.floor(viewport.width())/3) {
itemList.animate({ left: Math.floor(viewport.width())/3 + 'px' }, 400);
}
});
CSS:
#wrapper {
width: 500px;
margin: 20px auto;
}
#carousel {
position: relative;
}
.viewport {
width: 260px;
border: 1px solid #6e6e6e;
height: 80px;
overflow: hidden;
position: relative;
margin-left: 100px;
}
.prev, .next {
position: absolute;
}
.prev {
top: 20px;
left: 0;
}
.next {
top: 20px;
right: 0;
}
.viewport ul {
position: absolute;
}
.viewport li {
float: left;
margin-right: 10px;
}
.viewport li a {
display: block;
width: 80px;
height: 80px;
background: #ddd;
}
While you have prepared all the information needed about all items, you can calculate the value of the left based on the clicked item.
Here is my modification:
and I've bound the click action of carousel items with this function and passed the clicked item using the self keyword.
var itemClicked=function(item){
var itemIndex=$(item).index(),
newLeft=(itemIndex*itemWidth*-1)+Math.floor(($(viewport).width()/itemWidth)/2)*itemWidth;
$(itemList).animate({left:newLeft+"px"},400);
};
You can check it working on this url: http://jsfiddle.net/rUZHg/3/
I assume that this should work despite of the number of viewed elements while it calculates the padding between the left 0 and the left of the center element.
Alright, it's ugly, I hope it gives you some ideas.
I created a global currentItem that tracks what's in the center. Every time the carousel moves this is updated.
The very useful variable I found was selfPosLeft which told me what was being clicked. I should add that 90 was the multiple I got from clicking around. Must be linked to your CSS and I don't know how to find this number dynamically.
Please try it :) http://jsfiddle.net/sp9Jv/4/
Well, I'm picturing that when you have more than 3 items you can change the code to compute the difference between the current item and the selfPosLeft of the clicked one, I'll leave that to you :) Like this, seems to work. http://jsfiddle.net/sp9Jv/5/
I'll even share my code with you!
Basically, I have a carousel that I built from the bottom up - Now, it works fine when there is more than one product being shown.
When there is only one product shown, then the animation jumps in IE (surprise...). Anyone have and idea how I could fix this up?
My jQuery for the sliding:
$(leftButton).click(function(){
var item_width = 205;
var left_indent = parseInt($('ul#carousel_ul').css('left')) + (item_width);
var $currElement = $('ul#carousel_ul li:last');
$($currElement).prependTo('ul#carousel_ul');
$('ul#carousel_ul').css({'left':-left_indent});
$('ul#carousel_ul:not(:animated)').animate({'left' : 0},carouselSpeed,function(){
$('#carousel_ul').css({'left':0}); //css fix
});
});
$(rightButton).click(function(){
var item_width = 205;
var position = $('ul#carousel_ul').position();
var left_indent = parseInt(position.left + item_width);
$('ul#carousel_ul:not(:animated)').animate({'left' : left_indent},carouselSpeed,function(){
var $currElement = $('ul#carousel_ul li:first');
if ($.browser.msie) {
$('ul#carousel_ul').css({'left':'11px'});
} else {
$('ul#carousel_ul').css({'left':'0px'});
}
$($currElement).hide().appendTo('ul#carousel_ul');
$($currElement).show();
});
return false;
});
And my HTML:
<div id="carousel_inner">
<ul id="carousel_ul">
<li name="1"></li>
<li name="2"></li>
<li name="3"></li>
<li name="4"></li>
<li name="5"></li>
<li name="6"></li>
<li name="7"></li>
<li name="8"></li>
<li name="9"></li>
</ul>
</div>
And finally, my CSS:
div#carousel_inner {
float:left;
width:205px;
height: 125px;
min-height: 115px;
margin-left: 25px;
position: relative;
overflow: hidden;
z-index: 75;
}
ul#carousel_ul {
position:relative;
left:0px;
list-style-type: none;
margin: 0 auto;
padding: 0px;
width:9999px; /* important */
height: 115px;
min-height: 115px;
bottom: 35px;
z-index: 75;
}
Try an absolute position like so:
ul#carousel_ul {
position:absolute;
left:0;
list-style-type: none;
margin: 0 auto;
padding: 0;
width:9999px; /* important */
height: 115px;
min-height: 115px;
bottom: 35px;
z-index: 75;
}
And where you wrote /* important */ did you not mean !important?? NOTE - Your carousal may now be positioned wrong, but at least test to see if it is FUNCTIONING properly with the above css...
Try replace this piece of code:
$('ul#carousel_ul:not(:animated)').animate({'left' : 0},carouselSpeed,function(){
$('#carousel_ul').css({'left':0}); //css fix
});
With this:
$('ul#carousel_ul').stop().animate({'left' : 0},carouselSpeed,function(){
$('#carousel_ul').css({'left':0}); //css fix
});
The code you've used to get the css left value here:
var left_indent = parseInt($('ul#carousel_ul').css('left')) + (item_width);
Will produce something like 100px and not 100, so you cannot add that to your item_width, because that would result in some math like 100px+300 which is incorrect. Try this:
var position = $('ul#carousel_ul').position();
var left_indent = parseInt(position.left + item_width);
position.left will return the left position of the object, while position.top will return the top position.
Reference: http://api.jquery.com/position/