I get the cursor position at time a. Then I get the cursor position at time b. I want to make a range from the cursor position at time a to the cursor position at time b. Time a and b are start and end of ctr-v (paste).
I get the cursor position like so - or rather a range at the cursor position.
sel = window.getSelection();
range_time_a = sel.getRangeAt(0).collapse(true);
But, how do I use range_time_a and range_time_b to create a new range that starts at range_time_a and ends at range_time_b?
I have seen code to get the element with the cursor and to get the offset within that element. I could use that for setStart() and setEnd, but it seems like there should be an easier way since I've already got two ranges.
EDIT This actually won't give you what you're looking for... This is really complicated. My initial suggestion of commonAnscestorContainer.innerHTML will give you too much back (all the HTML of the closest parent container to your selection).
First, you're probably going to want to trigger this code on an eventHandler that fires when the user presses ctrl+c (discussion here: How to detect Ctrl+V, Ctrl+C using JavaScript?).
If you only want to get the text selected, that's easily done:
range = window.getSelection().toString();
You don't need to check the selection at various times - you only need to capture it at the point the user hits ctrl-c.
getSelection is not meant for capturing the HTML of a selection. You can capture text & remove text, move to the start/end of the selection and a bunch of other things described here, but you can't grab HTML.
Big part of the problem is that this isn't part of any stanfard spec (see this link). Another reason its not consistent across browsers, or supported in IE7/8.
Some non-standards based examples of how to get more info out of range selections can be found here if you really need to do this - Get a range's start and end offset's relative to its parent container
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With