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: 50vw;
  height: 50vh;
  overflow: auto;
}

JavaScript

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

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

const selection = Selection.create({
    class: 'selection',
    selectables: ['.box > div'],
    boundaries: ['.container'],

    onSelect({target, originalEvent, selectedElements}) {
        const selected = target.classList.contains('selected');

        // Remove class if the user isn't pressing the control key or ⌘ key and the
        // current target is already selected
        if (!originalEvent.ctrlKey && !originalEvent.metaKey) {

            // Remove class from every element that is selected
            for (const el of selectedElements) {
                el.classList.remove('selected');
            }

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

        if (!selected) {

            // Select element
            target.classList.add('selected');
            this.keepSelection();
        } else {

            // Unselect element
            target.classList.remove('selected');
            this.removeFromSelection(target);
        }
    },

    onStart({selectedElements, originalEvent}) {

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

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

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

    onMove({selectedElements, changedElements: {removed}}) {

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

        // Remove the class from elements that where removed
        // since the last selection
        for (const el of removed) {
           ...