2

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;
}
lbpoundz
  • 45
  • 7

2 Answers2

1

You can use e.preventDefault() to prevent the default effect from happening inside your onmousedown 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()

John
  • 3,716
  • 2
  • 19
  • 21
0

I had your exact issue with Etch-A-Sketch and this is how I did it: similar to the other user's answer, this also uses preventDefault() but this activates using the ondragstart HTML attribute.

First, use this JS function to enable preventDefault().

function dragstart (event) {
    event.preventDefault()
}

Next, apply dragstart (event) to all your elements in your etch grid. In my case, I used the spread syntax [...nodeList] with the forEach method in a function which runs immediately after generating my grid squares.

let grid = document.getElementById('grid');

function addSquare () {
let sliderValue = document.getElementById('slider').value;
  for (let i = 0; i < sliderValue ** 2; i++) {
    const square = document.createElement('div');
    square.className = 'square';
    grid.appendChild(square);
  }
}

function modifyGridProperty () {
  let square = [...document.getElementsByClassName('square')];
  square.forEach(element => {
    element.setAttribute('ondragstart', 'dragstart(event)');
  });
}