SelectionJS Template

by Simonwep

HTML

<div class="container">
    <div class="box"></div>
</div>

CSS

.box {
    display: grid;
    grid-template-columns: repeat(28, 1fr);
    grid-gap: 0.4em;
    user-select: none;
}

.box > div {
    height: 3em;
    width: 3em;
    background: rgba(66, 68, 90, 0.075);
}

.box > div.selected {
    background: #7febc2;
}

.selection-area {
    background: rgba(0, 0, 255, 0.1);
    border-radius: 0.1em;
    border: 0.05em solid rgba(0, 0, 255, 0.2);
}

.container {
  width: 70vmin;
  height: 70vmin;
  overflow: auto;
  margin: 15vmin;
}

JavaScript

import SelectionArea from "https://cdn.jsdelivr.net/npm/@simonwep/selection-js/lib/selection.min.mjs"

// Create selectable elements
const container = document.querySelector('.box');
for(let i = 0; i < 500; i++) {
	const div = document.createElement('div');
  container.appendChild(div);
}

const selection = new SelectionArea({

    // All elements in this container can be selected
    selectables: ['.box > div'],

    // The container is also the boundary in this case
    boundaries: ['.container'],
}).on('start', ({store, event}) => {

    // Remove class if the user isn't pressing the control key or ⌘ key
    if (!event.ctrlKey && !event.metaKey) {

        // Unselect all elements
        for (const el of store.stored) {
            el.classList.remove('selected');
        }

        // Clear previous selection
        selection.clearSelection();
    }

}).on('move', ({store: {changed: {added, removed}}}) => {

    // Add a custom class to the elements that where selected.
    for (const el of added) {
        el.classList.add('selected');
    }

    // Remove the class from elements that where removed
    // since the last selection
    for (const el of removed) {
        el.classList.remove('selected');
    }

}).on('stop', () => {
    selection.keepSelection();
});