esafwan
esafwan

Reputation: 18059

HTML5 Drag & Drop - Get a selection text dropped to a droppable element

I want to Drag & Drop a text selection from outside the tab/window to a droppable element. So far am able to drop either a file or an element from within the page to the dropzone/droppable element.

I am able to get drop for file with the below code. I have the full working example here.

var dropZoneTwo = document.querySelector('#dd-files');

dropZoneTwo.addEventListener('drop', function(e) {
  if (e.preventDefault) e.preventDefault(); 
  if (e.stopPropagation) e.stopPropagation();

  this.className = "";

  var fileList = e.dataTransfer.files;

    console.log(e);

  if (fileList.length > 0) {
    readTextFile(fileList[0]);
  }
});

I want the user to have the ability to drag and drop links, texts etc. I want to detect these text and then do certain actions. For example, if user drag and drop url from a youtube video, I will detect it as a youtube url and load embed code etc...

Upvotes: 0

Views: 373

Answers (1)

Craveiro
Craveiro

Reputation: 503

Inside your eventListener for the drop you can get the URL of what's being dragged with

e.dataTransfer.getData('URL');

Having the URL you can retrieve content and display whatever you want. To show a youtube video thumbnail, for example, parse the URL obtained with the code above to het the youtube video id and use something like this

<img src="http://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg">

Upvotes: 2

Related Questions