Chrome "Can not drag" icon is interfering with mouseover events, how can I prevent this?

Viewed 120

Here is some code that uses javascript to create a bunch of div elements to act as pixels. I added an event listener to the mouseover event, and check to see if the mouse is clicked down. If the mouse is clicked down, I change the color of that pixel. The end result, is a simple drawing function.

I believe using something like HTML5 canvas would be more effective, but I was just playing around with the DOM and how events work.

The problem I am facing is that every so often, the chrome browser thinks I am trying to drag the body or a div, and no longer triggers mouseover events. It seems like an unusual problem, and I was wondering if anyone knew how to avoid it.

var numOfPxls = 0;
var resolution = "13px"

while (numOfPxls < 1300) {
  const pxl = document.createElement("div");
  pxl.classList.add("pxl");
  pxl.style.cssText = `
      height: ${resolution};
      width: ${resolution};
  `;
  document.querySelector("body").appendChild(pxl);
  pxl.addEventListener("mouseover", function(e){
    // only continue if left click
    if (e.buttons != 1) return; 
    this.style.backgroundColor = "pink";
  });
  numOfPxls++;
}
body {
  margin: 0;
  background-color: black;
}

.pxl {
  display: inline-block;
  background-color: black;
}
<body>

</body>

2 Answers

In case anyone stumbles across this later, I found the issue.

The default action for the "mousedown" event is to initiate dragging. The div elements can not be dragged. To resolve this, use the preventDefault method of the event.

i.e.

add onto

...
  pxl.addEventListener("mouseover", function(e){
    // only continue if left click
    if (e.buttons != 1) return; 
    this.style.backgroundColor = "pink";
  });
...

with:

...
  pxl.addEventListener("mouseover", function(e){
    // only continue if left click
    if (e.buttons != 1) return; 
    this.style.backgroundColor = "pink";
  });
  //new line to prevent drag default on mousedown
  pxl.addEventListener("mousedown", e => e.preventDefault());
...

I’m assuming you can just add this to your CSS

cursor: pointer;
Related