jsFiddle is here: http://jsfiddle.net/qBQD4/
It's pretty simple really; I want the right arrow to move the images forwards, left arrow to move them backwards in a simple slideshow. I have multiple slideshows running on the page that this code will be implemented on, hence why I've gone the .next() route instead of just specifying a unique div id. The HTML is:
<div class="media">
<div class="slideButtons">
<span class="prev"><</span>
<span class="next">/ ></span>
</div>
<ul class="gallery" id="olympGallery">
<li><img src="http://i.imgur.com/8aA7W.jpg" alt="" title="" /></li>
<li><img src="http://i.imgur.com/jE7vj.jpg" alt="" title="" /></li>
<li><img src="http://i.imgur.com/L7lVg.jpg" alt="" /></li>
</ul>
</div>
And the jQuery code is:
var speed = 100;
$(".prev").click(function() {
var now = $(this).next("ul.gallery").children(":visible"),
last = $(this).next("ul.gallery").children(":last"),
prev = now.prev();
prev = prev.index() == -1 ? last : prev;
now.fadeOut(speed, function() {prev.fadeIn(speed);});
});
$(".next").click(function() {
var now = $(this).next("ul.gallery").children(':visible'),
first = $(this).next("ul.gallery").children(':first'),
next = now.next();
next = next.index() == -1 ? first : next;
now.fadeOut(speed, function() {next.fadeIn(speed);});
});
$(".gallery li").click(function() {
var first = $(this).parent().children(':first'),
next = $(this).next();
next = next.index() == -1 ? first : next;
$(this).fadeOut(speed, function() {next.fadeIn(speed);});
});
And finally, a bit of CSS:
.prev, .next {position: relative; padding: 3px; font-size:50px; font-weight: 900; cursor:pointer;
}
.gallery li{display:none; list-style:none;}
.gallery li:first-child {display:block;}
.gallery img {
max-height:550px
}
The 3rd function works fine (clicking the image progresses to the next in the series). However, the first two are completely broken. What have I done wrong here?
In the prev and next functions you've forgotten to ascend to the clicked div's parent before trying to find its associated gallery, i.e.:
var now = $(this).parent().next("ul.gallery").children(":visible")
Working sample at http://jsfiddle.net/alnitak/qBQD4/1/
FWIW, you should also really separate out that step into a separate variable, and then find the relevant images:
var gallery = $(this).parent().next("ul.gallery");
var first = gallery.children(':first');