ES6 Checkbox Painter
by MegaScience
CSS
html,
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
body {
display: grid;
grid-template-columns: repeat(var(--column-count), var(--checkbox-width));
grid-template-rows: repeat(var(--row-count), var(--checkbox-height));
justify-content: center;
align-content: center;
background-color: green;
}
input[type="checkbox"] {
box-sizing: border-box;
margin: 3px;
}
JavaScript
class checkboxPainterClass {
container = document.body
checkboxWidth = 20
checkboxHeight = 20
checkboxGrid = []
debounce = null
getInsertionIndex(row, col) {
for (let r = 0; r < row; r++) col += this.checkboxGrid[r].length
return col
}
checkboxHandler(e) {
// Left-Click + Shift: Uncheck
if (e.buttons === 1 && e.shiftKey) e.currentTarget.checked = false
// Only Left-Click: Check
else if (e.buttons === 1) e.currentTarget.checked = true
}
updateGridHandler() {
clearTimeout(this.debounce)
this.debounce = setTimeout(() => this.updateGrid(), 50)
}
updateGrid() {
const colCount = Math.floor(window.innerWidth / this.checkboxWidth)
const rowCount = Math.floor(window.innerHeight / this.checkboxHeight)
this.container.style.setProperty('--column-count', colCount)
this.container.style.setProperty('--row-count', rowCount)
while (this.checkboxGrid.length < rowCount) this.checkboxGrid.push([])
while (this.checkboxGrid.length > rowCount) for (const checkboxElement of this.checkboxGrid.pop()) this.container.removeChild(checkboxElement)
for (let row = 0; row < rowCount; row++) {
while (this.checkboxGrid[row].length < colCount) {
const checkboxElement = document.createElement('input')
checkboxElement.type = 'checkbox'
checkboxElement.style.gridRowStart = row + 1
checkboxElement.style.gridColumnStart = this.checkboxGrid[row].length + 1
checkboxElement.addEventListener('mousedown', this.checkboxHandler)
checkboxElement.addEventListener('mouseover', this.checkboxHandler)
const insertionIndex = this.getInsertionIndex(row, this.checkboxGrid[row].length)
if (insertionIndex < this.container.children.length) this.container.insertBefore(checkboxElement,...