JSFiddle - React, Tailwind, and code Playground

by sbaydakov

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fixed Focus Row List</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="row-list">
        <div class="list-container">
            <div class="list">
                <div class="item">Item 1</div>
                <div class="item">Item 2</div>
                <div class="item">Item 3</div>
                <div class="item">Item 4</div>
                <div class="item">Item 5</div>
                <div class="item">Item 6</div>
                <div class="item">Item 7</div>
                <div class="item">Item 8</div>
                <div class="item">Item 9</div>
                <div class="item">Item 10</div>
            </div>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

SCSS

body {
    font-family: Arial, sans-serif;
    text-align: center;
    overflow: hidden; /* Hide horizontal scroll */
}

.row-list {
    overflow: hidden;
}

.list-container {
    display: flex;
    /* gap: 20px; /* Adjust the gap between items as needed */
    margin: 0 auto;
    transition: transform 0.3s;
    will-change: transform;
}

.list {
    display: flex;
}

.item {
  width: 100px;
  padding: 20px;
  border: 1px solid #ccc;
  background-color: #f2f2f2;
  flex: 0 0 auto;
  transition: transform 0.3s;

  &:focus {
    background-color: #d0d0d0;
    outline: none;
  }
  
  img {
    display: block;
  }
}

.fixed-focus {
    /* transform: scale(1.2); */ /* Adjust the scaling factor for the fixed focus item */
    z-index: 1;
}

JavaScript

const listContainer = document.querySelector('.list-container');
const list = document.querySelector('.list');
const items = document.querySelectorAll('.item');

let focusedIndex = 0;

items[focusedIndex].classList.add('fixed-focus');
items[focusedIndex].tabIndex = 0;
items[focusedIndex].focus();

list.addEventListener('keydown', (e) => {
    items[focusedIndex].classList.remove('fixed-focus');

    if (e.key === 'ArrowRight') {
        focusedIndex = (focusedIndex + 1) % items.length;
    } else if (e.key === 'ArrowLeft') {
        focusedIndex = (focusedIndex - 1 + items.length) % items.length;
    }

    items[focusedIndex].classList.add('fixed-focus');
    items[focusedIndex].tabIndex = 0;
    items[focusedIndex].focus();

    const scrollOffset = focusedIndex * (items[focusedIndex].offsetWidth); // Adjust the gap as needed
    listContainer.style.transform = `translateX(-${scrollOffset}px)`;
});