5

I want the select2 element to lose the focus when the select2-close event is triggered, what I have tried so far was:

.on("select2-close", function (e) {
    var $focused = $(':focus');
    $focused.blur();
});

and some variations to get focused element like document.activeElement, $(e.target) non f these worked.

JSFiddle

Akos K
  • 7,071
  • 3
  • 33
  • 46

1 Answers1

10

You need to remove the .select2-container-active class from the containing divider:

.on("select2-close", function () {
    setTimeout(function() {
        $('.select2-container-active').removeClass('select2-container-active');
        $(':focus').blur();
    }, 1);
});

I've used a setTimeout here as a hacky way to ensure that this triggers after the plugin itself finalises the close.

JSFiddle demo.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • Are you sure that your code removed the focus from the select2 element? Just try to log the focused element after your call. Really simple test. – Akos K Jan 16 '14 at 09:05
  • @akoskm ah sorry, I'd removed your part of the code. I've added `$(':focus').blur();` back in and updated the JSFiddle. – James Donnelly Jan 16 '14 at 09:11
  • Okay, I realized that your fiddle is different from your answer and without `setTimeout` it won't work. Please edit your answer and I'll accept it. The 'setTimeout' is crucial in this case. – Akos K Jan 16 '14 at 09:22
  • @akoskm ah sorry, I'd forgotten about that too! Slow morning...! – James Donnelly Jan 16 '14 at 09:24
  • This select2 Github issue may be related - ["Blur event fires at the wrong time with newer versions of jQuery"](https://github.com/ivaynberg/select2/issues/1545) – mnoble01 Feb 25 '14 at 17:22
  • whats the containing divider? – SuperUberDuper Jan 26 '15 at 16:01