JSFiddle - React, Tailwind, and code Playground

by sm1215

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<form role="search" method="get" autocomplete="off" id="searchform" action="http://localhost/site/" class="searchbar-nav">
    <div class="row collapse">
        <input type="text" name="s" id="s" placeholder="Search game">
    </div>
</form>

<ul id="searchresults" class="searchresults">
    <li id="101">Mirror's Edge Catalyst</li>
    <li id="95">Minecraft</li>
    <li id="106">Middle-earth: Shadow of Mordor</li>
</ul>

CSS

.liSelected{
	background-color:red;
	color:white;
}

JavaScript

$(document).ready(function() {

	//track the currentSelection in js, instead of relying on jQuery lookups
	//this will be a little better on performance
    var $currentSelection;

    //on focus when arrow down is pressed
    $("#s").focus(function() {

        console.log('has focus');
		console.log('curSel', $currentSelection);

        $("#s").keydown(function(e) {

            if (e.which === 40) { //on arrow down
				
				console.log('key down');
				console.log('curSel', $currentSelection);
				
				//remove the liSelected class here, only after the arrow down is pressed 
				//because we know the selection is probably going to change
				$('ul#searchresults li').removeClass('liSelected');

                if ($('ul#searchresults li').length >= 1) { //if has one or more li

					if(typeof $currentSelection === 'undefined'){ //if there isn't a currentSelection
						console.log('PASS')
						$currentSelection = $('ul#searchresults li:first-child'); //set first child

                    } else {
					
						console.log('next: ',$currentSelection.next(), 'length: ',$currentSelection.next().length)
					
						//only change selection if we aren't at the end
						//we check the length here because we always get an
						//array back from calling .next(). If it's 0, then the array is empty
						//meaning we are at the end of the results list
						if($currentSelection.next().length > 0){ 
							console.log('setting')
							$currentSelection = $currentSelection.next();							
							
						} 
						
                    }
					
					//finally, apply the class after all the logic is out of the way
					$currentSelection.addClass('liSelected');
					//check console to see what we've got
					console.log('curSel: ', $currentSelection);
					
                }
            }
        });
    });

    $("#s").focusout(function() {
		//clear $currentSelection
		$currentSelection = undefined;
		console.log('is undefined? ', $currentSelection);
		
		//we also need to...