0

Having issues with setting up a script for left and right arrow key image navigation

<script type="text/javascript">

        document.onkeydown = function(event) {
            var e = event || window.event;
            if (e.key === '37') { //LEFT
                nextSlide(-1);
            } else if (e.key === '39') { //RIGHT
                nextSlide(1);
            }
        };

        var slide_index = 1;
        displaySlides(slide_index);

        function nextSlide(n) {
            displaySlides(slide_index += n);
        }

        function displaySlides(n) {
            var i;
            var slides = document.getElementsByClassName("showSlide");
            if (n > slides.length) { slide_index = 1 }
            if (n < 1) { slide_index = slides.length }
            for (i = 0; i < slides.length; i++) {
                slides[i].style.display = "none";
            }
            slides[slide_index - 1].style.display = "block";
        }
    </script>

here is the html

     <div class="slidercontainer  ">
                    <div class="showSlide fade ">
                        <img src="https://i.stack.imgur.com/NjC6V.jpg" />
                    </div>
                    <div class="showSlide fade ">
                        <img src="https://i.stack.imgur.com/0eBBQ.gifg" />
                    </div>

                    <div class="showSlide fade ">
                        <img src="https://i.stack.imgur.com/uhjjB.png" />
                    </div>

<!--                     Navigation arrows-->
                    <a class="left" onclick="nextSlide(-1)">❮</a>
                    <a class="right" onclick="nextSlide(1)">❯</a>
                </div>

Looking to have accessibility to use the keyboard left and right arrows to change to the next or previous image

310_hills
  • 31
  • 6
  • Possible duplicate of [Detecting arrow key presses in JavaScript](https://stackoverflow.com/questions/5597060/detecting-arrow-key-presses-in-javascript) – Herohtar Jun 10 '19 at 02:09

1 Answers1

2

The key values for navigation keys are not intended to be numbers or numeric strings.

if(e.key === 'ArrowRight') { //RIGHT

and

if(e.key === `ArrowLeft`) {  //LEFT

should work in current browsers. Per the link you may need to test for key values of "Left" and "Right" as well to support some older browsers.

Note older key event properties like charCode, keyCode and which are deprecated and have been for some time.

traktor
  • 17,588
  • 4
  • 32
  • 53