I have recently worked on a project that uses the excellent zelect-library for dropdowns.
There was a requirement to take out the search box on the list. There might be several ways to tackle this, but here is what I came up with.
My first thought was to simply hide it by setting search box element to display:none; In fact, this does hide the search box.
input.zearch{ display:none; }
However, this brings up a problem. Zelect uses blur-event of the zearch-input to sense that user has clicked and dropdown should be closed. When zearch-input is set to display: none, it doesn't get rendered, which means it won't get focus. This means blur-event doesn't fire when user clicks outside dropdown. This can be remedied by catching click-events on page. Then we can check that user clicks outside zelect-list by checking that the target is not zelect.
$(document).click(function(e){
if(!$(e.target).hasClass('zelected')){
$('.dropdown').hide()
$('.zelect').removeClass('open')
}
})
This could already be enough for many cases, but it does have a corner case if more than one zelect-lists are contained on the page. Opening new list while one is already open, leaves both open.
A way to handle this is to check that if clicking on zelect-list, close other zelect lists.
$(document).click(function(e){
var isZelect = $(e.target).hasClass('zelected')
if(isZelect){
closeOtherZelects($(e.target))
}
else{
$('.dropdown').hide()
$('.zelect').removeClass('open')
}
})
function closeOtherZelects(element){
var zelects = $('.zelected')
for (var i = zelects.length - 1; i >= 0; i--) {
if(!element.is(zelects[i])) {
currentZelect = $(zelects[i])
currentZelect.siblings('.dropdown').hide()
currentZelect.parent('.zelect').removeClass('open')
}
}
}
Voilá! Now we have maximum of one dropdown open at a given time. This functionality can still break if some other code on the page messes with global click-handlers. It probably won't become a problem once we are aware of it.
Software professional with a passion for quality. Likes TDD and working in agile teams. Has worked with wide-range of technologies, backend and frontend, from C++ to Javascript. Currently very interested in functional programming.