I created two versions of a pixel art maker, one with vanilla JS and another with jQuery. When you try drawing on the grid, if you move too quickly, a cell is dragged, and after you release the mouse pointer, it shows the no-symbol (circle with a line through it) and keeps coloring (which doesn't happen otherwise). The only way to make it stop coloring at that point is to click a cell. What code can I add, if any, to prevent this default browser behavior for each version?
I'm not sure if these are what need to be changed, but here are my functions for color dragging:
jQuery (view CodePen for full code):
function dragColor() {
// Filters clicks by those in cells
$(pixelCanvas).on('mousedown', 'td', function() {
mousedown = true;
});
// 'mouseup': when pointer is over element and mouse button has been clicked then released (unlike click event, doesn't have to be on same element on which mousedown occurred)
$(document).mouseup(function() {
mousedown = false;
});
// 'mouseover' triggered when mouse pointer enters an element
$(pixelCanvas).on('mouseover', 'td', function() {
if (mousedown) {
$(this).css('background-color', color);
}
});
}
Vanilla JS (view CodePen for full code):
let down = false; // Tracks whether or not mouse pointer is pressed
// Listens for mouse pointer press and release on grid. Changes value to true when pressed, but sets it back to false as soon as released
pixelCanvas.addEventListener('mousedown', function(e) {
down = true;
pixelCanvas.addEventListener('mouseup', function() {
down = false;
});
// Ensures cells won't be colored if grid is left while pointer is held down
pixelCanvas.addEventListener('mouseleave', function() {
down = false;
});
pixelCanvas.addEventListener('mouseover', function(e) {
// 'color' defined here rather than globally so JS checks whether user has changed color with each new mouse press on cell
const color = document.querySelector('.color-picker').value;
// While mouse pointer is pressed and within grid boundaries, fills cell with selected color. Inner if statement fixes bug that fills in entire grid
if (down) {
// 'TD' capitalized because element.tagName returns upper case for DOM trees that represent HTML elements
if (e.target.tagName === 'TD') {
e.target.style.backgroundColor = color;
}
}
});
});