Skip to content

Instantly share code, notes, and snippets.

@taufik-nurrohman
Last active June 7, 2021 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taufik-nurrohman/6cd2422017f7baf1c745addcabaf3981 to your computer and use it in GitHub Desktop.
Save taufik-nurrohman/6cd2422017f7baf1c745addcabaf3981 to your computer and use it in GitHub Desktop.
A custom select box draft to be used on Mecha’s control panel extension.
<!DOCTYPE html>
<meta charset="utf-8">
<title>Accessible Custom Select Box by Taufik Nurrohman</title>
<!--onsele
The MIT License (MIT)
Copyright © 2021 Taufik Nurrohman <https://github.com/taufik-nurrohman>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->
<style>
:root {
font: normal normal 16px/1.2 serif;
background: white;
color: black;
}
</style>
<style>
.select {
position: relative;
background: white;
color: black;
border: 1px solid;
font: inherit;
display: inline-block;
vertical-align: middle;
width: 12em;
padding: .5em .75em;
cursor: pointer;
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
-webkit-tap-highlight-color: transparent;
}
.select,
.select * {
box-sizing: border-box;
}
.select[disabled],
.select.disabled {
color: gray;
cursor: not-allowed;
}
.select:focus {
outline: 0;
border-color: blue;
box-shadow: 0 0 0 3px rgba(0, 0, 255, .25);
}
.select *:focus {
outline: 0;
}
.select.js::after {
content: "";
width: 0;
height: 0;
border-top: 6px solid;
border-right: 5px solid transparent;
border-bottom: 0;
border-left: 5px solid transparent;
position: absolute;
top: 50%;
margin-top: -3px;
right: .5em;
pointer-events: none;
}
.select.js.open::after {
border-top: 0;
border-bottom: 6px solid;
}
.select.js > b {
display: block;
font: inherit;
margin-right: 1em;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.select.js > div {
position: fixed;
z-index: 9999;
background: inherit;
border: inherit;
box-shadow: 0 1px 2px rgba(0, 0, 0, .4);
overflow: auto;
display: none;
}
.select.js > div.up {
}
.select[size] + .select.js {
height: auto;
}
.select[size] + .select.js::after {
display: none;
}
.select[size] + .select.js > b {
margin: 0;
}
.select[size] + .select.js > div {
display: block;
position: relative;
z-index: 1;
background: none;
border-width: 0;
border-top-width: inherit;
box-shadow: none;
margin: .5em -.75em -.5em;
padding: 0;
}
.select.js > div a {
display: block;
padding: .25em .5em;
font: inherit;
color: inherit;
cursor: pointer;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.select.js > div a:hover,
.select.js > div a.focused {
background: blue;
color: white;
}
.select.js > div span {
display: block;
padding: .25em .5em;
}
.select.js > div span[title]::before {
content: attr(title);
display: block;
margin: 0 0 .25em;
font-weight: bold;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.select.js > div span a {
padding-left: 1.5em;
margin: 0 -.5em;
}
.select.js > div a.disabled {
color: gray;
cursor: not-allowed;
}
.select.js > div a.disabled:hover,
.select.js > div a.disabled.focused {
background: gray;
color: white;
}
.select.js > div a.selected {
color: blue;
}
.select.js > div a.selected:hover,
.select.js > div a.selected.focused {
background: blue;
color: white;
}
.select.js.open > div {
display: block;
}
.select.select-source {
position: fixed;
top: -1px;
left: -1px;
width: 1px;
height: 1px;
background: none;
border: 0;
outline: 0;
font-size: 0;
overflow: hidden;
opacity: 0;
}
</style>
<p>
<label>
<input onchange="this.checked ? setSelectBoxesFake() : letSelectBoxesFake();" type="checkbox">
<span>Enable Custom Select Box</span>
</label>
</p>
<hr>
<form method="get">
<p>
<input name="input-1" type="text">
</p>
<p>
<select class="select" name="select-1">
<option>Red</option>
<option value="1">Green</option>
<option value="2">Blue</option>
<option disabled>Disabled</option>
</select>
</p>
<p>
<select class="select" name="select-2">
<option value="#000">Black (not in group)</option>
<optgroup label="Group 1">
<option value="#fff">White (in group)</option>
</optgroup>
<optgroup label="Group 2">
<option>Red</option>
<option value="1">Green</option>
<option value="2" selected>Blue</option>
<option disabled>Disabled</option>
</optgroup>
<option value="3">A very very very very very very very very very very very long value.</option>
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
<option>Item 4</option>
<option>Item 5</option>
<option>Item 6</option>
<option>Item 7</option>
<option>Item 8</option>
<option>Item 9</option>
</select>
<br>
<small>Description goes here.</small>
</p>
<p>
<select class="select" disabled name="select-3">
<option>Test 1</option>
<option selected>Test 2</option>
<option>Test 3</option>
</select>
</p>
<p>
<select class="select" name="select-4" size="4">
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
<option>Item 4</option>
<option>Item 5</option>
<option>Item 6</option>
<option>Item 7</option>
<option>Item 8</option>
<option>Item 9</option>
</select>
</p>
<p>
<input name="input-2" type="text">
</p>
<p>
<button type="submit" name="button-1" value="true">Submit</button>
<button type="reset">Reset</button>
</p>
</form>
<script>
function trigger(node, eventName) {
node.dispatchEvent(new Event(eventName, {
cancellable: true
}));
}
function getStyle(node, property) {
return W.getComputedStyle(node).getPropertyValue(property);
}
function getSelectBox(selectBoxFake) {
return selectBoxFake.previousElementSibling;
}
function getSelectBoxFake(selectBox) {
return selectBox.nextElementSibling;
}
function getSelectBoxFakeDropDown(selectBoxFake) {
return selectBoxFake.children[1];
}
function getSelectBoxFakeLabel(selectBoxFake) {
return selectBoxFake.children[0];
}
function getSelectBoxFakeOptions(selectBoxFake) {
return [...getSelectBoxFakeDropDown(selectBoxFake).querySelectorAll('a')];
}
function getSelectBoxFakeOptionByIndex(selectBoxFakeOptions, index) {
return selectBoxFakeOptions.length && selectBoxFakeOptions.find(selectBoxFakeOption => {
return index === selectBoxFakeOption._index;
});
}
function getSelectBoxFakeOptionByValue(selectBoxFakeOptions, value) {
return selectBoxFakeOptions.length && selectBoxFakeOptions.find(selectBoxFakeOption => {
return value === selectBoxFakeOption._value;
});
}
function letSelectBoxFake(selectBox) {
selectBox.removeEventListener('focus', onSelectBoxFocus);
selectBox.removeEventListener('change', onSelectBoxChange);
selectBox.removeEventListener('input', onSelectBoxInput);
if (selectBox.classList.contains('select-source')) {
selectBox.classList.remove('select-source');
let selectBoxFake = getSelectBoxFake(selectBox);
selectBoxFake.removeEventListener('blur', onSelectBoxFakeBlur);
selectBoxFake.removeEventListener('click', onSelectBoxFakeClick);
selectBoxFake.removeEventListener('focus', onSelectBoxFakeFocus);
selectBoxFake.removeEventListener('keydown', onSelectBoxFakeKeyDown);
selectBoxFake.textContent = "";
selectBoxFake.remove();
}
}
function setSelectBoxFake(selectBox) {
let selectBoxFake = D.createElement('div'),
selectBoxFakeLabel = D.createElement('b'),
selectBoxValue = selectBox.value,
selectBoxTitle = selectBox.title,
selectBoxOptionIndex = 0,
selectBoxItems = selectBox.children;
selectBoxFake.className = selectBox.className;
selectBoxFake.classList.add('js');
if (selectBoxTitle) {
selectBoxFake.title = selectBoxTitle;
}
// if (!selectBoxValue && selectBox.options[0]) {
// selectBoxValue = selectBox.options[0].value; // Set default value to the first option value
// }
selectBoxFakeLabel.textContent = '\u200c';
selectBoxFake.append(selectBoxFakeLabel);
selectBox.parentNode.insertBefore(selectBoxFake, selectBox.nextElementSibling);
selectBox.classList.add('select-source');
function setSelectBoxFakeOptions(selectBoxItem, parent) {
function onSelectBoxFakeOptionBlur() {
this.classList.remove('focus');
}
function onSelectBoxFakeOptionClick(e) {
let selectBoxFakeOption = this,
selectBoxValuePrevious = selectBoxValue;
selectBoxValue = selectBoxFakeOption._value;
selectBoxFakeLabel.textContent = selectBoxFakeOption.textContent;
getSelectBoxFakeOptions(selectBoxFake).forEach(selectBoxFakeOption => {
selectBoxFakeOption.classList.toggle('selected', selectBoxValue === selectBoxFakeOption._value);
});
e.isTrusted && selectBoxFake.focus();
if (selectBoxValue !== selectBoxValuePrevious) {
selectBox.value = selectBoxValue;
trigger(selectBox, 'input'); // `input` must come first
trigger(selectBox, 'change');
}
e.preventDefault();
}
function onSelectBoxFakeFocus() {
this.classList.add('focus');
}
if ('optgroup' === selectBoxItem.tagName.toLowerCase()) {
let selectBoxFakeOptionGroup = D.createElement('span'),
selectBoxItems = selectBoxItem.children;
selectBoxFakeOptionGroup.title = selectBoxItem.label;
for (let i = 0, j = selectBoxItems.length; i < j; ++i) {
setSelectBoxFakeOptions(selectBoxItems[i], selectBoxFakeOptionGroup);
}
parent.append(selectBoxFakeOptionGroup);
return;
}
let selectBoxFakeOption = D.createElement('a'),
selectBoxOptionValue = selectBoxItem.getAttribute('value'),
selectBoxOptionText = selectBoxItem.textContent;
selectBoxOptionValue = selectBoxOptionValue || selectBoxOptionText;
selectBoxFakeOption.tabIndex = -1;
selectBoxFakeOption.textContent = selectBoxOptionText;
selectBoxFakeOption.title = selectBoxOptionText;
selectBoxFakeOption._index = selectBoxOptionIndex;
selectBoxFakeOption._value = selectBoxOptionValue;
selectBoxFakeOption.dataset.index = selectBoxOptionIndex;
selectBoxFakeOption.dataset.value = selectBoxOptionValue;
if (selectBoxItem.hasAttribute('disabled')) {
selectBoxFakeOption.classList.add('disabled');
} else {
selectBoxFakeOption.addEventListener('click', onSelectBoxFakeOptionClick, false);
}
parent.append(selectBoxFakeOption);
if (selectBoxOptionValue === selectBoxValue) {
selectBox.value = selectBoxValue;
selectBoxFakeLabel.textContent = selectBoxOptionText;
selectBoxFakeOption.classList.add('selected');
}
++selectBoxOptionIndex;
}
if (selectBox.disabled) {
selectBoxFake.classList.add('disabled');
} else {
selectBoxFake.tabIndex = 0;
selectBox.tabIndex = -1;
selectBoxFake.addEventListener('blur', onSelectBoxFakeBlur, false);
selectBoxFake.addEventListener('click', onSelectBoxFakeClick, false);
selectBoxFake.addEventListener('focus', onSelectBoxFakeFocus, false);
selectBoxFake.addEventListener('keydown', onSelectBoxFakeKeyDown, false);
}
if (selectBoxItems.length) {
let selectBoxFakeDropDown = D.createElement('div');
selectBoxFakeDropDown.tabIndex = -1;
selectBoxFake.append(selectBoxFakeDropDown);
for (let i = 0, j = selectBoxItems.length; i < j; ++i) {
setSelectBoxFakeOptions(selectBoxItems[i], selectBoxFakeDropDown);
}
if (selectBox.size) {
let selectBoxFakeOptions = getSelectBoxFakeOptions(selectBoxFake),
selectBoxFakeOption = getSelectBoxFakeOptionByIndex(selectBoxFakeOptions, 0),
heightMax = selectBoxFakeOption.offsetHeight * selectBox.size;
selectBoxFakeDropDown.style.maxHeight = heightMax + 'px';
}
}
selectBox.addEventListener('focus', onSelectBoxFocus, false);
selectBox.addEventListener('change', onSelectBoxChange, false);
selectBox.addEventListener('input', onSelectBoxInput, false);
if (selectBox.multiple) {
// TODO
}
if (selectBox.size) {
// Force open class
selectBoxFake.classList.add('open');
}
}
function setSelectBoxFakeOptionsPosition(selectBoxFake) {
let selectBox = getSelectBox(selectBoxFake),
selectBoxFakeDropDown = getSelectBoxFakeDropDown(selectBoxFake),
selectBoxFakeBorderTopWidth = W.parseInt(getStyle(selectBoxFake, 'border-top-width'), 10),
selectBoxFakeBorderBottomWidth = W.parseInt(getStyle(selectBoxFake, 'border-bottom-width'), 10);
if (!selectBox.size) {
let {height, left, top, width} = selectBoxFake.getBoundingClientRect(),
heightWindow = W.innerHeight,
heightMax = heightWindow - top - height;
selectBoxFakeDropDown.style.top = (top + height - selectBoxFakeBorderTopWidth) + 'px';
selectBoxFakeDropDown.style.bottom = "";
selectBoxFakeDropDown.style.left = left + 'px';
selectBoxFakeDropDown.style.width = width + 'px';
selectBoxFakeDropDown.style.maxHeight = heightMax + 'px';
if (heightMax < (heightWindow - height) / 2) {
heightMax = top;
selectBoxFakeDropDown.style.top = "";
selectBoxFakeDropDown.style.bottom = (heightWindow - top - selectBoxFakeBorderBottomWidth) + 'px';
selectBoxFakeDropDown.style.maxHeight = (heightMax + 1) + 'px';
selectBoxFakeDropDown.classList.add('up');
} else {
selectBoxFakeDropDown.classList.remove('up');
}
}
let selectBoxFakeOption = getSelectBoxFakeOptions(selectBoxFake).find(selectBoxFakeOption => {
return selectBoxFakeOption.classList.contains('selected');
});
if (selectBoxFakeOption) {
let height = selectBoxFakeOption.offsetHeight,
heightParent = selectBoxFakeDropDown.offsetHeight,
top = selectBoxFakeOption.offsetTop,
topScroll = selectBoxFakeDropDown.scrollTop;
if (top < topScroll) {
selectBoxFakeDropDown.scrollTop = top;
} else if (top + height - heightParent > topScroll) {
selectBoxFakeDropDown.scrollTop = top + height - heightParent;
}
}
}
function onSelectBoxFakeClickOutside(e) {
selectBoxesFake && selectBoxesFake.forEach(selectBoxFake => {
let selectBox = getSelectBox(selectBoxFake);
if (!selectBox.size && selectBoxFake !== selectBoxFakeCurrent) {
selectBoxFake.classList.remove('open');
}
});
}
function onSelectBoxFakeBlur(e) {
if (!selectBoxFakeCurrent) {
return;
}
this.classList.remove('focus');
selectBoxFakeCurrent = null;
}
function onSelectBoxFakeClick(e) {
let selectBoxFake = this,
selectBox = getSelectBox(selectBoxFake);
selectBoxFakeCurrent = selectBoxFake;
if (selectBox.size) {
selectBoxFake.classList.add('open');
return;
}
selectBoxFake.classList.toggle('open');
if (selectBoxFake.classList.contains('open')) {
setSelectBoxFakeOptionsPosition(selectBoxFake);
}
}
function onSelectBoxFakeFocus() {
let selectBoxFake = this,
selectBox = getSelectBox(selectBoxFake);
selectBoxFake.classList.add('focus');
selectBoxValue = selectBox.value;
selectBoxFakeCurrent = selectBoxFake;
}
function onSelectBoxFakeKeyDown(e) {
let key = e.key,
keyCode = e.keyCode,
selectBoxFake = this,
selectBox = getSelectBox(selectBoxFake),
selectBoxOptionIndex = selectBox.selectedIndex,
selectBoxFakeOptions = getSelectBoxFakeOptions(selectBoxFake),
selectBoxFakeOption = getSelectBoxFakeOptionByIndex(selectBoxFakeOptions, selectBoxOptionIndex),
open = selectBoxFake.classList.contains('open');
if ('ArrowDown' === key || 40 === keyCode) {
while (selectBoxFakeOption = getSelectBoxFakeOptionByIndex(selectBoxFakeOptions, ++selectBoxOptionIndex)) {
if (!selectBoxFakeOption.classList.contains('disabled')) {
break;
}
}
if (selectBoxFakeOption) {
trigger(selectBoxFakeOption, 'click');
selectBoxFake.classList.toggle('open', open);
}
e.preventDefault();
} else if ('ArrowUp' === key || 38 === keyCode) {
while (selectBoxFakeOption = getSelectBoxFakeOptionByIndex(selectBoxFakeOptions, --selectBoxOptionIndex)) {
if (!selectBoxFakeOption.classList.contains('disabled')) {
break;
}
}
if (selectBoxFakeOption) {
trigger(selectBoxFakeOption, 'click');
selectBoxFake.classList.toggle('open', open);
}
e.preventDefault();
} else if ('End' === key || 35 === keyCode) {
selectBoxOptionIndex = selectBox.options.length;
while (selectBoxFakeOption = getSelectBoxFakeOptionByIndex(selectBoxFakeOptions, --selectBoxOptionIndex)) {
if (!selectBoxFakeOption.classList.contains('disabled')) {
break;
}
}
if (selectBoxFakeOption) {
trigger(selectBoxFakeOption, 'click');
selectBoxFake.classList.toggle('open', open);
}
e.preventDefault();
} else if ('Enter' === key || 13 === keyCode) {
selectBoxFake.classList.toggle('open');
e.preventDefault();
} else if ('Escape' === key || 27 === keyCode) {
!selectBox.size && selectBoxFake.classList.remove('open');
// e.preventDefault();
} else if ('Home' === key || 36 === keyCode) {
selectBoxOptionIndex = -1;
while (selectBoxFakeOption = getSelectBoxFakeOptionByIndex(selectBoxFakeOptions, ++selectBoxOptionIndex)) {
if (!selectBoxFakeOption.classList.contains('disabled')) {
break;
}
}
if (selectBoxFakeOption) {
trigger(selectBoxFakeOption, 'click');
selectBoxFake.classList.toggle('open', open);
}
e.preventDefault();
} else if ('Tab' === key || 9 === keyCode) {
selectBoxFakeOption && trigger(selectBoxFakeOption, 'click');
!selectBox.size && selectBoxFake.classList.remove('open');
// e.preventDefault();
}
selectBoxFake.classList.contains('open') && setSelectBoxFakeOptionsPosition(selectBoxFake);
}
function onSelectBoxChange(e) {
onSelectBoxInput.call(this, e);
}
function onSelectBoxFocus(e) {
getSelectBoxFake(this).focus();
}
function onSelectBoxInput() {
let selectBox = this,
selectBoxValue = selectBox.value,
selectBoxFake = getSelectBoxFake(selectBox),
selectBoxFakeOptions = getSelectBoxFakeOptions(selectBoxFake);
// if (!selectBoxValue && selectBox.options[0]) {
// selectBoxValue = selectBox.options[0].value;
// }
let selectBoxFakeOption = getSelectBoxFakeOptionByValue(selectBoxFakeOptions, selectBoxValue);
selectBoxFakeOption && trigger(selectBoxFakeOption, 'click');
}
function onSelectBoxFormReset() {
W.setTimeout(() => selectBoxes.length && selectBoxes.forEach(selectBox => trigger(selectBox, 'input')), 1);
}
function onSelectBoxWindowResize() {
if (!selectBoxesFake) return;
selectBoxesFake.length && selectBoxesFake.forEach(selectBoxFake => {
if (selectBoxFake.classList.contains('open')) {
setSelectBoxFakeOptionsPosition(selectBoxFake);
}
});
}
function letSelectBoxesFakeView() {
D.removeEventListener('click', onSelectBoxFakeClickOutside);
W.removeEventListener('resize', onSelectBoxWindowResize);
}
function setSelectBoxesFakeView() {
D.addEventListener('click', onSelectBoxFakeClickOutside, false);
W.addEventListener('resize', onSelectBoxWindowResize, false);
}
let D = document,
R = D.documentElement,
W = window,
selectBoxValue,
selectBoxFakeCurrent,
selectBoxes,
selectBoxesFake;
// Destruct function
function letSelectBoxesFake() {
if (!selectBoxesFake) {
return;
}
let form;
selectBoxes.forEach(selectBox => {
if (form = selectBox.form) {
form.removeEventListener('reset', onSelectBoxFormReset);
}
letSelectBoxFake(selectBox);
});
letSelectBoxesFakeView();
selectBoxesFake = null;
}
// Construct function
function setSelectBoxesFake() {
selectBoxes = D.querySelectorAll('.select');
let form;
selectBoxes.forEach(selectBox => {
if (form = selectBox.form) {
form.removeEventListener('reset', onSelectBoxFormReset); // Remove duplicate!
form.addEventListener('reset', onSelectBoxFormReset, false);
}
setSelectBoxFake(selectBox);
});
setSelectBoxesFakeView();
selectBoxesFake = D.querySelectorAll('.select.js');
}
</script>
<script>
// Test for native JavaScript event(s)
document.querySelectorAll('select').forEach(select => {
select.addEventListener('change', function() {
console.log('change: ' + JSON.stringify(this.value));
});
select.addEventListener('input', function() {
console.log('input: ' + JSON.stringify(this.value));
});
});
document.forms[0].addEventListener('submit', function(e) {
alert(new URLSearchParams(new FormData(this)) + "");
e.preventDefault();
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment