Reputation: 49384
I am trying to create a very simple image slider. As simple as it gets but the way I'm doing it I'm having to enter too many combinations.
This is what I've got:
<script>
$(document).ready(function(){
$('#1').show();
$('#2').hide();
$('#3').hide();
$("next-btn").click(function(){
$("#1").hide();
$("#2").show();
});
});
</script>
</head>
<body>
<div id="slider">
<div id="1" class="slide"><img src="slide-image-1" alt="" /></div>
<div id="2" class="slide"><img src="slide-image-2" alt="" /></div>
<div id="3" class="slide"><img src="slide-image-3" alt="" /></div>
</div>
<div id="previous-btn">Previous slide</div>
<div id="next-btn">Next slide</div>
As you can see by the jquery code, the way I'm going i'll have to enter different onclick's depending which image is hidden etc..
How can I change this so it can just go to the next or previous div and show it when either buttons are clicked without having to add too many combinations?
Upvotes: 1
Views: 1504
Reputation: 2851
This code should work OK (tested). I hope you will get the idea :).
<script>
var active = 0;
var n = $('#slider div').length; // number of divs...
$(document).ready(function(){
showElement(1);
$("#next-btn").click(function(){
if (active < n) showElement(active + 1);
});
$("#previous-btn").click(function(){
if (active > 1) showElement(active - 1);
});
});
function showElement(id) {
$('#slider div').hide();
$('#' + id).show();
active = id;
}
</script>
active
stores the number of element that is showed. When you show something else, you hide everything, and show only the one you need. n
is used to store maximum number of elements so you will not get out of scope.
By the way this is not the most memory efficient solution, but it is really simple to modify it and it is really flexible. To be honest, you should track which slide is showed, which is hidden, and hide only the one that is showed, and show only the one that You need. But if there are only few slides (100?), the performance gap wont be a problem here, while the clarity of code and future expandability is much better here.
Also if something will go wrong in the future, every time user clicks something, the showElement function will repair it: hiding everything, and showing only the one you need.
Take a look on a working solution under this link: http://codepen.io/anon/pen/XbPogg
BTW: You can add more slides (id = 1, 2, 3, 4, 5, 6, ...) in your html markup, and this script will work without of any changes.
Upvotes: 1