Search code examples
javascriptjqueryclickfocusjquery-focusout

Avoid click triggering focusout


i am working on the tab button functionality for my form.

I am using a plugin to customize all the selects of my form but now i am stuck on a conflict.

This is the code i have written to display my dropdown menu list using the tab button on the selects

$styledSelect.focus(function(e) {
  var dropdown = $(this).next('ul');
  dropdown.show();
});

$styledSelect.focusout(function(e) {
  var dropdown = $(this).next('ul');
  dropdown.hide();
});

The problem is that any click event triggers a focusout so i can not really select any option of my select tag, because the dropdown gets hidden first.

You can see the problem here http://codepen.io/Mannaio/pen/tLaup

How can i solve this problem?


Solution

  • You can set up a click and focus handler and reuse the same logic for both.

    function setFocus(e) {
      e.stopPropagation();
      $('div.select-styled.active').each(function() {
        $(this).removeClass('active').next('ul.select-options').hide();
      });
      $(this).toggleClass('active').next('ul.select-options').toggle();
    };
    
    $styledSelect.click(setFocus);
    
    $styledSelect.focus(setFocus);
    

    Updated CodePen: http://codepen.io/anon/pen/kcpqd