javascript - Press left and right arrow to change image? -
so have simple slideshow:
<div class="container"> <div id="slideshow"> <img alt="slideshow" src="1.jpg" id="imgclickandchange" onclick="changeimage()" /> </div> </div>
i have managed create images alter when click 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 want images alter when press right arrow (for next) , left arrow (to go back). how can this? i've tried adding "onkeypress" event nil seems work. i'm doing wrong. i'm pretty new javascript if can help me great. give thanks :)
see reply in action http://jsfiddle.net/7lhlsh7l/ (note fiddler: runs in editor before pressing arrow(left, right) keys, should give focus(just click result area) result area)
here markup , 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 click on image, it'll take next image , repeats cycle when reaches lastly image. for left arrow(<-) loads previous image , cycles repeats in reverse direction when reaches first image. right arrow(->) behavior similar click. javascript html image slideshow arrow-keys
No comments:
Post a Comment