Welcome to WebmasterWorld Guest from 54.147.189.54

Forum Moderators: open

Message Too Old, No Replies

Content Carousel

     
1:42 am on Dec 17, 2013 (gmt 0)

Full Member

5+ Year Member

joined:Mar 22, 2008
posts: 315
votes: 0


I'm trying to build a basic 'carousel'. I have a container dive, and several content divs. I want to show each content div one at a time, for about 20 seconds, and then rotate to the next one. The number of content divs changes multiple times a day. My current script is doing a mediocre job, and bunching some of the content divs together. There's got to be a better way to do this?
<script type='text/javascript'>
$( document ).ready(function() {
$('.message').each(function(index,i) {
$(this).delay(index * 20000).show(0);
$(this).delay(index * 20000).hide(0);
});
});
</script>
<style>
.content {
display: none;
}
</style>

<div id='container'>
<div class='content'>Blah Blah</div>
<div class='content'>Foo</div>
<div class='content'>Bar</div>
<div class='content'>Lorem Ipsum</div>
</div>
7:14 pm on Dec 18, 2013 (gmt 0)

Full Member

5+ Year Member

joined:Mar 22, 2008
posts: 315
votes: 0


Bump.
9:12 pm on Dec 18, 2013 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts: 4965
votes: 10


What is the 'message' class referenced in your example?

Rather than attempting to schedule all of the image swaps at once at startup, use a more event driven approach. For exmample:


$( document ).ready(function() {
var contentList = $('.content'),
count = contentList.length,
index = 0,
current = $(contentList[index]),
delay = 20000;

function showNext() {
if (++index >= count) index = 0;
var next = $(contentList[index]);
current.hide();
next.show();
current = next;
setTimeout(showNext, delay);
}

$(current).show();
setTimeout(showNext, delay);
});


In other words, use setTimeout to schedule the next one after all of the work has been done. This will avoid the case where incremental work being done over a period of time causes overlap.
4:57 pm on Dec 19, 2013 (gmt 0)

Full Member

5+ Year Member

joined:Mar 22, 2008
posts: 315
votes: 0


Precisely what I was looking for! Thank you for your insightful problem solving approach.