Better Dropdowns
HTML
<dropdown>
<currentitem>Choose an option</currentitem>
<items>
<item>Option #1 areyatryaeyaethyaetyaertaar art a</item>
<item>Choose an optioni</item>
<item>Option #3</item>
<item>Choose an optionnr</item>
<item>Option #2</item>
<item>Option #3</item>
<item>Option #4</item>
</items>
</dropdown>
<dropdown>
<currentitem>Choose an option</currentitem>
<items>
<item>Option #1 areyatryaeyaethyaetyaertaar art a</item>
<item>Choose an option</item>
<item>Option #3</item>
<item>Choose an optionnr</item>
<item>Option #2</item>
<item>Option #3</item>
<item>Option #4</item>
</items>
</dropdown>
CSS
dropdown {
box-sizing: border-box;
display: inline-block;
font-family: Arial, Helvetica, sans-serif;
position: relative;
-webkit-user-select: none;
}
currentItem {
background: #f6fde4;
border: 1px solid #888;
border-radius: 20px;
box-sizing: border-box;
cursor: pointer;
display: block;
overflow: hidden;
padding: 0.4em 1.2em;
position: relative;
text-align: center;
text-overflow: ellipsis;
white-space: nowrap;
word-wrap: break-word;
}
currentItem:hover {
background: #e8f7e0;
outline: none;
}
currentItem::after {
border-right: 0.2em solid transparent;
border-left: 0.2em solid transparent;
border-top: 0.4em solid black;
content:"";
position: absolute;
top: calc((100% - 0.4em) / 2);
right: 0.5em;
}
items {
background: #f6fde4;
border: 1px solid #888;
border-radius: 6px;
box-sizing: border-box;
display: none;
overflow: hidden;
position: absolute;
text-align: center;
width: 100%;
}
item {
cursor: pointer;
display: block;
padding: 0.3em 0.5em;
word-wrap: break-word;
}
item:not(.activeItem):hover {
background: #e9fabe;
}
item.activeItem {
box-shadow: inset 0 0 5px 0 #614;
}
JavaScript
var width = $('currentItem').outerWidth();
$('dropdown').css('width', width + 1);
$().val = function() {
return $(this).find('currentitem').text();
};
console.log($().val);
$('currentItem').click(function (e) {
e.stopPropagation();
$(this).next('items').stop().slideToggle();
});
$('item').click(function (e) {
e.stopPropagation();
$(this).siblings('.activeItem').removeClass('activeItem');
$(this).addClass('activeItem');
var text = $(this).text();
$(this).parents('items').stop().slideUp();
$(this).parents('items').prev('currentItem').text(text);
console.log($(this).parents('dropdown').val());
});
$(':not(dropdown *)').click(function () {
var visibleDropdown = $('dropdown items').filter(function(i, item) { return $(item).is(':visible'); })
if (!visibleDropdown.length) return false;
$(visibleDropdown).stop().slideUp();
});