Skip to content

Commit 1afffb0

Browse files
committed
improved blur tracking. closes select2#2
1 parent f6eb1ed commit 1afffb0

1 file changed

Lines changed: 14 additions & 20 deletions

File tree

select2.js

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,7 @@
2020
"use strict";
2121
/*global document, window, jQuery, console */
2222

23-
var uid = 0, KEY;
24-
25-
KEY = {
23+
var KEY = {
2624
TAB: 9,
2725
ENTER: 13,
2826
ESC: 27,
@@ -144,6 +142,18 @@
144142
return width;
145143
}
146144

145+
/**
146+
* blurs any Select2 container that has focus when an element outside them was clicked or received focus
147+
*/
148+
$(document).ready(function () {
149+
$(document).on("mousedown focusin", function (e) {
150+
var target = $(e.target).closest("div.select2-container").get(0);
151+
$(document).find("div.select2-container-active").each(function () {
152+
if (this !== target) $(this).data("select2").blur();
153+
});
154+
});
155+
});
156+
147157
/**
148158
*
149159
* @param opts
@@ -161,9 +171,6 @@
161171
AbstractSelect2.prototype.init = function (opts) {
162172
var results, search;
163173

164-
this.uid = uid;
165-
uid = uid + 1;
166-
167174
// prepare options
168175
this.opts = this.prepareOpts(opts);
169176

@@ -333,21 +340,13 @@
333340

334341
this.alignDropdown();
335342
this.dropdown.show();
336-
337-
// register click-outside-closes-dropdown listener
338-
$(document).on("click.id" + this.uid, this.bind(function (e) {
339-
if ($(e.target).closest(this.container).length === 0) {
340-
this.blur();
341-
}
342-
}));
343343
};
344344

345345
AbstractSelect2.prototype.close = function () {
346346
if (!this.opened()) return;
347347

348348
this.dropdown.hide();
349349
this.container.removeClass("select2-dropdown-open");
350-
$(document).off("click.id" + this.uid);
351350

352351
if (this.select) {
353352
// TODO see if we can always clear here and reset on open
@@ -439,7 +438,7 @@
439438
more = results.find("li.select2-more-results"),
440439
below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
441440
offset = -1, // index of first element without data
442-
page = this.resultsPage+1;
441+
page = this.resultsPage + 1;
443442

444443
if (more.length === 0) return;
445444

@@ -835,11 +834,6 @@
835834
}
836835
}
837836

838-
if (e.which === KEY.TAB) {
839-
this.blur();
840-
return;
841-
}
842-
843837
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
844838
return;
845839
}

0 commit comments

Comments
 (0)