JacobTheDev
JacobTheDev

Reputation: 18520

Making a Slideshow Rotate

I'm having trouble with a concept with a HTML5/jQuery slideshow system...

I want the images to constantly rotate, without stopping. The way I have it set up now is just going to the first image by changing the margin-left back to 0 when I run out of slides. I'd much rather have it continue indefinitely.

While I'm at it...Is there a way to read a property from the stylesheet? It'd be better if I could ask a user to point the script to the stylesheet and pull the sizing and stuff from there.

Demo: http://bearce.me/so/slideshow

Script (mainly focus on the CSS version, I can convert it to the jQuery version once I understand how to do it):

// JavaScript Document
var slides = 4; // number of slides
var time = 3; // time per slide (in seconds)
var width = 600; // width of slideshow (ex: 600)
var transition = .5 // transition time (in seconds) (for older browsers only, edit css for newer)
window.onload = function start() {
    if(Modernizr.csstransitions) {
        cssslide();
    } else {
        jqueryslide();
    }   
}
function cssslide() {
    document.getElementById("container").style.width=(width * slides) + "px";
    var num = 0;
    setInterval(function() {
        num = (num + 1) % slides;
        document.getElementById('container').style.marginLeft = (("-" + width) * num) + "px"; 
    }, time * 1000);
}
function jqueryslide() {
    $("#container").width((width * slides) + 'px');
    var num = 0;
    setInterval(function() {
        num = (num + 1) % slides;
        $("#container").animate({marginLeft: (("-" + width) * num) + "px"},{duration: (transition * 1000)});
    }, time * 1000);
}

EDIT: To clarify, I don't want it to constantly scroll, I want it to scroll, stop for a few seconds, scroll, stop, scroll, stop like it does, but instead of zooming all the way back to the first image, I just want it to keep going.

Upvotes: 3

Views: 591

Answers (2)

chipcullen
chipcullen

Reputation: 6960

I would seriously rethink your approach. Just tacking on more DOM elements into infinity is seriously inefficient, and would probably be an accessibility nightmare.

I would suggest you check out the jQuery Cycle plugin - it's real easy to implement, and allows you to loop infinitely.

Upvotes: 0

Brian Hadaway
Brian Hadaway

Reputation: 1893

When your slideshow initializes, use JS to duplicate your first image so that the markup looks like this:

<div id="container">
    <img src="setup/slides/portal2.jpg" />
    <img src="setup/slides/crysis2.jpg" />
    <img src="setup/slides/deadspace2.jpg" />
    <img src="setup/slides/acb.jpg" />
    <img src="setup/slides/portal2.jpg" />
</div>

Then once the 5th slide (duplicate of slide 1) is visible, clear your interval, reset your margin to 0 and re-initialize your slideshow.

Upvotes: 1

Related Questions