Programming-Duck / carousel

Accessible carousel slider with HTML, CSS, JavaScript
MIT License
4 stars 4 forks source link

Keyboard support? #1

Open craig02445 opened 1 year ago

craig02445 commented 1 year ago

Great project, thank you. I have it running and the only way to move the carousel is via mouse on the buttons. Hints on getting it to also work with arrow keys?

sargalias commented 1 year ago

Thank you for the kind words.

For keyboard events, one way to make them work is to have an event listener for "keydown" on the window element. In this case, specifically "keydown" events rather than "keypress" because it seems that some browsers only support "keydown" events for the arrow keys. All keydown events would be captured for all buttons, so you'll need to test if the key that was pressed was the left arrow or right arrow keys. If it was, then call the handlePrevious or handleNext functions that are already in the code.

Here is some example code you can add between lines 50 and 51:

const handleArrowKeydownEvent = (event) => {
    if (event.key === "ArrowLeft") {
        handlePrevious();
    } else if (event.key === "ArrowRight") {
        handleNext();
    }
};
window.addEventListener('keydown', handleArrowKeydownEvent);

Hope that helps.