0

I want to select the contents of a DIV (like highlight when you click and drag) when the user clicks on a button. The (hidden) div contains text that needs to be dragged to a 3rd party app outside the browser as input. In other words: I want to simulate the user selecting the contents of a textarea, click and dragging it to another app.

I'm using the PrototypeJS framework, and I came this far:

  • put an mousedown observer on the button that needs to be pressed.

I've searched pretty hard already to find a way to select text in an html element, but couldn't find anything. The Prototype API doesn't seem to have a good function that can select the contents of a textarea or an element. It does have Form.Element.select() but that only works on input fields apparently.

Can someone help me out?

Rob W
  • 341,306
  • 83
  • 791
  • 678
Coen
  • 153
  • 1
  • 1
  • 13

1 Answers1

0

Based on the answer I gave yesterday to a similar question, in Prototype you could do it this way:

$('elId').observer('click', function(e){
  var selectTarget = Event.element(e); // Get the element
  if(selectTarget != null) {
     if(selectTarget.tagName == 'TEXTAREA' || (selectTarget.tagName == "INPUT" && selectTarget.type == "text")) {
         selectTarget.select();
     } else if(window.getSelection) { // FF, Safari, Opera
         var sel = window.getSelection();
         var range = document.createRange();
         range.selectNode(selectTarget);
         sel.removeAllRanges();
         sel.addRange(range);
     } else { // IE
         document.selection.empty();
         var range = document.body.createTextRange();
         range.moveToElementText(selectTarget);
         range.select();
     };
  };
});
Community
  • 1
  • 1
Doug Neiner
  • 65,509
  • 13
  • 109
  • 118
  • this one did the trick, thanks! Frankly I already found the createRange() methods and corresponding code for IE/non-IE, but fiddling with it couldn't get it to work properly. In fact, you still have to be a bit lucky to get it to go right, but we'll see. – Coen Jan 16 '10 at 17:38
  • @Coen great! Don't forget to mark the answer as excepted if it answered your question. Good luck on your project! – Doug Neiner Jan 16 '10 at 17:41
  • @Coen - `createRange()` works fine in all browsers that implement it. If you have code using it that isn't working consistently then it is almost certainly a fault in your code. You could post a new question if you need help working out why it isn't working. – Tim Down Jan 17 '10 at 14:10