Segment Control Plugin
by Shawn Wood
HTML
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="mySegmented"></div>
JavaScript
(function($) {
/**
* Create Segemented Control.
* @constructor
* @param {object} options - The options for the segmeneted control.
* @param {string} style - The style or styles to be applied to the selector.
*/
$.fn.segmentControl = function(options) {
// This is the easiest way to have default options.
var settings = $.extend({
// @param {array} items - An array of objects.
items: [{
"label": "Item 1",
"id": "item1",
"value": "item1"
},
{
"label": "Item 2",
"id": "item2",
"value": "item2"
},
{
"label": "Item 3",
"id": "item3",
"value": "item3"
}
],
selected: "item1", // selectedID
name: "option",
width: "304px", // 304px
colors: { // Colors being used for slider button
"control": {
"background": "#f4f4f4",
"border": "#ccc",
"color": "#000"
},
"slider": {
"background": "#FFF",
"border": "#ccc",
"color": "#000"
}
},
speed: ".4s", // Speed for the slide transition
onChange: function(data) {} // function to run on change
}, options);
// Sim
var itemArray = settings.items,
selectedItem = settings.selected,
itemName = settings.name,
selectedID = settings.selected,
controlColors = settings.colors,
thisElement = $(this),
thisID = $(this).attr('id');
// Create classes with styles and add to the head
function createClass(name, rules) {
var style = document.createElement('style');
style.type = 'text/css';
rulesArray = rules;
document.getElementsByTagName('head')[0].appendChild(style);
document.getElementsByTagName('head')[0].appendChild(style);
if (!(style.sheet || {}).insertRule)
(style.styleSheet || style.sheet).addRule(name, rules);
else
...