Empty Drag'n'drop dataTransfer.getDataInstantiationException

I'm struggling to figure out how to make drag and drop functionality work. The getData/setData methods are puzzling me.

Here's the code I'm working with: http://jsfiddle.net/ASKte/218/

var el = angular.element(document.getElementById('drag'));
el.attr("draggable", "true");
el.bind("dragstart", function(e) {
    e.dataTransfer.setData('text', 'Why won't you show up?!')         
});

var target = angular.element(document.getElementById('drop'));
target.bind("dragover", function(e) {
    if (e.preventDefault) {
        e.preventDefault(); // Required for dropping items.
    }
    return false;
});

target.bind("dragenter", function(e) {
    console.debug(e.dataTransfer.types);
    console.debug(e.dataTransfer.getData('text'));
});

I chose to use AngularJS in this case, as it's part of a larger project.

Whenever I drag the top square onto the bottom one, the value retrieved by getData('text') is always blank. I'm baffled by this issue...

Any insights or suggestions would be greatly appreciated!

Thank you in advance.

Answer №1

To ensure security, the data is only accessible during drag and drop actions on this website. This prevents unauthorized data extraction by other websites.

var el = angular.element(document.getElementById('drag'));
el.attr("draggable", "true");
el.bind("dragstart", function(e) {
    e.dataTransfer.setData('text', 'Where have you gone?!?!')         
});

var target = angular.element(document.getElementById('drop'));
target.bind("dragover", function(e) {
    if (e.preventDefault) {
        e.preventDefault(); // Necessary. Allows us to drop.
    }
    return false;
});

target.bind("drop", function(e) {
    console.debug(e.dataTransfer.types);
    console.debug(e.dataTransfer.getData('text'));
});  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="drag" style="width: 100px; height: 100px; background-color: blue;"></div>

<div id="drop" style="width: 100px; height: 100px; background-color: green;"></div>

Answer №2

For those seeking to retrieve data from various drop-events, the recommended approach is to utilize dataTransfer.types. One can work around the issue of dataTransfer.types automatically converting characters to lowercase by employing methods like JSON.parse, JSON.stringify, and encoding/decoding uppercase characters.

When setting data:

event.dataTransfer.setData(encodeUpperCase(JSON.stringify(value)), '');

When retrieving data:

const data = JSON.parse(decodeUpperCase(event.dataTransfer.types[0]))

The process of encoding/decoding could be outlined as follows:

  const UPPERCASE_PREFIX = '^{';
  const UPPERCASE_SUFFIX = '}^';

  function encodeUpperCase(str: string): string {
    return str.replace(/([A-Z]+)/g, `${UPPERCASE_PREFIX}$1${UPPERCASE_SUFFIX}`);
  }

  function decodeUpperCase(str: string): string {
    const escapeRegExp = (escape: string) => ['', ...escape.split('')].join('\\');

    return str.replace(
      new RegExp(`${escapeRegExp(UPPERCASE_PREFIX)}(.*?)${escapeRegExp(UPPERCASE_SUFFIX)}`, 'g'),
      (_, p1: string) => p1.toUpperCase()
    );
  }

Although this method is effective, it may inadvertently awaken ancient entities such as Cthulhu.

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

Can we compel Morphia to convert the ObjectId into its hexadecimal representation?

Currently, I am working on a Kotlin multi-project solution. One project defines data classes and an API to access a MongoDB where the ObjectId is automatically created. This particular project uses Morphia version 1.3.2. Entries are stored using the follow ...

Is it possible for a directive to mandate a controller on its parent(s)?

According to the angular documentation, it explains how to define where a directive should search for a controller using the require property. ^^ - The required controller is located by traversing through the element's ancestors. An error is thro ...

Can you explain the variance between using 'npm i' and 'npm install'?

Can you explain the distinction between running npm i and npm install? Both commands are used to install all node Modules listed in the package.json file. While the purpose of both commands is clear - to install modules, there may be subtle differences be ...

Conditions in Controller Made Easy with AngularJS

I have recently started working on implementing a notifications feature. The service will involve making a GET request to a specific URL which will then return an array of notifications. Within the controller, I am in the process of setting up a variable ...

The reference to 'this' object is not functioning properly, indicating that either a 'property' or 'method' is undefined when attempting to access a method through routes

I am encountering an issue with the this reference when calling a method via a route. For example, when I call /api/certifications, it triggers the indexAction method. Within this method, I try to access a property using this.collection but receive an err ...

For each variable, assign a value

Apologies if this question has been asked before, but I'm encountering an issue with a foreach loop in JavaScript. let fields = temp_deviceAllocation.devices.forEach(async (device) => { const fields = await device_model .findOne({ dev ...

My Bootstrap 4 slider is malfunctioning and needs to be fixed

Help with my Bootstrap 4 slider issue! It's only displaying one image instead of three. <title> Welcome - Maqbool Solutions </title> <link rel="shortcut icon" href="images/favicon_Y13_5.ico" type="image/x-icon"> <link rel="st ...

SB Admin 2 menu with multiple levels does not collapse as expected

I'm in the process of integrating the menu from the sb admin 2 template into my Ruby on Rails application: As I gradually added components to test functionality, I successfully implemented the top and side nav bars. However, I encountered an issue wi ...

Replace all existing content on the webpage with an exciting Unity game upon clicking

In an interesting experiment, I am trying to hide a secret href that, once clicked, has the power to wipe out everything on the page, leaving it temporarily blank before replacing it with a captivating Unity game that takes over the entire page. Let me sh ...

Utilize the Angular route scope property $resolve in your controller rather than your view

AngularJS 1.5.0 introduces the $resolve property, which simplifies passing ngRoute resolve data to the view without requiring a controller for directives. This feature is applicable to both directives and regular views. Here is an example: (function() { ...

Patience is key as you wait for the observable to finish

My methods have dependencies where one method needs to complete before the next can be called. process1(data: string) : Observable<string> { this.dataservice.process(data).subscribe( (response) => { return response. ...

Angular's digest loop is a crucial feature that ensures data

What could be the reason behind the digest loop not getting triggered in this code, despite the fact that the value of the now variable is being updated? var app = angular.module('coolName',['ngResource']); app.controller('TimeCo ...

Removing a custom JavaScript reference from a Drupal 7 subtheme is a task that can be accomplished

After following the instructions for handling javascript in Drupal 7, I placed a "myjs.js" file in the js folder located at sites/all/themes/mytheme/js and added a line to the mytheme.info file (scripts[] = js/myjs.js). Upon inspecting the page source of m ...

Issue with the submission button not triggering onclick event correctly

I've been trying to add an onclick event to a submit button. I've searched various tutorial sites and followed all the suggestions, but none of them have solved the issue. Interestingly, when I include an alert in the function being called, it wo ...

Unable to access the users property of the discord.js client

I encountered an issue with the blacklist command that I can't seem to resolve, despite trying multiple solutions. Discord.js version: 13.6.0 Node.js version: 16.13.2 Command snippet: const { MessageEmbed } = require('discord.js'); mod ...

When the value remains unchanged, Angular's @Input() value does not get updated

Upon running this program, I initially receive the output as false, 5, 500 since they have been initialized in the child component. However, upon clicking the update button, I am unable to revert to the previous values. Instead of getting true, 10, 1000, I ...

Generate a random number not found within the given array

Hopefully, I can explain this clearly. Imagine I have 8 boxes with the class .boxA, each containing a numeric value generated from JavaScript: <div class="tfooter"> <div class="boxA" id="bx3" value="3">3</div> <div class="box ...

Switchable radio options

Currently, I am creating a form containing multiple options that are mutually exclusive. However, none of these options are mandatory. That is why I want to enable the user to uncheck a selected radio button by simply clicking on it again. This way, all th ...

Issues with Javascript .map function failing to return accurate components

Encountered an issue with the .map method in my React project not returning the expected value. This is the desired output: const prepInfo = [ <PrepInfo uniqueKey={1} type={'prep'} quantity={'1'} unit={'unit'} suf ...

Is it possible to use v-if in conjunction with a style tag to specify a different source file? Alternatively, is there a more efficient method I

I attempted the example provided below, but unfortunately, it did not function as expected. The reason behind my endeavor is that adding numerous modifiers (--tuned) to achieve the desired outcome seemed impractical. Therefore, I decided to try and link ...