Home:ALL Converter>How to create carousel using javascript and hover to prev and next image with keypress?

How to create carousel using javascript and hover to prev and next image with keypress?

Ask Time:2019-07-07T16:17:20         Author:Jesse W

Json Formatter

I want to create carousel using javascript which have an array of infinity images and after last image ends it should start from first image.On page load the first image should be selected by default and have active border on first image. When keypress right arrow or left arrow the image active border should move accordingly to next or prev image. And when press enter the active border image should get selected and opens link.

I have tried creating carousel but on keypress arrow left or right it doesn't work.

// Hover
var active = document.querySelector(".hover") || document.querySelector(".myImg a");


function handler(e){
           switch (e.keyCode) {
        case 37:
        active = active.previousElementSibling || active;
        case 39:
            active = active.nextElementSibling || active;
    default: active = e.target;


// Carousel
var carousel = document.querySelector('.content');
var slider = document.querySelector('.slider');

var next = document.querySelector('.next');
var prev = document.querySelector('.prev');
var imagesA = document.querySelector('.carousel-img');
//  var vid = document.querySelector('.videos');
var direction;

next.addEventListener('click', function () {
    direction = -1;
    carousel.style.justifyContent = 'flex-start';
    slider.style.transform = 'translate(-20%)';

prev.addEventListener('click', function () {
    if (direction === -1) {
        direction = 1;
    carousel.style.justifyContent = 'flex-end';
    slider.style.transform = 'translate(20%)';


slider.addEventListener('transitionend', function () {
    if (direction === 1) {
    } else {

    slider.style.transition = 'none';
    slider.style.transform = 'translate(0)';
    setTimeout(() => {
        slider.style.transition = 'all 0.5s';
}, false);

It can be like we see on netflix home carousel where we have list of movies covers but instead of mouse click or mouse over i want same behaviour with Keypress.Please help.

CODE HERE : codepen.io

Author:Jesse W,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/56920420/how-to-create-carousel-using-javascript-and-hover-to-prev-and-next-image-with-ke