views:

562

answers:

2

Using jQuery's dialog I came across the following quirk (tested in FF3):

  1. User selects text
  2. In code, open up a jQuery dialog
  3. BUG: the text gets unselected

(text could be in a textarea or just an HTML on the page)

So, to me it seems like a funny (and annoying) bug or a quirk, but maybe there's a good explanation for that. And what interests me most, is how to preserve this text selection after opening the dialog?

Here's some code:

function getSelectedText() {
 var t;
 if (d.getSelection) t = d.getSelection();
 else if(d.selection) t = d.selection.createRange();
 if (t.text != undefined) t = t.text;
 if (!t || t=='') {
  var a = d.getElementsByTagName('textarea');
  for (var i = 0; i < a.length; ++i) {
   if (a[i].selectionStart != undefined && a[i].selectionStart != a[i].selectionEnd) {
    t = a[i].value.substring(a[i].selectionStart, a[i].selectionEnd);
    break;
   }   
  }   
 }   
 return t;
}

 $("#dialog").dialog({
    autoOpen: false,
    bgiframe: false,
    height: 60,
    width: 80,
    modal: false,
    show: 'highlight',
    title: 'wc'});
 alert(getSelectedText()); // Text is here      
 $("#dialog").dialog("open");
 alert(getSelectedText()); // Text is not selected here :( damn!

Thanks!

A: 

Welcome to the murky waters of text selection! I share your frustration. If it's a bug, there is nothing one can do about it. I guess who would have to manually preserve the selection and restore it.

A: 

The jQuery dialog will take the user's focus ( you should see one of the buttons selected on the dialog ). Browsers only have 1 focus so you lose whatever they had selected.

You should just retrieve the start and end positions of the user's selection before you do the dialog, and then reselected it after the dialog goes away.

I don't have any example code for getting and setting user's selection, but a web search should find you some.

Something like :

$("dialog").focus(function() {
  // save the selection
}).blur(function() {
  // set the text selection
});

[edited (Nickolay): see http://stackoverflow.com/questions/1592637/keep-text-selection-when-focus-changes/1592906#1592906 for more code]

Paul Tarjan