Search code examples
javascriptjqueryhtmlw3c

W3 school lightbox jquery add keybinds


I am trying to add keybinds to the exemple lightbox (link) But as much as I try I can't get it to work. Anyone that has any ideas?

I know that I have to do it in JS And I know the keycodes for Left and Right. But I am quite new to JS and I don't understand where I should do the function and how I would make it connect to next/prev.

Then I would like to be able to get ESC to function as a close as well. Any help would be appreciated.

The original version:

function plusSlides(n) {
showSlides(slideIndex += n);
}

My version so far, don't know if I am on the right track:

function plusSlides(n) {
            window.onkeydown = keydown;
            function keydown(e){
                if(e.which == 37 && next)
            }
            showSlides(slideIndex += n);
        }

Got the idea from the original text:

<a class="prev" onclick="plusSlides(-1)">&#10094;</a>
      <a class="next" onclick="plusSlides(1)">&#10095;</a>

With help from this community:

document.onkeydown = function (e) {
   e = e || window.event;
   if(e.keyCode === 39) {
       showSlides(slideIndex +=1);
   } else if(e.keyCode === 37) {
       showSlides(slideIndex -=1);
   } else if(e.keycode === 27) {
      closeModal();
   }

};

Strangely enough will not escape work. I have tried with keyup as well.


Solution

  • document.onkeydown = function (e) {
        e = e || window.event;
        if(e.keyCode === 39) {
            showSlides(slideIndex +=1);
        } else if(e.keyCode === 37) {
            showSlides(slideIndex -=1);
        } else if(e.keyCode === 27) {
            closeModal();
        }
    };
    

    This works, it can't go inside a function because you want to capture the actual keypress all the time. You'll also want to do something like make sure the modal is actually open before even capturing the keypresses, otherwise every time someone types a key on your site this code runs.

    For the record 46 is the period, 44 is the comma