0

hey guys, I'm trying to build a simple custom select box with jquery.

html:

<div class="select">
    <ul>
        <li class="option darr">Dropdown one</li>
        <li class="option">Dropdown two</li>
        <li class="option">Dropdown three</li>
    <ul>
</div>

jquery:

$('.select ul li.option').click(function() {
    $(this).siblings().toggle().removeClass('darr');
    $(this).addClass('darr');
})

You can check out the working example right here: http://jsfiddle.net/WFTvq/2/

This works fine actually, however there is one little thing that bugs me. When I click on the custom select field all options are shown. If I do not choose one of the options and click anywhere else on the window the dropdown does not collapse autamatically.

A normal select box would collapse if I click anywhere else on the screen, how could I implement that behaviour in my example?

Thank you

h

Hussein
  • 42,480
  • 25
  • 113
  • 143
matt
  • 42,713
  • 103
  • 264
  • 397

1 Answers1

1

Answered a similar question at Make a search menu disappear when the search field loses focus, but still allow user to click on links

You can detect when a mouse is clicked outside by doing

$(document).click(function(){
   ...
});

Full code for your example

$('.select ul li.option').click(function(e) {
    e.stopPropagation();
    $(this).siblings().toggle().removeClass('darr');
    $(this).addClass('darr');
});


$(document).click(function() {
    $('.select ul li.option').siblings().not('.darr').css('display', 'none');
});

Check working example at http://jsfiddle.net/WFTvq/3/

Community
  • 1
  • 1
Hussein
  • 42,480
  • 25
  • 113
  • 143