Reputation: 910
Can I customize this plugin so that on clicking any other place in document except selectbox - its close? I try to add click event for body tag, but it seems dont work..
html
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>
css
.selectbox {
width: 100px;
border: 1px solid #000;
padding: 2px 5px;
}
.list {
background-color: #eee;
border: 1px #ddd solid;
padding: 0;
position: absolute;
list-style: none;
width: 100%;
}
.list li:hover {
color: #fff;
background-color: #00f;
}
js
! function(t) {
return t.fn.selectbox = function(e) {
var i;
return i = t.extend({
customList: !1
}, e), this.each(function() {
var e, n, s, c;
return s = t(this).css({
opacity: 0,
position: "absolute",
"z-index": 2,
top: 0,
width: "100%",
height: "100%"
}), i.customList && (n = s.children()), c = s.wrap("<div class='selectbox'></div>").parent().css({
position: "relative"
}), c.append("<span class='value'>" + s.val() + "</span>"), i.customList && (s.hide(), e = c.append("<ul class='list'></ul>").find("ul"), n.each(function() {
return e.append("<li>" + this.text + "</li>")
}), e.hide()), s.on("change", function() {
return c.children(".value").text(t(this).val()), !1
}), i.customList && (c.click(function() {
return e.toggle(), !1
}), e.children().click(function() {
return e.toggle(), s.val(n.eq(e.children().index(this)).attr("value")).trigger("change"), !1
})), t(this)
})
}, !1
}(jQuery);
and with this code hook up plugin
$('select').selectbox({customList: true});
Here is JsFiddle DEMO
Upvotes: 0
Views: 78
Reputation: 15802
You can listen to the document
on clicks and just hide the .selectbox ul
tags. Since the <select>
naturally eats the click event to stop it bubbling up to the document, you don't need to worry about checking where the event's come from - you know it's not come from the selectbox.
Generally you should be very leery of binding event handlers to the document, but since this shouldn't ever get called too often (click) is a relatively infrequent event), you should be fine.
This should work:
(function($) {
$(document).on('click', function(e) {
$('.selectbox').find('ul').hide();
});
})(jQuery);
Upvotes: 1