I’ve got an interesting little challenge. I need to be able to programmatically change the document selection, as in the text that is selected, not a select box or anything like that, using JavaScript.
Basically, I want to repeat the effect that appears on the Google Adsense site, where selecting in a textarea selects the contents of that text area. But I want to do it with just a random element. It’s easy with a TextArea, but I want my element to maintain it’s lovely formatting.
I’m not actually sure I can do it. With IE, I can set it up to copy the text to the clipboard, but not select it.
You little ripper!
sel = window.getSelection();div = document.getElementById("id");
sel.selectAllChildren(div);
Works a treat in Mozilla.
17 minutes after the fact.
IE seems to have the ability to create alterations to it’s selection:
sel = document.selection.createRange();div = document.getElementById("id");
sel.moveToElementText(div);
However, this doesn’t seem to work. If only IE had decent JavaScript console support. Then I might be able to do this without having to save a huge file to the server and back again…
36 minutes after the fact.
Fuck Internet Explorer.
It was selecting the whole lot, just not updating the display to reflect it!
Grr. Minutes wasted.
48 minutes after the fact.
Doesn’t work in Safari. No selectAllChildren() method.
Fuck Safari too. But less than IE.
1 hour, 16 minutes after the fact.
Actually, really fuck internet explorer.
It is actually setting the selection, or at least creating a range, as I can do an
alert(sel.text);, but the selection isn’t really being changed.That is, if I Ctrl-C, it is not added to the clipboard. I could use the evil
clipboardData = sel.text;command, but I don’t really want to. It’s not really fair to a user to overwrite whatever they had as the clipboard.I did find another site that might be doing what I need. They use an
href="javascript:highlight(0);", which isn’t the right way to do it, but I suspect it’s textarea only, anyway.Oh, and I apologise to IE users who are also getting the crappy resizing as you type I am getting in the comments box!
17 hours, 15 minutes after the fact.