Owly Owly - 1 year ago 79
HTML Question

Press left and right arrow to change image?

So I have this simple slideshow:

<div class="container">
<div id="slideshow">
<img alt="slideshow" src="1.jpg" id="imgClickAndChange" onclick="changeImage()" />

I have managed to make the images change when I click like this:

<script language="javascript">
var imgs = ["2.jpg", "3.jpg", "4.jpg", "5.jpg"];

function changeImage() {
document.getElementById("imgClickAndChange").src = imgs[0];

The problem is I also want the images to change when I press the right arrow (for next) and left arrow (to go back). How can I do this? I've tried adding an "onkeypress" event but nothing seems to work. I'm doing something wrong. I'm pretty new to javascript so if you can help me it would be great. Thank you :)

Answer Source

See the answer in action http://jsfiddle.net/7LhLsh7L/ (note for fiddler: as it runs in editor itself before pressing arrow(left, right) keys, you should give focus(just click result area) to result area)

Here is the markup and script:

<div class="container">
    <div id="slideshow">
        <img alt="slideshow" src="http://thumb7.shutterstock.com/photos/thumb_large/253822/156271139.jpg" id="imgClickAndChange" onclick="changeImage()" />
    var imgs = ["http://thumb7.shutterstock.com/photos/thumb_large/253822/156271139.jpg", "http://thumb9.shutterstock.com/photos/thumb_large/554278/132632972.jpg", "http://thumb7.shutterstock.com/photos/thumb_large/101304/133879079.jpg", "http://thumb101.shutterstock.com/photos/thumb_large/422038/422038,1327874090,3.jpg", "http://thumb1.shutterstock.com/photos/thumb_large/975647/149914934.jpg", "http://thumb9.shutterstock.com/photos/thumb_large/195826/148988282.jpg"];

    function changeImage(dir) {
        var img = document.getElementById("imgClickAndChange");
        img.src = imgs[imgs.indexOf(img.src) + (dir || 1)] || imgs[dir ? imgs.length - 1 : 0];

    document.onkeydown = function(e) {
        e = e || window.event;
        if (e.keyCode == '37') {
            changeImage(-1) //left <- show Prev image
        } else if (e.keyCode == '39') {
            // right -> show next image

The features of above solution:

  • If you click on the image, it'll take you to next image and repeats the cycle when it reaches last image.
  • For Left arrow(<-) it loads previous image and cycles repeats in reverse direction when reaches first image.
  • Right arrow(->) behavior is similar to click.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download