Option name | Type | Description |
---|---|---|
el | Element | |
params | Object |
ToggleSwitch constructor.
var ToggleSwitch = function(el) {
if (!el) {
return;
}
this._cacheElements(el);
this._bindEventListenerCallbacks();
this._addEventListeners();
};
ToggleSwitch.prototype = {
Include common functionality.
_getElementMatchingParent: Base.getElementMatchingParent,
_getMatchingChild: Base.getMatchingChild,
remove: Base.remove,
Default values for internal properties we will be setting.
These are set on each construction so we don't leak properties
into the prototype chain.
defaults: {
el: null,
activate: null,
deactivate: null,
toggle: null,
input: null,
_onKeydownBound: null
},
Toggle the ToggleSwitch state.
toggle: function() {
// Check if input exists
if (!this.input) return;
// toggle checked property
if (this.input.checked)
this.deactivate();
else
this.activate();
},
Activate toggle state
activate: function() {
// Check if input exists
if (!this.input) return;
this.input.checked = true;
},
Deactivate toggle state
deactivate: function() {
// Check if input exists
if (!this.input) return;
this.input.checked = false;
},
Option name | Type | Description |
---|---|---|
el | Element |
Store a reference to the element.
_cacheElements: function(el) {
this.el = el;
this.input = el.querySelector('.spark-toggle__input');
},
Create bound versions of event listener callbacks and store them.
Otherwise we can't unbind from these events later because the
function signatures won't match.
_bindEventListenerCallbacks: function() {
this._onKeydownBound = this._onKeydown.bind(this);
},
Add event listeners for DOM events.
_addEventListeners: function() {
this.el.addEventListener('keydown', this._onKeydownBound);
},
Remove event listeners for DOM events..
_removeEventListeners: function() {
this.el.removeEventListener('keydown', this._onKeydownBound);
},
Option name | Type | Description |
---|---|---|
e | Object |
When the space or enter key is pressed on the toggle, toggle!
_onKeydown: function(e) {
if (!this._getElementMatchingParent(e.target, '.spark-toggle-switch, spark-toggle-switch__handle', this.el)) {
return;
}
var code = e.keyCode || e.which;
switch (code) {
case 32:
// space
// Skip, native works as expected
break;
case 13:
// enter
e.preventDefault();
this.toggle();
break;
case 39:
case 40:
// right
// down
e.preventDefault();
this.activate();
break;
case 37:
case 38:
// left
// up
e.preventDefault();
this.deactivate();
break;
}
}
};
Base.exportjQuery(ToggleSwitch, 'ToggleSwitch');
return ToggleSwitch;
}));