Text selection issue

Á

Álvaro G. Vicario

I've written this function to select text from JavaScript in a web page:

/*
* Selects node's text
*
* Usage: <input type="button" value="Select"
* onclick="selectNode(document.getElementById('foo'))">
*/
function selectNode(node){ // v2008-04-23
// Create a range
try{
var range = document.createRange();
}catch(e){
try{
var range = document.body.createTextRange();
}catch(e){
return;
}
}

// Asign text to range
try{
range.selectNode(node);
}catch(e){
try{
range.moveToElementText(node);
}catch(e){
return;
}
}

// Select range
try{
var seleccion = window.getSelection();
seleccion.addRange(range);
}catch(e){
try{
range.select();
}catch(e){
return;
}
}
}

I use this script to select data tables double clicking on them (so I
can then copy and paste into a spreadsheet or whatever) and it works in
both IE and Firefox (not Opera or Konqueror). However, it has a weird
issue in Firefox. Most of the times (but not always) there's an extra
cell at the end of the table, with random contents taken from the table
(but not always the same). Firebug's DOM viewer doesn't show that extra
cell but the cell gets there as soon as I copy the selection into clipboard.

I've seen this behaviour in Firefox 2 and Firefox 3 beta 5. It also
happens in Windows XP, Windows Vista and Fedora 8. It's all random but
easy to reproduce.

Have I made any obvious mistake in my code?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top