0

I am trying to make an autocomplete functionality and want to apply focus to the first item in a list of matches once the user pressed the 'down' arrow.

This fires on keyup within the search box and manages the type of keypress fine:

   var handleKeyCode = function (e) {

    switch (e.which) {

        // Arrow up
        case 38:
            alert("Up");
            break;

        // Arrow down
        case 40:
            console.log("This fires fine...");
            arrowDown();
            break;

        // Other keys
        default:
            filter();
    };

    e.preventDefault();

};

This fires once the down arrow has been pressed, however, DOESNT apply the focus code for some reason. When I console log the selector it is returning the correct list item, just failing to focus.

var arrowDown = function () {

    console.log("Code below finds the selector fine:");
    console.log($('.scheme-list li:visible:first'));

    $('.scheme-list li:visible:first').focus(function () {
        console.log("The selector is not focused AND...");
        console.log("Anything in here is not fired!");
    });
};
Top Questions
  • 1,862
  • 4
  • 26
  • 38
Tomuke
  • 869
  • 2
  • 8
  • 26
  • 3
    `.focus(function...)` binds an event handler. To fire the event, send it without the argument `.focus()` – blgt Feb 09 '15 at 10:13
  • 1
    Only forms controls can take focus anyway, and `
    ` elements are not form controls.
    – Frédéric Hamidi Feb 09 '15 at 10:13
  • @FrédéricHamidi - aah okay, that makes sense! I am trying to focus onto a list item, so I assume the same cannot be done. I guess I will have to apply classes to replicate a focused state or something – Tomuke Feb 09 '15 at 10:15
  • @blgt .focus() doesn't work either. I am assuming because of the reason suggested above – Tomuke Feb 09 '15 at 10:19
  • Please show enough HTML to create a repro. Are the items in the list actually focusable elements? – iCollect.it Ltd Feb 09 '15 at 10:33

2 Answers2

0

$elem.focus(function () { /* do something */ }) will do something whenever the element gets focus.

$elem.focus() or $elem.trigger('focus') will set the focus on the element.

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
0

Turns out I was trying to focus on a non-focusable element I.e NOT a form control.

To get around this I added a tabindex HTML attribute to each of my list items to enable the focus event on these elements like so:

<li tabindex="0"> Some item I want to focus </li>

This then allowed me to call $().focus()and worked fine.

Tomuke
  • 869
  • 2
  • 8
  • 26