3

If you see the image attached below. The country name style changes on mouse over. But when i click the down arrow key we have to show the same behavior. Can some one tell me how to do this ?

enter image description here

guradio
  • 15,524
  • 4
  • 36
  • 57
joy
  • 47
  • 1
  • 5

1 Answers1

0

Idea is to bind on keydown event and if key is arrow down - you should select next in the list. You have to have index of current selection and using it highlight menu item. When mouse over event happens, just change current selection index to the hovered item. Using index change background color. It's super easy to do with ReactJs and similar UI frameworks and a little messy with jQuery but if you got the idea, hopefully, you will succeed.

2 code snippets that should help:

$(document).keydown(function(e) {
    switch(e.which) {
        case 37: // left
        break;

        case 38: // up
        break;

        case 39: // right
        break;

        case 40: // down
        break;

        default: return; // exit this handler for other keys
    }
    e.preventDefault(); // prevent the default action (scroll / move caret)
});

$('.tg').bind('keypress', function(event) {
  if(event.which === 13) { // tab
    $(this).next().focus();
  }
});

Sources: - Simulate pressing tab key with jQuery - Binding arrow keys in JS/jQuery

I have demo repo where i done similar thing with ReactJs https://github.com/liesislukas/react-dropdown-autocomplete-with-search

Lukas Liesis
  • 24,652
  • 10
  • 111
  • 109
  • I tried above code. Does not work. Problem is I want exact behavior of mousehover on the country name. How do i trigger the mouseover event ? – joy Jul 20 '17 at 06:09
  • Is there any way to trigger the 'Tab' key press event in javascript ? – joy Jul 20 '17 at 06:10
  • You can trigger any event. Check this question: https://stackoverflow.com/questions/832059/definitive-way-to-trigger-keypress-events-with-jquery – Lukas Liesis Jul 20 '17 at 06:13
  • So basically what i want is when i key the down key it should trigger the tab key press event. I have given the tab indexes to the country names. Please any one .... – joy Jul 20 '17 at 06:25
  • Is there any way to record the script ? So that i can record what happens after mousehover. – joy Jul 20 '17 at 06:41
  • not sure what you mean. You can listen for all events and save data in some array or log data out to console or any other destination if needed. – Lukas Liesis Jul 20 '17 at 07:06