Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html5 drag and drop using jquery (not jquery UI)

I want to implement the w3schools EXAMPLE for html5 drag and drop using jquery instead of javascript.

here is my implementation in jquery JSFIDDLE

I just changed the html inline declaration of events into jquery on() method keeping everything else same.

I cant understand why jquery doesnt recognize the events like drop dragstart when i see lot of snippets online.

HTML:

<div id="div1"></div>
<img id="drag1" src="http://www.w3schools.com/html/img_logo.gif" draggable="true" width="336" height="69">

JQUERY:

$(document).ready(function(){
  $("#div1").on("dragover",function(e){
    e.preventDefault();
  });
  $("#drag1").on("dragstart",function(e){
    e.dataTransfer.setData("Text",ev.target.id);
  });
  $("#div1").on("drop",function(e){
    e.preventDefault();
    var data=e.dataTransfer.getData("Text");
    e.target.appendChild(document.getElementById(data));
  });
});
like image 677
Sagi_Avinash_Varma Avatar asked Apr 26 '14 10:04

Sagi_Avinash_Varma


People also ask

Does HTML5 support drag-and-drop?

Complete HTML/CSS Course 2022 Now HTML 5 came up with a Drag and Drop (DnD) API that brings native DnD support to the browser making it much easier to code up. HTML 5 DnD is supported by all the major browsers like Chrome, Firefox 3.5 and Safari 4 etc.

How do I drag data in HTML5?

HTML Drag and Drop (DnD) is a feature of HTML5. It is a powerful user interface concept which is used to copy, reorder and delete items with the help of mouse. You can hold the mouse button down over an element and drag it to another location. If you want to drop the element there, just release the mouse button.

Is drag-and-drop possible in HTML?

In HTML, any element can be dragged and dropped.


1 Answers

You want to use orginal event, not jQuery one to get/set data:

e.originalEvent

Fixed jsFiddle

$(document).ready(function(){
  $("#div1").on("dragover",function(e){
    e.preventDefault();
  });
  $("#drag1").on("dragstart",function(e){
    e.originalEvent.dataTransfer.setData("Text",e.target.id);
  });
  $("#div1").on("drop",function(e){
    e.preventDefault();
    var data=e.originalEvent.dataTransfer.getData("Text");
    e.target.appendChild(document.getElementById(data));
  });
});
like image 100
A. Wolff Avatar answered Sep 28 '22 14:09

A. Wolff