Last active
April 6, 2018 16:30
-
-
Save philfreo/4afbf63f486a772c4a4c to your computer and use it in GitHub Desktop.
Give a <select> element a different look, but still retain all OS benefits of using a real <select> (full screen height options list, keyboard navigation, etc.)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Make faux dropdowns show their new value, when it's changed. | |
$(document.body).on('change', '.faux-select-wrapper select', function(e) { | |
var select = $(e.target); | |
$.fn.fauxSelect.refresh(select); | |
}); | |
$.fn.fauxSelect = function(method) { | |
var select = this; | |
// if fauxSelect is being called again on an already-handled element, then just update the | |
// visible text | |
if (select.parent().is('.faux-select-wrapper')) { | |
$.fn.fauxSelect.refresh(select); | |
return; | |
} | |
var wrapper = $('<div class="faux-select-wrapper">'); | |
var chosen = select.find('option:selected'); | |
if (!chosen.length) chosen = select.find('option:first'); | |
var fake = $('<div class="faux-select">').text(chosen.text()).appendTo(wrapper); | |
['font', 'color'].forEach(function(prop) { | |
fake.css(prop, select.css(prop)); | |
}); | |
fake.css('line-height', (select.height() - 1) + 'px'); | |
fake.height(select.outerHeight()); | |
fake.width(select.outerWidth()); | |
select.before(wrapper).appendTo(wrapper); | |
}; | |
$.fn.fauxSelect.refresh = function(select) { | |
var wrapper = select.parent(), | |
fake = wrapper.find('.faux-select'); | |
fake.text(select.find('option:selected').text()); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.faux-select-wrapper { | |
position: relative; | |
select { | |
opacity: 0; | |
} | |
.faux-select { | |
display: block; | |
position: absolute; | |
top: 0; | |
color: #555; | |
padding-left: 8px; | |
.box-sizing(border-box); | |
border: solid 1px #ddd; | |
border-radius: 5px; | |
background: white; | |
pointer-events: none; | |
overflow: hidden; | |
&:active { | |
border-color: blue; | |
} | |
&::before { | |
content: '▾'; | |
float: right; | |
margin-right: 5px; | |
color: #999; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment