Link to home
Start Free TrialLog in
Avatar of renisenbb
renisenbb

asked on

Javascript: Range object

I see different behavior in IE-11 (text becomes blue) and FF (text becomes grey) with this code.
In IE, the text can be copied to the clipboard because it's selected, and in FF it cannot.
<p id="p1">
This is a line of text
</p>
element = document.getElementById("p1");
var selection = window.getSelection();
txtRange = document.createRange();
txtRange.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(txtRange);
Avatar of HainKurt
HainKurt
Flag of Canada image

https://jsfiddle.net/4o4g3by1/

add
window.focus();

Open in new window

Avatar of renisenbb
renisenbb

ASKER

i still see grey text in your jsfiddle
but I see blue :)

Chrome
Version 58.0.3029.81 (64-bit)
I was looking at firefox. Yes, i see that it works for Chrome. Thanks for that.
Is there a solution for Firefox too?
ummm...

add this

Document.getSelection();

Open in new window

It's not working in Firefox. I have this:
element = document.getElementById("p1");
var selection = window.getSelection();

txtRange = document.createRange();
txtRange.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(txtRange);
//window.focus();
Document.getSelection();
window.focus();
did you try

window.focus();
Document.getSelection();
Yes, that didn't work either. You mean document.getSelection() correct?
yes, document.getSelection()

here the updated version
https://jsfiddle.net/3rhgL1c3/
try adding blur/focus

window.blur();
window.focus();

Open in new window

It seems to work in Firefox if i add the attribute contenteditable=true to the <p> element. IE and Chrome continued to work with this addition.
Not sure what the side effects of doing this will be....
click and you can edit it :)
one more thing

add this code to a button click
is it working in FF

https://jsfiddle.net/mywop17z/
ASKER CERTIFIED SOLUTION
Avatar of HainKurt
HainKurt
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you so much, it was a very tricky issue for me
meantime, here is the solution, using jQuery
call this and pass id of any element...

function SelectText(element) {
  var doc = document,
    text = doc.getElementById(element),
    range, selection;
  if (doc.body.createTextRange) {
    range = document.body.createTextRange();
    range.moveToElementText(text);
    range.select();
  } else if (window.getSelection) {
    selection = window.getSelection();
    range = document.createRange();
    range.selectNodeContents(text);
    selection.removeAllRanges();
    selection.addRange(range);
  }
}

Open in new window