How can you use plain javascript to drag and drop the cross sign within the box in the grid?

Creating a grid in HTML where clicking on a box will draw an x sign and remove it if clicked again.

View the DEMO here.

Challenge Description:-

  • I am now looking to implement dragging the cross (x) sign to another grid within the box, but cancelling the action if the target box already contains the cross sign.

Is there a way to achieve this using only HTML and plain Javascript?

Answer №1

Check out the modified JSFiddle link here: http://jsfiddle.net/wz4hs9qa/2/

Here are the key updates made to your code:

1) Assigned a unique id to each cell based on its index:

cell.id = "cell_" + i;

2) Corrected a typo in the code:

on_drop.value = "drop(event, this)";

3) Moved the ondragover attribute from X inside the cell to the cell itself. Enabling dropping on empty cells is crucial.

var on_dragover = document.createAttribute('ondragover');
on_dragover.value = "allowDrop(event, this)";
cell.setAttributeNode(on_dragover);

4)

a) Provided each X with an id similar to its containing cell's id for proper handling by the drop event.

b) Added an ondragstart handler to save the index in the drag-and-drop dataTransfer object for both newer and older browsers.

function createX(obj){
    if (obj.innerHTML == ''){
        var id = obj.id.replace("cell", "X");
        obj.innerHTML = "<h1 id='" + id + "' style='text-align:center;' draggable='true' ondragstart='saveCell(event, this);'>X</h1>";
    } else {
        obj.innerHTML = "";
    }
}

function saveCell(ev, obj) {
    var cell_index = obj.id.substring(2);
    try {
        ev.dataTransfer.setData("text/plain", cell_index);
    } catch (exception) {
        ev.dataTransfer.setData("text", cell_index);
    }
}

5) Removed the line that cleared X on every drop as it conflicted with the desired behavior:

function allowDrop(ev, obj) {
    ev.preventDefault();
    //obj.innerHTML = '';
}

6) Enhanced the drop() function to:

a) Prevent dropping when a cell already contains an X

b) Place an X in the target cell

c) Retrieve the cell index from dataTransfer to clear the source cell

function drop(ev, obj) {
    ev.preventDefault();

    if (obj.innerHTML !== '') { // not empty
        return false;
    } else {
        createX(obj);
    }

    var data;
    try {
        data = ev.dataTransfer.getData("text/plain");
    } catch (exception) {
        data = ev.dataTransfer.getData("text");
    }
    var cell_id = "cell_" + data;
    document.getElementById(cell_id).innerHTML = '';
}

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

How can I bypass hotlink protection for RSS images?

According to the definition, RSS feeds are considered public. When images are displayed within the feed, it is essentially "hotlinking," meaning that the content is being read directly from the Internet rather than your local machine. Is there a specific ...

Pressing the shortcut key will activate the function specified in ng-click,

I have been searching for a solution to my problem, but I haven't found anything that really helps. What I am looking for is a shortcut within an ng-click directive where there is only an if condition without an else expression. Essentially, I just wa ...

Add a new item to an array in Angular 2 when a click event occurs

I'm trying to add a new list item (which comes from an API) when a button is pressed, but I'm not sure how to do it. Can anyone provide some guidance? Here's the code: <ul> <li *ngFor="let joke of jokes">{{joke.value}}</li> ...

You need to click the form submit image twice in order to make it work

Struggling to get a standard opt-in form to work with an image submit button. The script works fine with a regular submit button, but the image button requires two clicks initially and then one click after unless the page is refreshed. I believe there mig ...

Retrieve key codes from inputs sharing the same class

My webpage contains multiple text inputs that all share the same class for various reasons. Currently, I am attempting to capture the ESC button press when an input is focused and alert whether the input has a value or not. However, this functionality on ...

reCAPTCHA v3 - Alert: There are no existing reCAPTCHA clients available

After coming across a similar issue on Stack Overflow (link to the question here), I attempted to implement reCAPTCHA on my website to combat spam emails received through the form. Despite following Google's instructions, I encountered an error that p ...

