Welcome to WebmasterWorld Guest from 54.166.114.43

Forum Moderators: open

Message Too Old, No Replies

Content Carousel

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

5+ Year Member



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)

5+ Year Member



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

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



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)

5+ Year Member



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