views:

48

answers:

3

I have a normal search box on my webpage. It is filled with text: Search this website

This text is removed when you click into the box to type your search query:

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

But how can I detect when someone drags text from the page onto the search box, as I often do myself? onfocus is not triggered and the previous text remains.

A: 

Have you tried to use the onchange event?

BTW, there is a nifty little jQuery plugin called jquery-defaultvalue which handles all the corner cases for you. If you're using jQuery anyway, it's worth a look.

piquadrat
I checked, and *jquery-defaultvalue* actually only handles the focus and blur events. It doesn't look like it handles any corner cases at all :-)
Andy E
A: 

See - http://www.simplecoding.org/drag-drop-s-ispolzovaniem-html5.html , but page on the russian language (Google Translate would help).

HWTech
+3  A: 

You need to use the ondrop event, which will only fire if the ondragenter and ondragover events are cancelled. Turns out it's a bit trickier than that because the behavior is different in Firefox than 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;
        }
    }
})();

Example - Firefox 3+, IE5+, Chrome and Safari. Near as I can tell, Opera doesn't support the event. At least you can get it working for 95% of your visitors though.

Drag Operations - MDC

Andy E
Browser support?
Tim Down
@Tim: IE, Firefox, Chrome and Safari (complete with working example). Was a bit of a pain getting it to work in Firefox because it changes the value of the input before firing the drop event. The solution was to move the value check to the *ondragover/ondragenter* event. Opera is the odd one out, these events are unsupported there, but there's no harm in using them for the browsers that do support them.
Andy E
Cool. I did seem to remember it being a bit tricky last time I looked at this stuff.
Tim Down