2

I have a javascript function to select the content of a cell (html table) onclick="select_cell(this)". No surprise, it works fine everywhere except IE. The weird part is that I discovered that if I set a timeout, it works... 100 ms was not enough: it was working half the time. With 200 ms, it's working great!

function select_cell(element){

        if (window.getSelection) {
            var range = document.createRange();
            setTimeout(function(){
              range.selectNode(element);
              window.getSelection().addRange(range);
            }, 200);
        }
        else if (document.selection) {
            var range = document.body.createTextRange();
            range.moveToElementText(element);
            range.select();
        }
}

The thing is that I don't like this timeout. Someone has an explanation? Or even better, a solution to skip this timeout?

pmrotule
  • 9,065
  • 4
  • 50
  • 58
  • 2
    Does this work for you -> http://jsfiddle.net/WdeTM/372/, and did you place that code after the elements in the DOM. – adeneo Mar 10 '14 at 19:08
  • Yeah man! It works! Thank you so much! The main problem was if(document.selection). I replaced it by if(document.body.createTextRange) like your example and the problem was fixed! – pmrotule Mar 10 '14 at 19:57

1 Answers1

0

i posted here an answer for text selection, may be helpful to you, check this out

Community
  • 1
  • 1
Amir Sherafatian
  • 2,083
  • 2
  • 20
  • 32