Restriction: Only HTML, Javascript (Jquery)
Goal: A slideshow where slides can be changed using left and right arrow.
Code Sample 1 (stop): https://jsfiddle.net/Penguinlay/8syyktd4/1/
HTML
<div class="card">
1
</div>
<div class="card">
2
</div>
<div class="card">
3
</div>
<div class="card">
4
</div>
<div class="card">
5
</div>
<div class="card">
6
</div>
<div class="card">
7
</div>
Script 1
$(document).ready(function() {
var totalCard, first, last, current, old;
first = $(".card:first");
last = $(".card:last");
current = first;
old = first;
$(".card").not(current).hide();
$(document).keydown(function(entry) {
old = current;
if(entry.keyCode == 37) {
if(old == first)
current = first;
else
current = old.prev();
}
if(entry.keyCode == 39) {
if(old == last)
current = last;
else
current = old.next();
}
$(".card").hide();
current.toggle();
});
});
Code Sample 2 (loop around): https://jsfiddle.net/Penguinlay/8syyktd4/3/
Same HTML as above.
Script 2
$(document).ready(function() {
var first, prev, current, next, last;
first = $(".card:first");
last = $(".card:last");
prev = last;
current = first;
next = first.next();
$(".card").not(first).hide();
$(document).keydown(function(e) {
if(e.keyCode == 37) {
next = current;
current = prev;
if(current == first)
prev = last;
else
prev = current.prev();
$(next).fadeOut(1);
}
if(e.keyCode == 39) {
prev = current;
if(current == last)
current = first;
else
current = next;
next = current.next();
$(prev).fadeOut(1);
}
$(current).fadeIn(100);
});
});
Problem:
In sample 1, the slide should stop on slide 1 upon left arrow click. It works correctly upon running but after visiting other slides and go back to slide 1, left arrow click on slide 1 does not stop but gives me white screen.
So, I tried with a little varied script in sample 2, where left arrow click on slide 1 with leads me to the last slide. Again, it works correctly upon running but after visiting other slides and go back to slide 1, left arrow click on slide 1 does not go to last slide but gives me white screen.
It doesn't work for right arrow either. Exact same problem as above.
It doesn't work in the latest version of Chrome, Firefox, Firefox Dev Edition, Microsoft Edge and JSFiddle.
How should I do so that it will work as I expected (either stop on slide 1 or go to last slide, respectively)?