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

The relentless Livewire Event Listener in JavaScript keeps on running without pausing

I need to create a solution where JavaScript listens for an event emitted by Livewire and performs a specific action. Currently, the JavaScript code is able to listen to the Livewire event, but it keeps executing continuously instead of just once per event ...

extract objects from an array of objects based on a specified array

Within my JSON array, I have data structured like this: const data = [ { "uniqueId": 1233, "serviceTags": [ { "Id": 11602, "tagId": "FRRRR", "missingRequired&quo ...

How can one utilize electron's webContents.print() method to print an HTML or text file?

Electron Version : 2.0.7 Operating System : Ubuntu 16.04 Node Version : 8.11.1 electron.js let win = new BrowserWindow({width: 302, height: 793,show:false}); win.once('ready-to-show', () => win.hide()); fs.writeFile(path.join(__dirname ...

Validating Two DateTime Pickers as a Group with Javascript in asp.net

How to Ensure Group Validation of Two DateTime Pickers Using JavaScript in ASP.NET ...

The battle of line-height versus padding for achieving vertical centering with one-lined text

One-lined text can be vertically centered using either the line-height property or by adding padding-top and padding-bottom. What are the advantages and disadvantages of each method? body { font-size: 12px; font-family: ...

Retrieving data from radio buttons using React Hook Form

As I delve into learning React and Next.js, working with form submissions has been a breeze thanks to react-hook-form. However, I've hit a roadblock when it comes to handling radio buttons in my application. Specifically, there's a step where use ...

Issues with PHP Form Email DeliveryIt seems that there is a

I currently have a ready-made form that is constructed using html, css, jquery, and ajax. It's basically copied and pasted onto my contact page for now. This is the code I include before the html tag on the contact.php page. <?php session_name(" ...

Enhanced Firefox functionality with support for multiple columns

It has come to my attention that Internet Explorer 9 and older versions do not support multiple columns. However, even with the latest version of Firefox, I am experiencing issues with this website loading correctly. Do you have any insight into what might ...

Having trouble with the move_uploaded_file function in PHP?

I have been actively studying PHP and am currently working on a CMS project. I have encountered an issue with image uploading. PHP if ( $_POST['img']) $uploads_dir = '/images'; $tmp_name = $_FILES["img"]["tmp_name"]; $name = $_FIL ...

Is there a way to make a single background image the frame for each individual post on a tumblr theme?

I've set my sights on a more challenging goal for my custom Tumblr themes - I want to have a background image for each post, similar to how other themes display posts within boxes. Is there a way to make these boxes into images? I've tried tinke ...

The process of making a pop-up modal instead of just relying on alerts

Attempting to change from using an alert to a pop-up with a simple if statement, but encountering some issues. Here is the current code: if(values == ''){ $('body').css('cursor','auto'); alert("Blah Blah..." ...

When running the command "npx create-next-app@latest --ts," be aware that there are 3 high severity vulnerabilities present. One of the vulnerabilities is that "node-fetch

Just set up a fresh project with Next.js and TypeScript by following the documentation using npx create-next-app@latest --ts. Encountering multiple high severity vulnerabilities despite running npm audit fix --force, which actually adds more vulnerabiliti ...

Search for specific parameters in an array and retrieve them

I have been attempting to sift through an array of data retrieved from my API, but unfortunately, the data remains unfiltered. I suspect that it might be due to the way I implemented my method or perhaps my params are not being returned correctly. Below ar ...

What is the most elegant way to retrieve a new item from Firebase and read it?

My goal is to display the result of a successful read on a page, with only one attempt available before the headers are set and the page is sent. I am looking to retrieve one new value, generated after a listener was initiated so as not to pull existing da ...

Sizing labels for responsive bar charts with chart.js

I'm encountering a problem with my bar chart created using chart.js - the responsive feature works well for some elements but not all. Specifically, the labels on my bar chart do not resize along with the window, resulting in a strange look at smaller ...

Effective ways to check for the time discrepancy between dates in moment.js

My server is set to use UTC date format and I am running my node server in UTC as well. I am looking to determine if the current time in Indian timezone (which is +5.30) is greater than 8AM, and if so, send an email notification. How can I achieve this u ...

How can I make tooltipster display tooltips properly?

I have been struggling to customize tooltips using a library called tooltipster. Here is what I currently have: Head of index.html: <head> <!--TOOLTIP CSS--> <link rel="stylesheet" type="type/css" href="node_modules/tooltipster-master ...

Avoid unnecessary renders by only updating state if it has changed from the previous state

Is there a specific React lifecycle method that can trigger a re-render only when the updated state differs from the previous state? For instance, consider the code snippet below: class App extends Component { constructor() { super(); this.state ...

Incorporating an HTTP header into d3.json using queue.js

I know that I can include a header in a D3 JSON request by using the following code: d3.json("http://localhost:8080/data") .header("Application-ID", "1") However, I'm uncertain about how to add this header when utilizing queue's defer method. ...

Tips for extracting JSON data from an API with identical names as values

I am working on a project to create a data search system using JSON. The JSON data is stored in a REST API, and the structure of the API is as follows: [ { "info": "cute but big animal", "type": "pig", ...