jQuery Chosen Plugin : Capturing focus to open when tabbing

SeanCocteau picture SeanCocteau · Jan 24, 2013 · Viewed 8.2k times · Source

We're currently using the Chosen Dropdown Plugin which is rather awesome, apart from one minor issue. When we're using a single dropdown, if you tab into the 'chosen' control, the actual dropdown portion is not shown. However, when applying the plugin to a multiple 'select', it does appear.

Having been through the documentation and GitHub issues, there seems to be a lot of mentions regarding tab ordering and focusing, but nothing that seemingly deals with this rather simple requirement; Display the dropdown when receiving focus when tabbing.

So assuming that this functionality is not part of the plugin, is there an alternative such as capturing the focus of the anchor tag?

$('.chzn-single').focus(function(e){
    alert('I should be focused!')
});    

So far, I haven't been successful and was wondering whether any others have experienced this issue. You can check out this jsfiddle that demonstrates the problem

Answer

paulitto picture paulitto · Jun 3, 2013
  1. You should keep track of focus event for the search input thats inside chosen conainer, not the anchor element, then trigger mousedown event for the chosen container - that's the event that it listens to when opening a dropdown

  2. You need to use delegated events approach to bind event handler to elements added dynamically (for jquery 1.7.1 and earlier you may just use 'live' method)

  3. You also need to check if the container is active currently, to avoid recursive calls (when chosen dropdown gets opened - search input will be focused again)

$('body').on('focus', '.chzn-container-single input', function() {
    if (!$(this).closest('.chzn-container').hasClass('chzn-container-active'))
        $(this).closest('.chzn-container').trigger('mousedown');
        //or use this instead
        //$('#select').trigger('liszt:open');  
});

Here's working jsfiddle

Instead of $(this).closest('.chzn-container').trigger('mousedown'); you may also trigger plugin's internal event: $('#select').trigger('liszt:open');