Posted by Michael in Portfolio, Tips, jQuery
on Jul 29th, 2010 | Comments Off
So I’ve got myself some work on a new website for my boss this week, and part of his site currently has some sort of slideshow thing – using jQuery. I have used them before, but never actually got round to coding one. So I decided to stop being lazy, and actually look at coding something up. So here it is:
<script type='text/javascript'>
/*
SlideShow jQuery Plugin v1.2
Michael Wright
http://michaelwright.me
*/
var slideShows = [];
$.fn.slideShow = function(){
$(this).children('img:gt(0)').hide();
slideShows[$(this).attr('id')] = {'imgs': $(this).children('img'), 'i': 0};
setInterval("changeImages('" + $(this).attr('id') + "')", 7000);
}
function changeImages(x){
$(slideShows[x]['imgs'][slideShows[x]['i']]).fadeOut(1000,
function(){
slideShows[x]['i'] = (slideShows[x]['i'] < slideShows[x]['imgs'].length-1? slideShows[x]['i'] + 1 : 0);
$(slideShows[x]['imgs'][slideShows[x]['i']]).fadeIn(1000);
}
);
}
</script>
<div id='test'>
</div>
<script type='text/javascript'>
$('#test').slideShow();
</script>
It is obviously lacking proper HTML structure, however, as it is, it works. Ultimately you created an element containing a series of images, and then simply invoke the slideshow function on the element. Make sure that the element container has an id as it is used to refer to the slideshow items later.
jQuery is required for this, so ensure that you are including the JavaScript file when using this code.