0

Managed to get highlighted text from within a textarea and transfer it into another textarea. But when the code is edited so that it gets the highlighted text from within a div instead, it does not work...

Any ideas why this is happening? Thanks.

<div id="quote"> load transcript in here instead and grab text from here</div> // does not work

<textarea id="quote" readonly> // works
load transcript in here
</textarea>


<textarea contenteditable="false" id="output" name="selected"></textarea> // outputs highlighted text here


<script>

var quotearea = document.getElementById('quote')
var output = document.getElementById('output')
quotearea.addEventListener('mouseup', function(){
    if (this.selectionStart != this.selectionEnd){ // check the user has selected some text inside field
        var selectedtext = this.value.substring(this.selectionStart, this.selectionEnd)
        output.innerHTML = selectedtext
    }
}, false)

</script>

fiddle:

https://jsfiddle.net/Lzgyh2kd/

Alexandre Lavoie
  • 8,711
  • 3
  • 31
  • 72
Jonathan Laliberte
  • 2,672
  • 4
  • 19
  • 44

2 Answers2

1

I answered your question in the comments and deleted it.

You're using selectionStart and selectionEnd methods that works only on input elements. For your solution used instead document.selection.createRange().text that gets the selected text in the document (inputs, divs, etc., doesn't matter).

Here's the fiddle:

Working demo

Gerardo
  • 979
  • 1
  • 7
  • 15
  • Thanks mate! The solution makes perfect sense. Much appreciated. – Jonathan Laliberte Feb 17 '17 at 05:27
  • 1
    Just FYI the code in the fiddle just works for the entire document, doesn't use an specific selector, so if you want to use it only in a div that won't work. – Gerardo Feb 17 '17 at 05:36
  • yeah i noticed, if there's a way around that so that it takes from a specific selector that would be cool, otherwise shouldn't be too much of a problem anyway. Kudos. – Jonathan Laliberte Feb 17 '17 at 05:38
  • 1
    Sure, that's possible. You can search here how to create a selectionrange of an specific element and get its content. If you dont find anything I'll send you a fiddle tomorrow morning. Cheers. – Gerardo Feb 17 '17 at 05:46
0

Someone in the comments answered it with a fiddle that had two textarea, but edited one to a div and it seems to work. Cheers. (Edit- turns out a div was not required, it took straight from the page, so a workaround)

<div name="" id="original">
Load transcript in here.
</div>

<textarea name="" id="copied" cols="30" rows="10"></textarea>

<script>


var text = '';
function copyText(e) {
    text = (document.all) ? document.selection.createRange().text : document.getSelection();
    document.getElementById('copied').value = text;
}
document.onmouseup = copyText;
if (!document.all) {
    document.captureEvents(Event.MOUSEUP);
}


</script>

Working fiddle here:

https://jsfiddle.net/eLwy4eLp/1/

Jonathan Laliberte
  • 2,672
  • 4
  • 19
  • 44