Wednesday, December 10, 2008

Drag and drop in a text box

I have an application that needs to fire an onchange javascript event when data in one of 21 to 119 text boxes changes (yes, it sounds like a problem, but the UI works!). Sounds easy...

But it is possible to drag and drop text from one text box into any of the others.

This is the one situation where MS IE actually does a decent job - IE fires all the drag events (ondrop, ondragstart, ondragend, etc) where as all the other browsers (firefox, chrome, konqueror, opera, safari) do not!

So IE first...
ondrop set variable window.dragged to be the destination text box, and ondragend (fired on the source text box) calls the onchange function on both source and destination - see, easy!

Now the hard bit....
This is only an approximation, but seems to work well. (We'll see what the testers do with it!)
When onmousedown is fired, and there is text selected in the textbox make a note of the id of the text box (window.dragged) - this indicates that we may have a drag event,
Subsequently, when the onmouseout event is fired (that doesn't originate from the text box that was source for the onmousedown event), and window.dragged is set, call the onchange function on both source and destination.

Yes, its a hack, but it seems to work.

To summarise:
onmousedown fired at start of text selection
onmouseup fired at end of text selection
onmousedown fired at start of drag - there is text selected, so we set window.dragged to this.id
** user drags text to another field, and drops
onmouseout fired at source text box
** user moves mouse out of destination text box
onmouseout event fired on destination text box - signal to call onchange function on the source (window.dragged) and destination (this)

Possible improvements:
1. Maybe the onmouseout code should be in document.onmousedown (update: not required)
2. Save needs to re-check each - just to be sure.... (update: yes, to force update before form is submitted using enter key after drop)

No comments:

Post a Comment