I’m trying to build a select-box like custom dropdown that should close whenever I click on the rest of the page or on another dropdown. Just like you would expect it.
The way I’m currently doing that is by is by giving every dropdown an id so I can store it in a variable and check if its the current one or not.
My html:
<div class="select width210" id="sortby1">
<ul>
<li class="option darr" title="oDisplay">show all</li>
<li class="option" title="all">show all</li>
<li class="option" title="published">published only</li>
<li class="option" title="unpublished">private only</li>
</ul>
</div>
My JS:
var currentSelectDiv = null;
$('.select ul li.option').click(function(e) {
//storing the id attribute
currentSelectDiv = $(this).parents("div.select").attr("id");
selectedOption = $(this).parents("div.select").find(".option:first");
console.log($(this));
$(this).siblings().show();//.removeClass('darr');
//$(this).addClass('darr');
selectedOption.text($(this).text()).attr("title",this.title);
});
$('.select ul li.option:not(".darr")').click(function(e) {
$(this).parents("div.select").find(".option:not('.darr')").hide();
});
$(document).click(function(e) {
$('.select ul li.option').each(function() {
// check IDs to make sure only closing other lis
if( $(this).parents("div.select").attr("id") !=
currentSelectDiv) {
if ( !$(this).is(":hidden" ) ) {
$(this).not('.darr').hide();
}
}
});
currentSelectDiv = null;
});
This works rather fine actually. I have just two BIG problems.
First, I need to have this working without id’s. Just because I’m using this dropdown in recurring dynamic elements on my page so there are multiple instances of the same id. Therefore my code doesn’t work anymore and an id should of course be unique.
Second thing: I have no clue how to listen for the actual “select” of an option. So imagine I want to console.log() the title of the option I clicked on. I’m just able to listen to every click on a option, but actually the selection of an option is only every second click.
Here is the example: http://jsfiddle.net/wRjBY/ So right now it works fine because both elements have a different id.
Any idea how to solve those two things?
New Code
I’ve… somewhat revamped the code. This should get you there.