Reputation: 3000
I'm trying to make this little slideshow, it works, but I can't write a correct function for the buttons. I want every time that a button is clicked, its related div display. and then slideshow continue its regular way.
demo: http://jsfiddle.net/sabeti05/dsagcc5u/
html
<div id="slideshow">
<div class=" hide block">
one
</div>
<div class="hide">
two
</div>
<div class="hide">
three
</div>
</div>
<button class="one">one</button>
<button class="two">two</button>
<button class="three">three</button>
css
body{text-align:center}
#slideshow {
height: 40px;
margin: 0 auto;
position: relative;
width: 100px;
}
#slideshow > div {
position: absolute;
}
.hide {
display: none;
}
.block {
display: block;
}
jquery
$(document).ready(function(){
setInterval(function() {
$('#slideshow > div.block')
.removeClass("block")
.next()
.addClass("block")
.end()
.appendTo('#slideshow');
}, 1000);
});
Upvotes: 2
Views: 76
Reputation: 3021
Have a look at changes I made to your demo.
You made really clever trick with rotating DOM elements but that way div
s lose their relation with buttons. Just leave elements in place and select next()
. If selection is empty, select first()
of siblings.
Also the markup needs to change so that buttons have type="button"
(thus avoiding their default type submit
) and have them contained in div #controls
.
Now you can bind single event listener to container's click
event on button
element. In listener, find its index in container and show corresponding div
with help of jQuery selectors. (Note that with jQuery 1.6.4 you have to use bind
instead of on
for binding event handler.)
Last but not least, there's the code to restart slideshow on button click.
Upvotes: 1