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!

2
  • as far as I can tell, this is normal behavior. If you select text and then click anywhere else on the page, the selection is gone. Commented May 5, 2009 at 13:34
  • It's not a click - the dialog is opened programatically (using setInterval) and there's no click involved. Commented May 5, 2009 at 13:36

1 Answer 1

2

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 Keep text selection when focus changes for more code]

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.