Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get notified about dragged images within a contenteditable div

Tags:

javascript

I have a div which has contenteditable="true" and which contains some html. This html may include images.

Since contenteditable="true" the user can move images by dragging them to a new position. But I need my code to be notified each time a image is moved, in a way where I get both the image element which is being moved, and the target node where the image is dropped. How do I do that?

My current solution adds a Drop listener to my div element which is contenteditable, and then I do get a drop event each time the user moves an image, but I can't get the dom node with the image which the user moved.

Also: Dragging an image, seems to copy the DOM node, instead of moving it. Is this true? (Tested in firefox).

like image 901
MTilsted Avatar asked Jul 27 '15 16:07

MTilsted


1 Answers

I would suggest a following pure JavaScript solution

HTML:

<div id="space" contenteditable="true">
  Hello <img width="300" class="contentImg" src='http://www.independent.co.uk/incoming/article9859555.ece/alternates/w620/Dr-Talyor.jpg'/> dude!
</div>

CSS:

#space {
  width: 500px;
  height: 500px;
  background-color: #000000;
  color: #ffffff;
}

JavaScript:

var draggedImg;
document.addEventListener("dragstart", function( event ) {
    // IE uses srcElement, others use target
    var targ = event.target ? event.target : event.srcElement;
    if (targ.className == 'contentImg'){
      draggedImg = event.target;
    }
}, false);

document.addEventListener("dragend", function( event ) {
    if(draggedImg){
      alert("It's moved!");
      console.log('Here is data', draggedImg);
      draggedImg = null;
    }
}, false);

You'll find an image node in draggedImg variable.

Please review a working example here: http://jsfiddle.net/o09hLtch/2/

like image 68
Alexander Schwarzman Avatar answered Nov 07 '22 05:11

Alexander Schwarzman