Last active
December 14, 2015 07:49
-
-
Save pzi/5053815 to your computer and use it in GitHub Desktop.
This script provides a workaround to apply custom style to a SELECT element. It dynamically wraps the targeted SELECT in a DIV and adds a SPAN element positioned absolutely after/below the SELECT element. This SPAN element then gets the selected option text. The SELECT will get opacity set to zero, so it is not visible but clickable. Since the S…
This file contains hidden or 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
$.fn.customSelect = -> | |
$(this).filter('select').each (i) -> | |
$select = $(this) | |
# make sure we only apply once, no matter how many times called with the same selector | |
return if $select.data('customSelect') | |
$select.data('customSelect', true) | |
title = $select.find('option:first').text() | |
$label = $("label[for="+ $select.attr("id") + "]") | |
$select.wrap "<div class='custom-select'/>" | |
$selectWrap = $select.parent('.custom-select') | |
if $('option:selected', this).val() != '' | |
title = $('option:selected', this).text() | |
$select | |
.css({ | |
'height': $select.parent().outerHeight(), | |
'top': parseInt($select.parent().css("borderTopWidth")) * -1 # need to factor in borders | |
}) | |
.after('<span>' + title + '</span>') | |
.change(-> | |
$('option', this).not(':selected').each -> | |
$(this).removeAttr('selected') | |
$('option:selected', this).attr('selected', 'selected') | |
val = $('option:selected', this).text() | |
$select.next().text(val) | |
) | |
$label.addClass($select.attr("id")) | |
$selectWrap | |
.attr('id', 'custom-' + $select.attr("id")) | |
.hover (-> | |
$(this).toggleClass "hover" | |
) | |
$select.bind("updateState", -> | |
).trigger("updateState").click(-> | |
$(this).trigger "updateState" | |
).focus(-> | |
$selectWrap.addClass "focus" | |
).blur -> | |
$selectWrap.removeClass "focus" | |
return $select | |
$ -> | |
$("#foo").customSelect() |
This file contains hidden or 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
.custom-select | |
background: #fff | |
border: 1px solid #ccc | |
cursor: pointer | |
display: inline-block | |
height: 30px | |
padding: 5px | |
position: relative | |
width: 155px | |
&.focus | |
+box-shadow(0 0 15px rgb(25, 75, 125)) | |
select | |
+appearance(none) | |
border: 0 none | |
cursor: pointer | |
left: 0 | |
+opacity(0) | |
position: absolute | |
top: 0 | |
z-index: 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Needs to cater for disabled state of a
select