Bootstrap Tri-state Toggle

by Erik Bartlow

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<div class="tri-switch"></div>
<div class="tri-switch2"></div>

CSS

.container {
    margin: 50px;
}

JavaScript

(function($) {

    var namespace = "tri.triswitch";

    if (!$.tri) {
        $.tri = new Object();
    }

    $.tri.triswitch = function(el, options) {
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;

        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el;
        base.options = $.extend({}, $.tri.triswitch.defaultOptions, options);

        // Sample Function, Uncomment to use
        base.getSelectedValue = function() {
            return base.options.selectedValue;
        };

        base.clickEventOverride = function(value, callback) {
            var that = base;
            ButtonStateClickEvent.call(that, value);
            if (callback) {
                callback();
            }
        };
    };

    function ButtonStateClickEvent(value) {
        var that = this;
        if (that.options.selectedValue != value) {
            that.$el.find('.' + that.options.defaultSelectedCssClass).removeClass(that.options.defaultSelectedCssClass);
            that.options.selectedValue = value;
            $.each(that.options.values, function(index, item) {
                item.selected = (item.value == value);
                if (item.selected) {
                    that.$el.find('button:contains("' + item.text + '")').each(function(index, i) {
                        if ($(i).text() == item.text) {
                            $(i).removeClass(item.class);
                            $(i).addClass(that.options.defaultSelectedCssClass);
                        }
                    });
                } else {
                    that.$el.find('button:contains("' + item.text + '")').each(function(index, i) {
                        if ($(i).text() == item.text)
                            $(i).addClass(item.class);
                    });
                }
            });
        }
    }

    function...