Skip to content

Instantly share code, notes, and snippets.

@willbroderick
Last active May 22, 2018 14:32
Show Gist options
  • Save willbroderick/158d2c3b894440408770 to your computer and use it in GitHub Desktop.
Save willbroderick/158d2c3b894440408770 to your computer and use it in GitHub Desktop.
Turn a <select> tag into a list of clickable boxes that behave like radio buttons.
.clickyboxes {
margin: 0.4em 0 1em;
padding: 0;
li {
display: inline;
vertical-align: top;
a {
display: inline-block;
margin: 0 10px 5px 0;
padding: 4px 10px;
border: 1px solid transparent;
border-radius: 3px;
vertical-align: top;
&.active, &.active:hover {
border-color: #999;
background: #fff;
color: #333;
}
&:hover {
color: inherit;
background: #eee;
}
}
}
}
/// Turn a <select> tag into clicky boxes
// Use with: $('select').clickyBoxes()
$.fn.clickyBoxes = function(prefix){
return $(this).filter('select:not(.replaced)').addClass('replaced').each(function(){
//Make sure rows are unique
var prefix = prefix || $(this).attr('id');
//Create container
var $optCont = $('<ul class="clickyboxes"/>').attr('id', 'clickyboxes-'+prefix).data('select', $(this)).insertAfter(this);
var $label;
if($(this).is('[id]')) {
$label = $('label[for="' + $(this).attr('id') + '"]'); // Grab real label
} else {
$label = $(this).siblings('label'); // Rough guess
}
if($label.length > 0) {
$optCont.addClass('options-' + $label.html().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-+/g, '-').replace(/-*$/, ''));
}
//Add options to container
$(this).find('option').each(function(){
$('<li/>').appendTo($optCont).append(
$('<a href="#"/>').attr('data-value', $(this).val()).html($(this).html())
.addClass('opt-' + $(this).text().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-+/g, '-').replace(/-*$/, ''))
);
});
//Select change event
$(this).hide().addClass('replaced').on('change keyup', function(){
//Choose the right option to show
$optCont.find('a').removeClass('active').filter('[data-value="'+$(this).val()+'"]').addClass('active');
}).trigger('keyup'); //Initial value
//Button click event
$optCont.on('click', 'a', function(){
e.preventDefault();
if(!$(this).hasClass('active')) {
var $clicky = $(this).closest('.clickyboxes');
$clicky.data('select').val($(this).data('value')).trigger('change');
$clicky.trigger('change');
}
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment