How to select multiple cells using ctrl + click
Try this:
const cells = document.querySelectorAll(".cell");
let lastClicked;
function handleClick(e) {
// Toggle class active
if (e.target.classList.contains("active")) {
e.target.classList.remove("active");
} else {
e.target.classList.add("active");
}
// Check if CTRL key is down and if the clicked cell has aready class active
let inRange = false;
if (e.ctrlKey && this.classList.contains("active")) {
// loop over cells
cells.forEach(cell => {
// check for the first and last cell clicked
if (cell === this || cell === lastClicked) {
// reverse inRange
inRange = !inRange;
}
// If we are in range, add active class
if (inRange) {
cell.classList.add("active");
}
});
}
// Mark last clicked
lastClicked = this;
}
cells.forEach(cell => cell.addEventListener("click", handleClick));
#grid {
display: grid;
grid-template-columns: repeat(3, 50px);
grid-template-rows: repeat(2, 50px);
}
.cell {
display: flex;
justify-content: center;
align-items: center;
border: solid 1px #ccc;
}
.active {
background-color: #80aaff;
}
<div id="grid">
<div class="cell">1</div>
<div class="cell">2</div>
<div class="cell">3</div>
<div class="cell">4</div>
<div class="cell">5</div>
<div class="cell">6</div>
</div>
codepen
I programmed the Javascript part completely different than you did. I hope that you can still use it. But it does exactly what you asked for.
With Shift + Cell you can select all cells in between.
var $lastSelected = [],
container = $('#grid'),
collection = $('.cell');
container.on('click', '.cell', function(e) {
var that = $(this),
$selected,
direction;
if (e.shiftKey){
if ($lastSelected.length > 0) {
if(that[0] == $lastSelected[0]) {
return false;
}
direction = that.nextAll('.lastSelected').length > 0 ? 'forward' : 'back';
if ('forward' == direction) {
// Last selected is after the current selection
$selected = that.nextUntil($lastSelected, '.cell');
} else {
// Last selected is before the current selection
$selected = $lastSelected.nextUntil(that, '.cell');
}
collection.removeClass('selected');
$selected.addClass('selected');
$lastSelected.addClass('selected');
that.addClass('selected');
} else {
$lastSelected = that;
that.addClass('lastSelected');
collection.removeClass('selected');
that.addClass('selected');
}
} else {
$lastSelected = that;
collection.removeClass('lastSelected selected');
that.addClass('lastSelected selected');
}
});
.selected {background-color: #80aaff;}
#grid{
display: grid;
grid-template-columns: repeat(3, 50px);
grid-template-rows: repeat(2, 50px);
}
.cell {
display: flex;
justify-content: center;
align-items: center;
border: solid 1px #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="grid">
<div class="cell">1</div>
<div class="cell">2</div>
<div class="cell">3</div>
<div class="cell">4</div>
<div class="cell">5</div>
<div class="cell">6</div>
</div>