Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Autocomplete: Get the currently focused <li>

JQuery Autocomplete triggers a focus event when the user mouses over or otherwise highlights one of its <li> options. Within this event, I want to refer to the <li> that is currently focused, but I can't figure out how to select it. At the moment, I have:

focus: function( event, ui ) {
  var target = event.currentTarget
  alert($(target).html())
}

But this returns the whole list of <li>s, rather than just the currently focused one. I've tried other event methods, such as event.delegateTarget and event.target, but with no success. Is there another way to get the focused element?

like image 612
nullnullnull Avatar asked Feb 01 '13 21:02

nullnullnull


2 Answers

You're going to have to:

  1. Grab the menu widget that autocomplete is using.
  2. Get the li that's currently focused (this li has an a with class ui-state-focus

    focus: function (event, ui) {
        var menu = $(this).data("uiAutocomplete").menu.element,
        focused = menu.find("li:has(a.ui-state-focus)");
        // focused is the focused `li`
    }
    

Example: http://jsfiddle.net/J5rVP/43/

like image 124
Andrew Whitaker Avatar answered Sep 18 '22 01:09

Andrew Whitaker


Are there any drawbacks when using the following instead?

focus: function(event, ui) {
    $(".ui-autocomplete li").removeClass("ui-state-hover");
    $(".ui-autocomplete").find("li:has(a.ui-state-focus)").addClass("ui-state-hover");
}
like image 20
Jack Avatar answered Sep 21 '22 01:09

Jack