Reputation: 1239
I have a textbox with multiple sentences, and when I click on a word, I need to get the position of the word in this textbox.
The code actually just get the whole text from the textarea and writes it in another text area. I am struggling to get specific position of the character (or word) I clicked on.
What it should do is to copy just the text before clicked word/character.
var themaintextarea = document.getElementById('textarea');
themaintextarea.addEventListener('click', replace_sentence);
function replace_sentence(e){
var themaintext = document.getElementById("textarea").innerHTML;
//alert(thereplace);
document.getElementById("curent_sentence").value = themaintext;
theselection = window.getSelection();
var therange = theselection.getRangeAt(0);
var sometext = therange.toString().trim();
alert(sometext);
}
<textarea id="curent_sentence"></textarea>
<div id="textarea" contenteditable>I <span>like</span> apples. I <span>like</span> apples.
<br>
I <span>like</span> apples.</div>
Upvotes: 0
Views: 992
Reputation: 961
EDITED : Heres the fiddle to select the word before the word clicked on. Note: no spans are used in this. https://jsfiddle.net/Lnkav5ca/5/
I think i understood what you're looking for. https://jsfiddle.net/Lnkav5ca/1/ I put all the clickable words in a class and add event listeners to that class. So when the word is clicked on it gets inserted into the text box.
var themaintextarea = document.getElementsByClassName('clickable');
for (var i = 0; i < themaintextarea.length; i++) {
themaintextarea[i].addEventListener('click', replace_sentence);
}
function replace_sentence(e){
console.log(e);
var themaintext = e.target.innerHTML
//alert(thereplace);
document.getElementById("curent_sentence").value = themaintext;
theselection = window.getSelection();
var therange = theselection.getRangeAt(0);
var sometext = therange.toString().trim();
//alert(sometext);
}
Upvotes: 1