I've just finished to work on an interesting jQuery/WordPress project (you can find it here) where I had to build an interactive slideshow very similar to a classic jQuery slot machine in its inner functioning. The only problem was to keep track of the visibility of the slides, that is, being sure that the current slide was visible. This is a fantastic use case for the Observer Pattern.
Let's take a sample slideshow:
<div id="slideshow"> <div id="slideshow-wrapper"> <div class="slide one">One</div> <div class="slide two">Two</div> <div class="slide three">Three</div> <div class="slide four">Four</div> <div class="slide five">Five</div> </div> </div> <div id="watch"></div>
with a couple of CSS styles used to make it work:
#slideshow { width: 500px; height: 300px; margin: 2em auto; position: relative; overflow: hidden; border: 0.5em double #aaa; } #slideshow-wrapper { width: 2500px; height: 300px; position: relative; background: #222; } div.slide { float: left; width: 500px; height: 300px; background: #ccc; text-align: center; font-size: 1.5em; line-height: 300px; } div.two, div.four {background: #ffc;} div[rel="visible"] { font-size: 5em; }
When the slideshow moves from right to left, obviously the current slide is visible. We can attach a custom attribute to the current slide so that we're sure that it's visible:
var watch = function(element) { element.attr('rel', 'visible').siblings().removeAttr('rel'); $('#watch').text(element.text() + ' is ' + element.attr('rel')); };
Then we have to call this method only when the slideshow change its position:
var slideTo = function(element) { wrapper.animate({ left: - element.position().left }, 2000); }; var watch = function(element) { element.attr('rel', 'visible').siblings().removeAttr('rel'); $('#watch').text(element.text() + ' is ' + element.attr('rel')); }; var autoSlide = function() { timer = setInterval(function() { index++; if(index == slides.length) { index = 0; } var slide = slides.eq(index); slideTo(slide); watch(slide); }, 2000); };
Since we've set the following styles on a particular slide whose rel
attribute is set to visible
:
div[rel="visible"] { font-size: 5em; }
the font size of the current slide is increased as well. You can see the demo below.
Demo
Live demo (with code on jsFiddle)