Reputation: 115
I'm making a pixel art maker, and I can color individual divs in my grid; however, I want the user to be able to click, hold, and drag to continually draw. There've been similar questions to mine, but they seemed to need jQuery or not exactly apply to me.
https://jsfiddle.net/8okf4yg0/2/
//create cell listeners
function listenCells() {
let cell = document.querySelectorAll('.grid-square');
cell.forEach((cell) => {
cell.addEventListener('mouseenter', function() {
cell.style.backgroundColor = color;
});
});
}
is there someway to combine mouseenter and mousedown? Or is there a better solution?
Upvotes: 0
Views: 445
Reputation: 171690
Add mousedown and mouseup listeners to the parent container and have them toggle a flag variable.
Then check that flag before changing the cells.
Simple demo using a table
/* Flag to know if mosue is down on table */
let MDOWN = false;
const tbl = document.querySelector('table')
createRows();
['mousedown', 'mouseup'].forEach(eName => tbl.addEventListener(eName, () => MDOWN = !MDOWN));
function cellEnter() {
if (MDOWN) {
this.style.backgroundColor = 'black';
}
}
function createRows() {
for (let i = 0; i < 50; i++) {
const row = tbl.insertRow()
for (let j = 0; j < 50; j++) {
let cell = row.insertCell();
cell.addEventListener('mouseenter', cellEnter)
}
}
}
td {
height: 10px;
width: 10px;
border: 1px solid #ccc
}
table {
border-collapse: collapse;
}
<table>
</table>
Upvotes: 1