Skip to content

Instantly share code, notes, and snippets.

@mankutila
Last active December 12, 2017 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mankutila/aa5cad9072ca2383836aae02594722e1 to your computer and use it in GitHub Desktop.
Save mankutila/aa5cad9072ca2383836aae02594722e1 to your computer and use it in GitHub Desktop.
Creates html `<select>` with custom styling
function initCustomSelects(selectors) {
$(selectors).each(function(){
var $this = $(this), numberOfOptions = $(this).children('option').length;
$this.addClass('select-hidden');
$this.wrap('<div class="select"></div>');
$this.after('<div class="select-styled"></div>');
var $styledSelect = $this.next('div.select-styled');
$styledSelect.text($this.children('option').eq(0).text());
var $list = $('<ul />', {
'class': 'select-options'
}).insertAfter($styledSelect);
for (var i = 0; i < numberOfOptions; i++) {
$('<li />', {
text: $this.children('option').eq(i).text(),
rel: $this.children('option').eq(i).val(),
dataReview: $this.children('option').eq(i).data('review')
}).appendTo($list);
}
var $listItems = $list.children('li');
$styledSelect.click(function(e) {
e.stopPropagation();
$('div.select-styled.active').not(this).each(function(){
$(this).removeClass('active').next('ul.select-options').hide();
});
$(this).toggleClass('active').next('ul.select-options').toggle();
});
$listItems.click(function(e) {
e.stopPropagation();
$styledSelect.text($(this).text()).removeClass('active');
$this.val($(this).attr('rel'));
$list.hide();
});
$(document).click(function() {
$styledSelect.removeClass('active');
$list.hide();
});
});
}
select.custom-select(name="someName", id="someId")
option(value="ABC") ABC
option(value="CBA") CBA
$background: #fff;
$select-color: #000;
$select-background: #fff;
$select-width: 100%;
$select-height: rem(35);
.select-hidden {
display: none;
visibility: hidden;
}
.select {
cursor: pointer;
display: inline-block;
vertical-align: top;
position: relative;
border: none;
font: 300 rem(24) $font;
color: #666;
padding: 0 rem(5);
width: $select-width;
height: $select-height;
}
.select-styled {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: $select-background;
padding: 0 rem(5);
border-bottom: 2px solid #666;
&:after {
content: '▼';
width: rem(9);
height: rem(12);
position: absolute;
top: rem(7);
right: rem(8);
font-size: rem(10);
}
&:active, &.active {
&:after {
transform: rotate(180deg);
}
}
}
.select-options {
display: none;
position: absolute;
top: 100%;
right: 0;
left: 0;
z-index: 999;
margin: 0;
padding: 0;
list-style: none;
background-color: #fff;
li {
margin: 0;
padding: rem(12) 0;
text-indent: rem(5);
border-top: 1px solid #666;
background-color: aliceblue;
&:before {
content: none;
}
&[rel="hide"] {
display: none;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment