Search code examples
javascripthtml-listshrefkeydown

Click active li href on keydown


I am using code to make a simple character select screen for a javascript game. Each character can be hovered over and clicked to go to a specific version of the game. I am trying to make them selectable with keyboard keys as well so they can be mapped to an arcade controller. The arrows work to select and the enter key will go to a link but the code I have now always goes to the same link on keydown, no matter which character is 'active'.

How do I go to the link of the active li item when the enter key is pressed?

Here is my current code.

CODE

$(document).ready(function () {
	var vehicleIndex = 1;

	function activeVehicle(index) {
		var selector = "#t-" + index;
		$('.active').removeClass('active');
		$(selector).addClass('active');
	}
	window.onkeyup = function (e) {
		var code = e.which;
		if (code == 39) {
			if (vehicleIndex < 5) vehicleIndex++;
		} //up
		if (code == 37) {
			if (vehicleIndex > 1) vehicleIndex--;
		} //down

		activeVehicle(vehicleIndex);
	};
});

$(document.body).on('keydown', function (e) {
	if (e.keyCode == 13) {
		window.location = $('.clickme').attr('href');
	}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <h3>SELECT YOUR VEHICLE</h3>
  <br>
  <ul id="SelectJeep">
    <a href="link1.html" 
    class="clickme">                                            
      <li id="t-1" class="active">
        <h1>MANCHE</h1>
      </li>
    </a>
    <a href="link2.html" class="clickme">
      <li id="t-2">
        <h1>ASCENDER</h1>
      </li>
    </a>
    <a href="link3.html" class="clickme">
      <li id="t-3">
        <h1>CRUSADER</h1>
      </li>
    </a>
    <a href="link4.html" class="clickme">
      <li id="t-4">
        <h2>COMING SOON</h2>
      </li>
    </a>
  </ul>
</div>


Solution

  •    if (e.keyCode == 13) {
            window.location = $('.clickme').attr('href');
        }
    

    =>

    if (e.keyCode == 13) {
            window.location = $('.active').parent().attr('href');
    }