Selection – Issues – #60 – Prevent the default browser actions when touching an element selectable
https://github.com/Simonwep/selection/issues/60
by Simonwep
HTML
<script src="https://cdn.jsdelivr.net/npm/@simonwep/selection-js/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>a>div {
height: 3em;
width: 3em;
background-color: rgba(66, 68, 90, 0.075);
}
.box>a.selected div {
background-color: #7febc2;
}
.selection {
background-color: rgba(0, 0, 255, 0.1);
border-radius: 0.1em;
border: 0.05em solid rgba(0, 0, 255, 0.2);
}
.container {
width: 100vw;
height: 100vh;
overflow: auto;
}
JavaScript
const container = document.querySelector('.box')
for (let count = 0; count < 500; count++) {
const div = document.createElement('div')
const a = document.createElement('a')
a.href = 'https://github.com'
container.appendChild(a).appendChild(div)
}
const selection = Selection.create({
// Class for the selection-area
class: 'selection',
// All elements in this container can be selected
selectables: ['a'],
// The container is also the boundary in this case
boundaries: ['.box']
}).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 element of selected) {
element.classList.remove('selected')
inst.removeFromSelection(element)
}
// Clear previous selection
inst.clearSelection()
}
}).on('move', ({ changed: { removed, added }, oe }) => {
// Prevent the default browser actions when touching an element selectable.
// The default browser actions, such as following links.
// Issue: https://github.com/Simonwep/selection/issues/60
oe.preventDefault()
oe.stopPropagation()
oe.stopImmediatePropagation()
// Add a custom class to the elements that were selected.
for (const element of added) {
element.classList.add('selected')
}
// Remove the class from elements that were removed
// since the last selection.
for (const element of removed) {
element.classList.remove('selected')
}
}).on('stop', ({ inst }) => {
inst.keepSelection()
})