4

So I have this simple slideshow:

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

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];
        imgs.push(imgs.shift())
    }
</script>

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 :)

Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93
Owly
  • 575
  • 2
  • 6
  • 16

3 Answers3

5

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()" />
    </div>
</div>
<script>
    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
            changeImage()
        }
    }
</script>

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.
Koti Panga
  • 3,660
  • 2
  • 18
  • 21
  • Yaay! It works. Thank you :) there's only one thing, I'd like the left arrow to go back and show the prev image, but it's showing the next image as well. What can I do to correct this? – Owly Oct 18 '14 at 20:45
  • @Owly: is left arrow not showing prev image? I checked with this fiddle http://jsfiddle.net/7LhLsh7L/1/ by putting all images together – Koti Panga Oct 18 '14 at 21:20
4

My own approach to the problem, while you've already accepted an answer, would be:

function imgCycle(e) {
    // obviously use your own images here:
    var imgs = ['nightlife', 'people', 'sports', 'cats'],
        // reference to the img element:
        imgElement = document.getElementById('imgClickAndChange'),
        // finding the string of the src after the last '/' character:
        curImg = imgElement.src.split('/').pop(),
        // finding that string from the array of images:
        curIndex = imgs.indexOf(curImg),
        // initialising the nextIndex variable:
        nextIndex;

    // if we have a keyCode (therefore we have a keydown or keyup event:
    if (e.keyCode) {
        // we do different things based on which key was pressed:
        switch (e.keyCode) {
            // keyCode 37 is the left arrow key:
            case 37:
                // if the current index is 0 (the first element in the array)
                // we next show the last image in the array, at position 'imgs.length - 1'
                // otherwise we show the image at the previous index:
                nextIndex = curIndex === 0 ? (imgs.length - 1) : curIndex - 1;
                break;
                // keyCode 39 is the right arrow key:
            case 39:
                // if curIndex + 1 is equal to the length of the images array,
                // we show the first element from the array, otherwise we use the next:
                nextIndex = curIndex + 1 === imgs.length ? 0 : curIndex + 1;
                break;
        }
        // if we don't have a keyCode, we check if the event-type (in lowercase)
        // is a mousedown:
    } else if (e.type.toLowerCase() === 'mousedown') {
        // I'm assuming you'd like to advance to the next image, rather
        // than regress to the previous (same check as above):
        nextIndex = curIndex + 1 === imgs.length ? 0 : curIndex + 1;
    }
    // setting the src of the image to the relevant URL + the string from the array
    // at the 'nextIndex':
    imgElement.src = 'http://lorempixel.com/200/200/' + imgs[nextIndex];
}

// binding a mousedown event-handler to the 'img' element:
document.getElementById('imgClickAndChange').addEventListener('mousedown', imgCycle);
// binding the keydown event-handler to the 'body' element:
document.body.addEventListener('keydown', imgCycle);

JS Fiddle demo.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
3

You can detect arrow key presses in JavaScript and then attach each key to an event. This SO answer shows how it's done but essentially:

document.onkeydown = checkKey;

function checkKey(e) {

    e = e || window.event;

    if (e.keyCode == '37') {
        // left arrow
    }
    else if (e.keyCode == '39') {
        // right arrow
    }
}
Community
  • 1
  • 1
Tim
  • 2,123
  • 4
  • 27
  • 44
  • I've tried to paste this – Owly Oct 18 '14 at 20:18