SelectionJS Template

by Simonwep

HTML

<script src="https://simonwep.github.io/selection/dist/selection.min.js"></script>
<div class="container">
  <div class="box"> </div>
</div>

CSS

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

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

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

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

.container {
  width: 70vw;
  height: 70vh;
  overflow: auto;
}

JavaScript

const container = document.querySelector('.box');

for(let i = 0; i < 500; i++) {
	const div = document.createElement('div');
  container.appendChild(div);
}

/**
 * SCROLLABLE CONTAINERS ARE SOMEWHAT BROKEN IN JSFIDDLE!
 */
const selection = Selection.create({

    // Class for the selection-area
    class: 'selection',

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

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

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

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

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

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

    // 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', ({inst}) => {
    
    // Remember selection in case the user wants to add smth in the next one
    inst.keepSelection();
});