Global error handling for URQL GraphQL mutation is a critical aspect that needs to be effectively implemented

Here's the technology stack I'm using: react v17.0.2 graphql v16.8.0 graphql-ws v5.14.0 urql v4.0.5 I rely on Hasura Actions to interact with a REST API and am in need of a solution for handling global errors for all mutations. For instance, I ...

The combination of two colors in a hard background fails to create an appealing aesthetic

Seeking assistance with an issue I encountered while trying to create a two-color background. Below is the code snippet: body, html { height: 100%; width: 100%; background: #0000ff; background: linear-gradient(180deg, #ff0000 50%, #0000f ...

Issue with integrating e-junkie shopping cart with Bootstrap 5

After transitioning from Bootstrap 4 to Bootstrap 5 and encountering navigation issues on smaller screens, I delved into the code to uncover the source of the problem. It turns out that the collapse button in the navbar wasn't functional due to confli ...

Extract the td elements from a table with specific class using the DataTable plugin

I stumbled upon this snippet of code while browsing through the DataTable website. var table = $('#example').DataTable(); table.column(0).data().each(function(value, index) { console.log('Data in index: ' + index + ' is: &apos ...

Creating a hover state for a CSS class seems straightforward, but I'm finding it a bit tricky

I am looking to customize my inline menu by changing the last menu item to a different colored box with unique text. I have successfully applied a custom style using the #navbar a.blogbox class, but I am struggling to figure out how to change the hover s ...

Using functions like nl2br() for new line breaks, preg_replace for replacing patterns, htmlspecialchars() for encoding special

I've reviewed all the answers on this topic, but I'm still struggling to find the correct method for sanitizing data. My task is to enter: <?php echo 'yes'; ?> <?php echo 'yes' ?> into a text area, submit it in ...

Enhance TinyMCE functionality to permit text as a primary element within <table> or <tr> tags

I've been struggling for the past three hours, trying out different solutions and searching like crazy on Google. Unfortunately, I have not been able to find a resolution to this particular issue. Issue: TinyMCE is not allowing me to insert text dire ...

The operation to add a new user timed out after 10 seconds while buffering in the mongooseError

It appears that when I run mongoose in this code, it doesn't seem to connect to my local MongoDB database in time. The error message "mongooseError: Operation users.insertOne() buffering timed out after 10000 ms" is displayed if the insert operation i ...

Using Python and Selenium to manipulate the webpage and execute JavaScript can help reconstruct the true HTML structure

I have a very basic Selenium code snippet that I am running: <input name="X" id="unique" value="" type="text"> <script> document.getElementById("unique").value="123"; </script> While I can retrieve the input value "123" using driv ...

What are the steps to integrate <br> in a JavaScript code?

I have recently started learning about web development and I'm facing a challenge with this implementation. var obj = [[{ name: "John", age: 30, city: "New York"}, { name: "Ken", age: 35, city: "New Orleans"}]]; ...

Fixing the Angular2 glitch: 'Uncaught TypeError: Cannot read property 'apply' of undefined'

Seeking solutions: How can I fix the "Uncaught TypeError: Cannot read property 'apply' of undefined" error that keeps showing up in the console of my Angular2 application? Any helpful insights are appreciated! ...

The declaration of 'exports' is not recognized within the ES module scope

I started a new nest js project using the command below. nest new project-name Then, I tried to import the following module from nuxt3: import { ViteBuildContext, ViteOptions, bundle } from '@nuxt/vite-builder-edge'; However, I encountered th ...

Banner with video background (not taking up the entire page)

I'm currently working on a website project that involves using a YouTube video as the banner, but I'm facing some challenges in making it work correctly. So far, this is what I have: #video-background { position: absolute; right: 0; top:1 ...

Position the label to the left of the form-switch using Bootstrap

I have been struggling to align the label to the left of my switchbox. Despite searching through stackoverflow and other websites, I haven't been successful in achieving the desired alignment. Here is a trimmed down version of the code for reference: ...