Detecting drag and drop in HTML text box?

I have a regular search box on my web page. It is filled with the text: Search this website

This text is deleted when you click on this field to enter your search query:

 onfocus="if(this.value=='Search this website') { this.value=''}; 

But how can I determine when someone drags text from a page into the search box, as I often do myself? onfocus does not start and the previous text remains.

+2
javascript html
source share
3 answers

You need to use the ondrop event, which will fire only if the ondragenter and ondragover events are canceled. It turns out this is a little more complicated because the behavior in Firefox is different from IE, Safari and Chrome.

 (function () { var inp = document.getElementById("test"), chg = false; inp.ondragover = inp.ondragenter = function () { chg = inp.value == "Drop here"; return false; } inp.ondrop = function (evt) { evt = evt || event; if (chg) { this.value = evt.dataTransfer.getData("text") || evt.dataTransfer.getData("text/plain"); return false; } } })(); 

An example is Firefox 3+, IE5 +, Chrome, and Safari. Nearby, as far as I can tell, Opera does not support this event. At least you can make it work for 95% of your visitors.

Drag and Drop Operations - MDC

+4
source share

Have you tried to use the onchange event?

By the way, there is a great little jQuery plugin called jquery-defaultvalue that handles all corner cases for you. If you use jQuery anyway, it's worth a look.

0
source share

See - http://www.simplecoding.org/drag-drop-s-ispolzovaniem-html5.html , but the page is in Russian (Google Translate will help).

0
source share

All Articles