0

I am really struggling with this. I have two div on a page. The first one has got contents (mainly text). On the second div, I want to display the content of first div based on the position. for example if i select line 30, then the content of that line will be displayed in second div. Is there any idea to do that?

Thank you

  • 2
    You need to show what you already tried to let people help you. If you haven't try anything yet and you have no idea how to do it, you should contact a software house. – Alberto Oct 11 '18 at 14:31
  • Could you be more precise ? How is formatted the content of your first div ? – R.Duteil Oct 11 '18 at 14:35

1 Answers1

0

This answer assumes you only want to copy the selected text to the new div and provices a basic idea how you can do so

In order to achieve that kind of behaviour you need to listen to the mouseup event in your container where you want text to be selected. That way we assume, that the user was selecting something and ended the selection.

I have prepared this JS fiddle for you: https://jsfiddle.net/djzkcw0m/

Code for the prove of concept: HTML

Highlight some text with mouse in this container:
<div id="test">
This is some text and you can highlight it with your mouse
</div>
Result div:
<div id="result"></div>

JS

const testDiv = document.getElementById('test');
const resultDiv = document.getElementById('result');

function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}

testDiv.addEventListener('mouseup', function(e) {
    const selectedText = getSelectionText();
    resultDiv.textContent = selectedText;
})

note Method "getSelectionText()" is found from a related question Get the Highlighted/Selected text

noa-dev
  • 3,561
  • 9
  • 34
  • 72
  • Thanks. It is bit similar but the div test will have multiple lines and if i select a line position, then that content will be displayed in the result – Hami Nepali Oct 11 '18 at 22:37
  • Let me know if you need further assistance, maybe that was enough for you to figure out the correct approach for your problem :) – noa-dev Oct 12 '18 at 10:07
  • Hi, Thanks for the follow up. I am still getting trouble. My plan is to get the content of position of test div into result div. – Hami Nepali Oct 16 '18 at 10:24