JSFiddle - React, Tailwind, and code Playground

by john_s

HTML

<ul id="colorList" tabindex="1">
    <li data-color="blue">Blue</li>
    <li data-color="red">Red</li>
    <li data-color="green">Green</li>
    <li data-color="orange">Orange</li>
    <li data-color="yellow">Yellow</li>
    <li data-color="pink">Pink</li>
    <li data-color="gray">Gray</li>
    <li data-color="magenta">Magenta</li>
    <li data-color="teal">Teal</li>
</ul>
<input id="color" type="hidden" value="" />

CSS

ul {
    padding: 0px;
    border: 1px solid;
    width: 100px;
    height: 100px;
    overflow: scroll;
    overflow-x: hidden;
}
ul:focus {
    border: 1px dashed;
}
ul>li {
    padding: 2px;
    width: 100px;
    display: block;
    list-style-type: none;
}

JavaScript

$(document).ready(function() {
    function selectItem($item, dir) {
        var color = $item.attr('data-color');
        $item.css({ background: color });
        $item.siblings().css({ background: 'white' });
        if (dir) { $item[0].scrollIntoView(dir == 'prev'); }
        $('#color').val(color);
    }

    $('#colorList').on('click', '>li', function() {
        var $item = $(this);
        selectItem($item);
    });

    $('#colorList').on('keydown', function(e) {
        if ((e.which == 38) || (e.which == 40)) {
            var $list = $(this),
                currentColor = $('#color').val(),
                dir = (e.which == 38) ? 'prev' : 'next';
            if (currentColor) {
                var $currentItem = $list.children('li[data-color="' + currentColor + '"]');
                if ($currentItem.length > 0) {
                    var $nextItem = $currentItem[dir]();
                    if ($nextItem.length > 0) {
                        selectItem($nextItem, dir);
                   }
                    return false;
                }
            }
            selectItem($list.children('li:first'), 'next');
            return false;
        }
    });  

    $('#colorList').on('keypress', function(e) {
        if ((e.which == 38) || (e.which == 40)) {
            return false;
        }
    });

    $('#colorList').on('keyup', function(e) {
        if ((e.which == 38) || (e.which == 40)) {
            return false;
        }
    });
});