Hidden text that can be dragged from the browser?

How can you create an html element that when you drag and drop hidden text or a drag element from the browser into the text editor, will be inserted into the editor?

My first thought was to use the href attribute in the anchor tag:

<a href="hidden message text here">Drag me into a text editor!</a> 

This works fine in chrome, but firefox and safari remove spaces from the href value, which renders the copied message unusable.

Any ideas?

+6
source share
2 answers

Instead of manipulating the default behavior of the browser to drag text / links / images, you want to set the data to something arbitrary in the dragstart .

For example, use text from a hidden #content :

 $('[draggable]').on('dragstart', function(e) { var content = $(this).find('#content').text(); // Can be anything you want! e.originalEvent.dataTransfer.setData('text/plain', content); $(this).addClass('dragging'); }); 

Here is a working JSFiddle

+3
source

For versions of IE below 10 that do not support the dataTransfer method, I discovered another rather hacky way to make this work.

Basically you make the text invisible with css, then use js to select it in the background on hover.

HTML

 <div id="drag_area" draggable="true"> <div id="text"> hidden text </div> </div> 

CSS

 #text { filter:alpha(opacity=0); opacity:0; overflow:hidden; z-index:100000; width:180px; height:50px } 

Js

  function selectText(elementID) { var text = document.getElementById(elementID); if ($.browser.msie) { var range = document.body.createTextRange(); range.moveToElementText(text); range.select(); } else if ($.browser.mozilla || $.browser.opera) { var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(text); selection.removeAllRanges(); selection.addRange(range); } else { var selection = window.getSelection(); selection.setBaseAndExtent(text, 0, text, 1); } } $('#drag_area').hover(function(){ selectText('text'); }); 

Here it is combined with Anson's solution and a small sign: <Up> http://jsfiddle.net/zaqx/PB6XL/udap> (works in IE8, IE9 and in all modern browsers)

EDIT: Updated Fiddle in the comments below.

+1
source

All Articles