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:

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

What is the process for enabling HTMLField in Django Admin and ensuring it is accurately displayed on the template?

One of the models in my Django app is for dorms and it looks like this: class Dorm(models.Model): dorm_name = models.CharField(max_length=50, help_text="Enter dorm name") dorm_description = models.TextField(max_length=1000, help_text="Enter dorm d ...

Fetch Timeout Issue in React Native

I am currently using fetch to retrieve data from a server. Unfortunately, I am facing issues with setting a timeout for the fetch request in case the server does not respond. This is my global fetchData class: fetchGetResp(url, token) { return fetch( ...

Troubleshooting Azure typescript function: Entry point for function cannot be determined

project structure: <root-directory> ├── README.md ├── dist ├── bin ├── dependencies ├── host.json ├── local.settings.json ├── node_modules ├── package-lock.json ├── package.json ├── sealwork ...

Tips for crafting effective error messages to communicate with users

One of the biggest challenges I face is crafting clear error messages for clients in case of errors. A typical scenario involves using Axios and a third-party API to fetch data, requiring appropriate error handling for both. Axios' error handling doc ...

JavaScript example: Defining a variable using bitwise OR operator for encoding purposes

Today I came across some JavaScript code that involves bitwise operations, but my knowledge on the topic is limited. Despite searching online for explanations, I'm still unable to grasp the concept. Can someone provide insight into the following code ...

Adjustments in margins for printed HTML may vary from page to page in Internet Explorer versions 8 to 11

One challenge I'm facing is with a user-generated report page that is typically printed. There seems to be an unusual bug occurring specifically in Internet Explorer. The layout of the page consists of tables within various divs, all aligned perfectly ...

Version 2: "In case of an empty input field, the submit button should be

After experimenting with two different codes on my websites, I encountered an issue. The first code looked like this: $(document).ready(function(){ $('.sendButton').attr('disabled', true); $('#message').keyup(function ...

Creating a Dynamic Navigation Bar with HTML and CSS

I've been exploring the code on w3schools.com, and while there are some great examples, I'm struggling to understand it all. Unfortunately, there aren't any instructions on customizing the code for a third level of menus. Can someone simplif ...

Encountering a Jquery 404 error while attempting to locate a PHP file through Ajax requests

I've been struggling with this issue for the past couple of hours, but I just can't seem to get it fixed. Here's my current file setup: classes -html --index.html --front_gallery.php -javascript --gallery.js I've been following a tuto ...

Warning: React detects a missing dependency within an interval in the effect

A webpage I developed using React and Next.js has the following structure. import Head from 'next/head'; import { useEffect, useState } from 'react'; import Header from '../components/Header'; export default function Home() { ...

Populate a PHP array with designated file types from a designated folder, to later be loaded into a JavaScript array

My goal is to populate a JavaScript array with files of type .dae from different directories: "/collada/basement", "/collada/ground", "/collada/first", and "/collada/roof". I'm thinking of creating separate arrays for each directory. I understand that ...

What is the best way to implement an anchor link in my JavaScript code?

I'm struggling to wrap my head around this, as my thoughts seem to have vanished. On my webpage, there's a button element with an id: for example <button id="someId"></button> Within the document.ready function, I've set up an ...

Parsing the CSV file contents according to the specified columns

Currently, I'm involved in a project using AngularJS where I need to extract data from a CSV file column by column using JavaScript. So far, I've successfully retrieved the CSV data and displayed it in the console. While I've managed to sepa ...

Clicking on multiple external links will open them in separate tabs simultaneously

My attempts to find a solution on Google have been fruitless. I am in the process of creating a content aggregator, which is essentially a list of links to external websites. I want each link clicked to open in a new tab. Currently, I am using target="bl ...

Is it possible to utilize mathematical operators such as multiplication, division, addition, subtraction, and exponentiation to transform a non-zero numerical value into

I am currently working with Oracle Siebel software which supports JavaScript expressions using only specific operators such as multiply, divide, subtract, add, and XOR (*, /, -, +, ^). Unfortunately, other operators like ! or ? : are not available for use. ...

Get information that has been uploaded using ajax

I need help with my code for sending data via ajax to an update.php page. $(document).ready(function() { $("#modify").click(function() { var a = $("#a").val(); var b = $("#b").val(); var c = $("#c").val(); $.ajax({ type: "POST", ...

What is the best way to assign a distinct index value to each object in an array

When I use the function below to add an index to each array object, all IDs end up with the same value when I check console.log: var foo = [...this.props.articleList]; foo.forEach(function(row, index) { row.id = index+1; }); console.log(foo); My des ...

Discover the steps to implement a live user list in a chat application with the help of angular.js, socket.io, and node

Currently, I am in the process of developing a chat application with AngularJS and Socket.io. The current status of my project allows users to send and receive messages from different individuals. To gain access to the chatbox, users need to input their na ...

Angular UI directive for modal confirmation

Looking to create a custom Angular directive using angular-bootstrap that mimics the confirm() function. Check out the visual result and desired behavior in this plunk: http://embed.plnkr.co/27fBNbHmxx144ptrCuXV/preview Now, I want to implement a directi ...

Attempting to show different fields depending on the chosen option

Having an issue with the signup process for my team and competition setup. I want to implement a feature where, if the user selects 'Competition', the promo code field will be displayed. However, this field should only appear when 'Competiti ...