Kyle Ulman Kyle Ulman - 4 months ago 5
Javascript Question

Can I execute a different set of code on the second time an event is triggered?

I am trying to develop a menu that can be navigated from the arrow keys and am having some trouble figuring out where to go from the initial event trigger that "highlights" the first element. If you check out my fiddle, you'll find that the first element is highlighted as it should when the right arrow key is pressed (remember to click in the body section of the fiddle!), but I am not sure where to go from there so that subsequent key presses will cycle through all of the elements.

https://jsfiddle.net/1kf34rdq

HTML

<div class="tile a">
A
</div>
<div class="tile b">
B
</div>
<div class="tile c">
C
</div>


jQuery

$(document).ready(function($) {
$("body").keydown(function(event){
if (event.which == 39) {
$(".a").css({"outline":"3px solid red"});
}
});
});


Any tips and feedback are appreciated, even if it takes the code in a completely different direction!

Answer

You should handle all direction key events like the following:

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

    $(".tile").hover(
      function() {$(this).css({"outline":"3px solid red"});},
      function() {$(this).css({"outline":"1px solid red"});}
    );

    $("body").keydown(function(event){
        if (event.which == 39) {
            activeIndex = 0;
        }
        else if (event.which == 38 && activeIndex != -1){
            activeIndex--;
        }
       else if (event.which == 40 && activeIndex != -1){
           activeIndex++;
       }

       if (activeIndex < 0) {
           activeIndex = 0;
       }
       else if (activeIndex == $("#menu-container").children(".tile").length) {
           activeIndex = $("#menu-container").children(".tile").length - 1;
       }

       if (activeIndex != -1) {
           $("#menu-container").children(".tile").css({"outline":"1px solid red"});
           $("#menu-container").children(".tile").eq(activeIndex).css({"outline":"3px solid red"});
       }
   });
});

You can find jsFiddle sample here: https://jsfiddle.net/k0yyk3ft/

Comments