Home > Net >  Disable dragging in HTML webpage
Disable dragging in HTML webpage

Time:04-16

I'm trying to make an etch-a-sketch with HTML where I have a div container with lots of div elements in it, using grid display in CSS.

HTML: <div id="canvas"></div>

Then I use JS to add the div elements:

for(let i =1;i<=256;i  ){
    let squareDiv = document.createElement("div");
    canvasElement.appendChild(squareDiv);
    canvasElement.setAttribute("draggable","false");}

The draggable attribute doesn't work.

When I click and drag to draw something, it is dragging a faint image as below: enter image description here

Is there an attribute I could use to disable this ?

Edit: All javascript code:

canvasElement =document.getElementById("canvas")

let isToggling = false;

function enableToggle(e) {
  isToggling = true;
}

function disableToggle() {
  isToggling = false;
}

function toggle(e) {
  if (isToggling === false) {
    return;
  }

  console.log('toggle:', e.target);

  e.target.classList.add('red');
}

for(let i =1;i<=256;i  ){
    let squareDiv = document.createElement("div");
    canvasElement.appendChild(squareDiv);
    canvasElement.setAttribute("draggable","false");

    squareDiv.onmousedown=enableToggle;
    squareDiv.onmouseenter=toggle;
    squareDiv.onmouseup=disableToggle;
}

CodePudding user response:

You can use e.preventDefault() to prevent the default effect from happening inside your onm ousedown event.

Add e.preventDefault() inside your enableToggle(e) function

function enableToggle(e) {
  isToggling = true;
  e.preventDefault()
}

If that doesn't work add it to toggle() and disableToggle()

  • Related