/** * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented * visually by a slider in the leftmost position. * * @example * // Toggle switches in the 'off' and 'on' position. * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget(); * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( { * value: true * } ); * * // Create a FieldsetLayout to layout and label switches * var fieldset = new OO.ui.FieldsetLayout( { * label: 'Toggle switches' * } ); * fieldset.addItems( [ * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ), * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } ) * ] ); * $( 'body' ).append( fieldset.$element ); * * @class * @extends OO.ui.ToggleWidget * @mixins OO.ui.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [value=false] The toggle switch’s initial on/off state. * By default, the toggle switch is in the 'off' position. */ OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) { // Parent constructor OO.ui.ToggleSwitchWidget.super.call( this, config ); // Mixin constructors OO.ui.TabIndexedElement.call( this, config ); // Properties this.dragging = false; this.dragStart = null; this.sliding = false; this.$glow = $( '' ); this.$grip = $( '' ); // Events this.$element.on( { click: this.onClick.bind( this ), keypress: this.onKeyPress.bind( this ) } ); // Initialization this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' ); this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' ); this.$element .addClass( 'oo-ui-toggleSwitchWidget' ) .attr( 'role', 'checkbox' ) .append( this.$glow, this.$grip ); }; /* Setup */ OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget ); OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.TabIndexedElement ); /* Methods */ /** * Handle mouse click events. * * @private * @param {jQuery.Event} e Mouse click event */ OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) { if ( !this.isDisabled() && e.which === 1 ) { this.setValue( !this.value ); } return false; }; /** * Handle key press events. * * @private * @param {jQuery.Event} e Key press event */ OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.setValue( !this.value ); return false; } };