Reputation: 8315
I'm writing a small gallery/slideshow page that should change through its images using the left or right arrow keys. Currently, the code works somewhat, but does not change through all of its images. Why is this? How can it be fixed?
Images for sample test :
[
'http://i.imgur.com/co6MlSo.jpg',
'http://i.imgur.com/gCxcOKi.jpg',
'http://i.imgur.com/lsu7ZSw.jpg',
'http://i.imgur.com/pwysNhX.jpg'
];
Code :
<html>
<head>
<title>gallery</title>
<style type="text/css">
html, body{
background: #333333;
height: 100%;
margin: 0;
padding: 0;
font-family: Arial Black;
font-size: 18px;
line-height: 1.5;
text-align: justify;
}
img{
padding: 0;
display: block;
margin: 0 auto;
max-height: 100%;
max-width: 100%;
}
</style>
</head>
<body>
<div class="container">
<div id="slideshow">
<img
alt="slideshow"
src="co6MlSo.jpg"
id="imgClickAndChange"
onclick="changeImage()"
/>
</div>
</div>
<script>
var images = [
"co6MlSo.jpg",
"gCxcOKi.jpg",
"lsu7ZSw.jpg",
"pwysNhX.jpg"
];
function changeImage(dir){
var img = document.getElementById("imgClickAndChange");
img.src = images[images.indexOf(img.src) + (dir || 1)] || images[dir ? images.length - 1 : 0];
}
document.onkeydown = function(e){
e = e || window.event;
if (e.keyCode == '37'){
changeImage(-1) // left to display previous image
}else if (e.keyCode == '39'){
// right to display next image
changeImage()
}
}
</script>
</body>
</html>
Upvotes: 1
Views: 52
Reputation: 67505
You could add conditions like :
if(dir=='next'){
index++;
}else{
index--;
}
if(index>images_length){
index=0;
}else if(index<0){
index=images_length;
}
img.src = images[index];
Hope this helps.
var images = ["http://i.imgur.com/co6MlSo.jpg","http://i.imgur.com/gCxcOKi.jpg","http://i.imgur.com/lsu7ZSw.jpg","http://i.imgur.com/pwysNhX.jpg"];
var index = 0;
var images_length = images.length-1;
function changeImage(dir){
var img = document.getElementById("imgClickAndChange");
if(dir=='next'){
index++;
}else{
index--;
}
if(index>images_length){
index=0;
}else if(index<0){
index=images_length;
}
img.src = images[index];
}
document.onkeydown = function(e){
e = e || window.event;
if (e.keyCode == '37'){
changeImage('prev');
}else if (e.keyCode == '39'){
changeImage('next');
}
}
html, body{
background: #333333;
height: 100%;
margin: 0;
padding: 0;
font-family: Arial Black;
font-size: 18px;
line-height: 1.5;
text-align: justify;
}
img{
padding: 0;
display: block;
margin: 0 auto;
max-height: 100%;
max-width: 100%;
}
<div class="container">
<div id="slideshow">
<img
alt="slideshow"
src="http://i.imgur.com/co6MlSo.jpg"
id="imgClickAndChange"
onclick="changeImage()"
/>
</div>
</div>
Upvotes: 1