Turn off the ability to drag on an HTML page

Need help with creating an HTML etch-a-sketch! I have a div container with multiple div elements inside it, all set up with CSS grid display.

HTML structure:

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

To populate the canvas with div elements, I've used JS:

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

Unfortunately, the draggable functionality is not working as expected.

When attempting to draw on the canvas by clicking and dragging, instead of drawing, it creates a faint image like this: https://i.sstatic.net/KomOT.png

Is there a way to disable this drag effect?

Complete JavaScript code for reference:

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;
}

Answer №1

To stop the default behavior in your onmousedown event, make use of e.preventDefault()

Simply insert e.preventDefault() within your enableToggle(e) function

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

If this approach doesn't solve the issue, remember to include it in toggle() and disableToggle() as well

Answer №2

I encountered a similar issue with Etch-A-Sketch and found a solution that worked for me. Just like another user suggested, I also utilized the preventDefault() method, but in my case, I used the HTML attribute ondragstart.

To start off, I created a JS function to trigger the preventDefault() action:

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

Next, I added dragstart (event) to all elements within my etch grid. To achieve this, I employed the spread syntax [...nodeList] along with the forEach method within a function that executed 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)');
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for ensuring session token verification remains intact upon reloading

I am currently in the process of developing a website using the Next.js framework and I am seeking advice on how to prevent the reload effect that occurs when transitioning from the login page back to the main page for just a fraction of a second. Below i ...

How can we prevent Material-UI and Redux-form from re-rendering when an option is clicked in the select input?

I am facing an issue with rendering options dynamically. Whenever I click on the select or the options, the component re-renders and changes the options. As a result, I need to click twice to select an option in the dropdown. This re-rendering is happening ...

Identify the changed field using Javascript

In my MVC application, I have a form with multiple fields that I am monitoring for changes using JavaScript. The code snippet below keeps track of any changes made in the form: var _changesMade = false; // Flag the model as changed when any other fie ...

Utilizing relative URIs in Node.js request library

I've encountered an issue with my code where node.js is unable to resolve the url: const request = require('request') const teamURL = `/users/${user._id}/teams`; const req = request({ url: teamURL, json: true }, function(error, ...

Is there a way to remove the unwanted code ​ from the client side of my website?

Upon inspecting the source code of a webpage, I noticed an odd character ​ appearing before the <script> tag on the client side. Strangely, this mysterious character is not present anywhere in the server-side PHP file. I attempted removing a ...

Tips on how to retrieve an Observable Array instead of a subscription?

Is there a way to modify this forkJoin function so that it returns an observable array instead of a subscription? connect(): Observable<any[]> { this.userId = this.authService.userId; this.habits$ = this.habitService.fetchAllById(this.userId); this.s ...

unable to retrieve the chosen item from the dropdown menu

How can I retrieve the value of the selected item from a dropdown menu without getting an undefined error? You can find my code on Jsfiddle. Can anyone spot what might be causing this issue? <select class="ddl_status" id="status_ddl_20" style="display ...

Express: when req.body is devoid of any data

My server code using Express: const express = require('express'); const exphbs = require('express-handlebars'); const path = require('path'); const bodyparser = require('body-parser'); const app = express(); cons ...

How can you securely transfer the ARRAY OBJECT from JavaScript to PHP using Ajax?

I am attempting to send a Javascript Array Object via Ajax to PHP and then use that object as a true Array on the PHP side. My current approach has not been successful in terms of utilizing the incoming object as an Array within PHP; I can only parse it as ...

Bootstrap's Vertical Margin Concept

Is there a way to include margin or a line similar to the image below? [![Please refer to the accompanying image][1]][1] ...

Exploring the scope of event listeners in jQuery's TimeCircles

Currently experimenting with the jquery timer known as "TimeCircles", which can be found here. I have successfully set up a minute / second timer for 30 minutes with an alert that triggers at 25 minutes. My goal is to implement an event when the timer hits ...

The functionality of the Bootstrap dropdown or radio input type is not functioning correctly

I'm currently utilizing electron([email protected]) along with bootstrap([email protected]). Whenever I attempt to incorporate a dropdown or other components from Bootstrap, they simply do not function. I am unsure of what mistake I might ha ...

Verify and generate a notification if the value is null

Before saving, it is important to check for any null values and alert them. I have attempted to do so with the following code, but instead of alerting the null values, the data is being saved. . function fn_publish() { var SessionNames = getParamet ...

Executing multiple HTTPS requests within an Express route in a Node.js application

1 I need help with a route that looks like this: router.get('/test', async(req, res)=>{ }); In the past, I have been using the request module to make http calls. However, now I am trying to make multiple http calls and merge the responses ...

Saving components locally (vue2)

Looking for help with passing data from Props to Data in vue.js? Check out this Stack Overflow discussion. If you're running into issues, take a look at this sandbox example: https://codesandbox.io/s/u3mr8. Concerned about side effects of copying ob ...

Loads a PHP file automatically using the URL from a jQuery Ajax method

Using the jquery ajax method, I am trying to populate a dropdown menu with a set of option values from my title.php file. However, upon loading the page, in the Chrome Android browser, it redirects to the title.php. Does anyone have any insights into what ...

Having trouble with Vee-validate Basic example - undefined errors issue

I've been struggling to get a basic form validation page working with vee-validate. Something seems to be going wrong, but I can't pinpoint the exact issue. Why am I seeing the error: errors not defined. <!DOCTYPE html> <html> < ...

"Struggling with the 2-Column Layout Glitch

I attempted to follow a tutorial for creating a 2 column layout from this person: Here is the result of my implementation: / http://jsfiddle.net/WrpA8/ The CSS: #container { width: 800px; margin: 40px auto; border: 1px solid black; } #header ...

Customize the position of nodes and their descendants in a d3 tree chart by setting specific x and y coordinates

I am in need of a d3 tree structure that looks like this. https://i.sstatic.net/X6U3u.png There are two key points to understand from the image above: Headers will have multiple parents(wells). I need to be able to drag and drop links connecting w ...

Is it acceptable to initiate an import with a forward slash when importing from the root directory in Next.js?

I've noticed that this import works without any issues, but I couldn't find official documentation confirming its validity: // instead of using a complex nested import like this import { myUtil } from '../../../../../lib/utils' // this ...