Skip to content

Instantly share code, notes, and snippets.

@taufik-nurrohman
Last active June 7, 2021 03:30
Show Gist options
  • Select an option

  • Save taufik-nurrohman/6cd2422017f7baf1c745addcabaf3981 to your computer and use it in GitHub Desktop.

Select an option

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>
<!--
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>
.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-user-select: none;
-moz-user-select: none;
user-select: none;
}
.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.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 > span {
display: block;
margin-right: 1em;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.select.js > span + span {
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 > span + span.up {
}
.select[size] + .select.js {
height: auto;
}
.select[size] + .select.js::after {
display: none;
}
.select[size] + .select.js > span {
margin: 0;
}
.select[size] + .select.js > span + span {
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 > span + span a {
display: block;
padding: .25em .5em;
font: inherit;
color: inherit;
cursor: pointer;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.select.js > span + span a:hover,
.select.js > span + span a.focused {
background: blue;
color: white;
}
.select.js > span + span span {
display: block;
padding: .25em .5em;
}
.select.js > span + span 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 > span + span span a {
padding-left: 1.5em;
margin: 0 -.5em;
}
.select.js > span + span a.disabled {
color: gray;
cursor: not-allowed;
}
.select.js > span + span a.disabled:hover,
.select.js > span + span a.disabled.focused {
background: gray;
color: white;
}
.select.js > span + span a.selected {
color: blue;
}
.select.js > span + span a.selected:hover,
.select.js > span + span a.selected.focused {
background: blue;
color: white;
}
.select.js.open > span + span {
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 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 = selectBox.nextElementSibling;
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('span'),
selectBoxFakeLabel = D.createElement('span'),
selectBoxValue = selectBox.value,
selectBoxTitle = selectBox.title,
selectBoxIndex = 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 onSelectBoxFakeOptionClick(e) {
let t = this,
selectBoxValuePrevious = selectBoxValue;
selectBoxValue = t._value;
selectBoxFakeLabel.textContent = t.textContent;
getSelectBoxFakeOptions(selectBoxFake).forEach(selectBoxFakeOption => {
selectBoxFakeOption.classList[selectBoxValue === selectBoxFakeOption._value ? 'add' : 'remove']('selected');
});
e.isTrusted && selectBoxFake.focus();
if (selectBoxValue !== selectBoxValuePrevious) {
selectBox.value = selectBoxValue;
trigger(selectBox, 'input');
}
e.preventDefault();
}
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 = selectBoxIndex;
selectBoxFakeOption._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');
}
++selectBoxIndex;
}
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('span');
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);
selectBoxFakeDropDown.style.maxHeight = (selectBoxFakeOption.offsetHeight * selectBox.size) + 'px';
}
}
selectBox.addEventListener('focus', onSelectBoxFocus, false);
selectBox.addEventListener('change', onSelectBoxChange, false);
selectBox.addEventListener('input', onSelectBoxInput, false);
if (selectBox.multiple) {
// TODO
}
}
function setSelectBoxFakeOptionsPosition(selectBoxFake) {
let selectBox = selectBoxFake.previousElementSibling,
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 = selectBoxFakeOption.offsetTop;
} else if (top + height - heightParent > topScroll) {
selectBoxFakeDropDown.scrollTop = top + height - heightParent;
}
}
}
function onSelectBoxFakeClickOutside(e) {
selectBoxesFake && selectBoxesFake.forEach(selectBoxFake => {
selectBoxFake !== selectBoxFakeClicked && selectBoxFake.classList.remove('open');
});
}
function onSelectBoxFakeBlur(e) {
if (!selectBoxFakeClicked) {
return;
}
let t = this,
selectBox = t.previousElementSibling;
if (!t.classList.contains('open') && selectBox.value !== selectBoxValue) {
trigger(selectBox, 'change');
}
selectBoxFakeClicked = null;
}
function onSelectBoxFakeClick(e) {
let t = this;
t.classList.toggle('open');
if (t.classList.contains('open')) {
setSelectBoxFakeOptionsPosition(t);
}
selectBoxFakeClicked = t;
}
function onSelectBoxFakeFocus() {
let t = this,
selectBox = t.previousElementSibling;
selectBoxValue = selectBox.value;
selectBoxFakeClicked = t;
}
function onSelectBoxFakeKeyDown(e) {
let t = this,
key = e.key,
keyCode = e.keyCode,
selectBox = t.previousElementSibling,
selectBoxIndex = selectBox.selectedIndex,
selectBoxFakeOptions = getSelectBoxFakeOptions(t),
selectBoxFakeOption = getSelectBoxFakeOptionByIndex(selectBoxFakeOptions, selectBoxIndex),
open = t.classList.contains('open');
// console.log([key, keyCode]);
if ('ArrowDown' === key || 40 === keyCode) {
while (selectBoxFakeOption = getSelectBoxFakeOptionByIndex(selectBoxFakeOptions, ++selectBoxIndex)) {
if (!selectBoxFakeOption.classList.contains('disabled')) {
break;
}
}
if (selectBoxFakeOption) {
trigger(selectBoxFakeOption, 'click');
t.classList[open ? 'add' : 'remove']('open');
}
e.preventDefault();
} else if ('ArrowUp' === key || 38 === keyCode) {
while (selectBoxFakeOption = getSelectBoxFakeOptionByIndex(selectBoxFakeOptions, --selectBoxIndex)) {
if (!selectBoxFakeOption.classList.contains('disabled')) {
break;
}
}
if (selectBoxFakeOption) {
trigger(selectBoxFakeOption, 'click');
t.classList[open ? 'add' : 'remove']('open');
}
e.preventDefault();
} else if ('End' === key || 35 === keyCode) {
selectBoxIndex = selectBox.options.length;
while (selectBoxFakeOption = getSelectBoxFakeOptionByIndex(selectBoxFakeOptions, --selectBoxIndex)) {
if (!selectBoxFakeOption.classList.contains('disabled')) {
break;
}
}
if (selectBoxFakeOption) {
trigger(selectBoxFakeOption, 'click');
t.classList[open ? 'add' : 'remove']('open');
}
e.preventDefault();
} else if ('Enter' === key || 13 === keyCode) {
t.classList.toggle('open');
e.preventDefault();
} else if ('Escape' === key || 27 === keyCode) {
t.classList.remove('open');
// e.preventDefault();
} else if ('Home' === key || 36 === keyCode) {
selectBoxIndex = -1;
while (selectBoxFakeOption = getSelectBoxFakeOptionByIndex(selectBoxFakeOptions, ++selectBoxIndex)) {
if (!selectBoxFakeOption.classList.contains('disabled')) {
break;
}
}
if (selectBoxFakeOption) {
trigger(selectBoxFakeOption, 'click');
t.classList[open ? 'add' : 'remove']('open');
}
e.preventDefault();
} else if ('Tab' === key || 9 === keyCode) {
selectBoxFakeOption && trigger(selectBoxFakeOption, 'click');
t.classList.remove('open');
// e.preventDefault();
}
t.classList.contains('open') && setSelectBoxFakeOptionsPosition(t);
}
function onSelectBoxChange(e) {
onSelectBoxInput.call(this, e);
}
function onSelectBoxFocus(e) {
this.nextElementSibling.focus();
}
function onSelectBoxInput() {
let t = this,
selectBoxValue = t.value,
selectBoxFake = t.nextElementSibling,
selectBoxFakeOptions = getSelectBoxFakeOptions(selectBoxFake);
// if (!selectBoxValue && t.options[0]) {
// selectBoxValue = t.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,
selectBoxFakeClicked,
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