Skip to content

Commit d92a572

Browse files
committed
close on scroll and resize. fixes select2#149
1 parent 921bf06 commit d92a572

1 file changed

Lines changed: 32 additions & 16 deletions

File tree

select2.js

Lines changed: 32 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -433,21 +433,6 @@
433433
});
434434
});
435435

436-
/**
437-
* Closes any opened Select2s when the window is resized
438-
*/
439-
$(window).resize(debounce(100, function() {
440-
$(".select2-container.select2-dropdown-open").select2('close');
441-
}));
442-
443-
/**
444-
* Closes any opened Select2s when the window is scrolled
445-
*/
446-
$(window).scroll(debounce(100, function() {
447-
$(".select2-container.select2-dropdown-open").select2('close');
448-
}));
449-
450-
451436
/**
452437
* Creates a new class
453438
*
@@ -491,6 +476,9 @@
491476
this.enabled=true;
492477
this.container = this.createContainer();
493478

479+
this.containerId="s2id"+nextUid();
480+
this.container.attr("id", this.containerId);
481+
494482
// cache the body so future lookups are cheap
495483
this.body = thunk(function() { return opts.element.closest("body"); });
496484

@@ -873,6 +861,27 @@
873861
*/
874862
// abstract
875863
opening: function() {
864+
var cid = this.containerId, selector = "#"+ cid,
865+
scroll = "scroll." + cid, resize = "resize." + cid;
866+
867+
this.container.parents().each(function() {
868+
$(this).bind(scroll, function() {
869+
var s2 = $(selector);
870+
if (s2.length == 0) {
871+
$(this).unbind(scroll);
872+
}
873+
s2.select2("close");
874+
});
875+
});
876+
877+
$(window).bind(resize, function() {
878+
var s2 = $(selector);
879+
if (s2.length == 0) {
880+
$(window).unbind(resize);
881+
}
882+
s2.select2("close");
883+
});
884+
876885
this.clearDropdownAlignmentPreference();
877886

878887
if (this.search.val() === " ") { this.search.val(""); }
@@ -898,6 +907,13 @@
898907
close: function () {
899908
if (!this.opened()) return;
900909

910+
var self = this;
911+
912+
this.container.parents().each(function() {
913+
$(this).unbind("scroll." + self.containerId);
914+
});
915+
$(window).unbind("resize." + this.containerId);
916+
901917
this.clearDropdownAlignmentPreference();
902918

903919
this.dropdown.hide();
@@ -2138,7 +2154,7 @@
21382154
var args = Array.prototype.slice.call(arguments, 0),
21392155
opts,
21402156
select2,
2141-
value, multiple, allowedMethods = ["val", "destroy", "open", "close", "focus", "isFocused", "container", "onSortStart", "onSortEnd", "enable", "disable", "positionDropdown", "data"];
2157+
value, multiple, allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "onSortStart", "onSortEnd", "enable", "disable", "positionDropdown", "data"];
21422158

21432159
this.each(function () {
21442160
if (args.length === 0 || typeof(args[0]) === "object") {

0 commit comments

Comments
 (0)