Get the position of clicked word in textbox (Javascript) - javascript

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>

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);
}

Related

Get content of div including input values

I'm replacing some specific character by inputs via regexp.
Div looks like that:
1) <div>Text text text text <input> text text <input> text</div>
2) <div>text Text <input> text <input> text text Text</div>
Is it possible to get whole text including input values from a div (with id 'body' in my case)?
jQuery code:
var body = data.body.replace(/\.\.\./g, "<input class='bodyy' type='text' size='2' />");
$("#body").html(body);
Fiddle: https://jsfiddle.net/uepf87fc/
You can parse it yourself with a function, here's an example:
function getTextWithInputValues(id) {
var element = document.getElementById(id);
if (!element) {
return null;
}
var elementText = element.innerHTML; // Get the entire text from your element
var elementInputs = element.getElementsByTagName('input'); // fetch all inputs from your element
// replace all input fields with their respective values
Object.getOwnPropertyNames(elementInputs).forEach(
(input) => {
var inputText = elementInputs[input].outerHTML;
if (elementText.search(inputText) > 0) {
elementText = elementText.replace(inputText, elementInputs[input].value);
}
}
);
return elementText;
}
You can test it right here by opening a console, paste this code in, then type in something in the search box on the top of the page (don't click search, just type in something), then when you call the function in the console like getTextWithInputValues('search') it will output something like
<svg ......</svg>
your-text-here
<button .....</button>
Hope this helps.
Even though you asked for REGEX, I don't believe it is by any means needed.
This will return the data in an array. With the first index being the body text, and each input field value thereafter.
var values = [];
values.push($('#body').text());
var inputs = $('#body input');
for(var i = 0; i < $(inputs).length; i++)
{
var currentElement = $(inputs)[i];
values.push($(currentElement).val());
}
console.log(values);

How to highlight a button based on the format in the text content?

I have a requirement where I have to highlight the appropriate button based on the format of the word selected in the textarea.
For instance,
If i have a text inside the textarea like, I am a new _text area_.
and if user clicks on the word _text area_ or brings the cursor point over that text the button bold should be highlighted, as the word is enclosed within _ .
I tried to use onclick event to get the index and traverse the string using regex .However it doesn't seem to work.Could anyone suggest me how to do this?
var getFormat = function(event) {
var element = document.getElementById('editor');
console.log('editor', element);
var startIndex = element.selectionStart;
console.log('startIndex', startIndex);
var selectedText = element.value.slice(startIndex);
var stringMatch = selectedText.match(((\ * )\ 2)(.* ? )\ 1));
console.log('stringMatch', stringMatch);
}
<html>
<body>
<textarea onclick='getFormat(event);' rows='10' cols='10' id='editor'></textarea>
<button>Bold</button>
</body>
</html>

Remove selected/highlighted text

I have some text in div selectable and I want to allow the user to remove text by selecting the text using their cursor.
It works fine, but if you click on the text, everything is removed. If you click and drag to select, it works fine.
What can I do to make it work with my text properly. If user clicks the text, it shouldn't remove everything.
jsFiddle for testing.
jQuery:
if (window.getSelection().toString() != "") {
selectedText = window.getSelection().toString()
var text1 = $(".selectable").text().split("")
pointStart = window.getSelection().anchorOffset
pointEnd = window.getSelection().focusOffset
if (pointEnd < pointStart) {
pointStart = pointEnd
}
text1.splice(pointStart, selectedText.length);
text1 = text1.join("")
} else {
selectedText = $(".selectable").text()
var text1 = ""
}
$(".selectable").text(text1)
Example HTML:
<div class="selectable">
Hello world what is 進撃の巨人 reality test test... test.
</div>
EDIT: Potential solution:
if (window.getSelection().toString() == "") {
return false;
}
Your error lies on the else part. If the user has not selected any text, which is the case of simply clicking on the text, your else code block gets executed.
In that block you assign var text1 = "";
Later you assing text1 as the text content of your $(".selectable") element.
Just change that line to:
var text1 = selectedText;
See the updated fiddle
I also suggest you declare var text1 only once at the top of your mouseup handler and change your assignments from var text1 = "value" to text1 = "value"
See: var hoisting

How to highlight/mark any text passages, so that javascript can change it?

To be a bit more specific: A user should be able to highlight text, so that Javascript could replace this highlighted part with a text-area. My problem is, that i don't know how to edit any part of the text!
I hope my example drawing helps to understand my very specific question!
I have built a little script in JSFiddle here is the link: http://jsfiddle.net/WT5XE/2/
JS
var textB = ''; // text before split
var textA = ''; // text after split
...
// here starts the magic, split current text and insert a new input box
var splitted = that.innerHTML.split(text);
textB = splitted[0];
textA = splitted[1];
$('#text').empty();
// Append the text before in a new span
$('#text').append('<span>'+textB+'</span>');
// Create the input box and attach key listener (on enter it will terminate and set the new text)
$('<input value="'+text+'">')
.keypress(function (e) {
if (e.which == 13) {
isInput = false;
var newText = this.value;
var text = textB+newText+textA;
$('#text').empty();
$('#text').append(text);
return false;
}
})
.appendTo('#text');
// Append the text after in a new span
$('#text').append('<span>'+textA+'</span>');

Shuffle selected text on <textarea> using JavaScript

When I select some texts on the <textarea> using my mouse, how can I shuffle/scramble it by clicking on a button?
I've searched for something similar to what I want here on SO, and I saw some who use substring, selectionStart, and selectionEnd.
What I want is: when I select some texts with my mouse, it will be shuffled/scrambled when I click on a button, and the rest of the texts on the <textarea> that are not selected should remain untouched/intact.
I just want to perform an action on the selected texts.
It's more similar to a rich text editor like when you select on some texts, then click on bold button, the selected texts will become bold.
P.S.
It should be shuffled by individual characters.
EDIT:
Got it! I just needed to separate the selection string. My code works now. This is very helpful - https://stackoverflow.com/a/9605191/1101391
Unfortunately, IE 9 and below does not support selectionStart and selectionEnd properties on <input> and <textarea>. Here's the solution that worked for me - https://stackoverflow.com/a/9276457/1101391
You have access to the full text and know the substring where the selection starts and ends. Try something like this:
var txtArea = document.getElementById("foo");
var before = txtArea.value.substr(0, txtArea.selectionStart);
var selection = txtArea.value.substr(txtArea.selectionStart, txtArea.selectionEnd + 1);
var after = txtArea.value.substr(txtArea.selectionEnd, txtArea.value.length);
txtArea.value = before + scrambleThisString(selection) + after;
Suppose you name the textarea with ID content:
var textarea = document.getElementById('content');
var content = textarea.value;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var before = content.slice(0, start);
var after = content.slice(end);
var selected = content.substring(start, end);
selected = shuffleStringByMagic(selected);
textarea.value = before + selected + after;

Categories