highlight data into popup in javascript - javascript

How to get the mouse hovered text from the textarea and display the content on a popup window using the javascript.In this the user as the freedom to select and hover any text but the text must be a string only and can't be a number or a special symbol , etc present in the textarea.
The code is as follows
Enter text:
<br>
output:
<span id="out"></span>
</div>
<script>
function ShowSelectionInsideTextarea()
{
var textComponent = document.getElementById('Words');
var selectedText;
// IE version
if (document.selection != undefined)
{
textComponent.focus();
var sel = document.selection.createRange();
selectedText = sel.text;
}
// Mozilla version
else if (textComponent.selectionStart != undefined)
{
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos)
window.alert("hello");
}
document.getElementById("out").innerHTML = selectedText;
}
setInterval(ShowSelectionInsideTextarea, 1000);
</script>
The problem here is that the alert is not getting the mouse hovered text and is not being displayed.What to do in this case

Inspired by: How to get selected text from textbox control with javascript
Here you go:
function getSelectionInsideTextarea(textComponent)
{
var selectedText;
if (document.selection != undefined)
{
textComponent.focus();
var sel = document.selection.createRange();
selectedText = sel.text;
}
else if (textComponent.selectionStart != undefined)
{
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos)
}
return selectedText;
}
var textArea = document.getElementById('mytextarea');
textArea.onselect = function(){ alert(getSelectionInsideTextarea(textArea)); };
Working example:
https://jsfiddle.net/jve4eehh/6/

Related

Validate letters in real time and manipulate them

I've a div with contenteditable and I'm trying to manipulate the array of this div to check if each letter written inside it, is the same as the letter on another text, based on the index.
The validation is done, I can check it, my problem is that, I need to change the letter color to red, if the letter don't validate. And I'm having trouble inserting a span with the class that I want.
Anyone have a sugestion?
Code follows:
timer.addEventListener('secondsUpdated', function (e) {
$('#countdown .values').html(timer.getTimeValues().toString(['minutes', 'seconds']));
if ($('.true-textarea').contents().get(0)) {
var textResult = $(".true-textarea").contents().get(0).nodeValue;
var textSize = textResult().length - 1;
}
$(".true-textarea").on("keypress", function(e) {
var c = String.fromCharCode(e.which);
e.preventDefault();
$(".true-textarea").html("");
if (c != textFake[textSize]) {
$(".true-textarea").addClass("red-border");
cls = "color-red";
} else {
cls = "color-purple";
$(".true-textarea").removeClass("red-border");
}
console.log('result', textResult);
console.log('size', textSize)
res += "<span class='"+cls+"'>"+c+"</span>";
cls = "";
$(".true-textarea").html(res);
});
});
So after hours trying to figure this out I came up if this code.
Used some examples that I saw in around the internet, fixed some problems, and it's working with the following code:
function focusAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
$('.true-textarea').unbind();
$('.true-textarea').focus();
timer.start({countdown: true, startValues: {seconds: 60}});
$('#countdown .values').html(timer.getTimeValues().toString(['minutes', 'seconds']));
var res = "", cls = "";
textResult.on("keypress", function(e){
textResult.find('br').remove();
var c = String.fromCharCode(e.which);
e.preventDefault();
res = textResult.html();
textSize = textResult.text().length;
if (c === textFake[textSize]) {
cls = "color-purple";
} else {
cls = "color-red";
}
res += "<span class='"+cls+"'>"+c+"</span>";
var del = false;
var lastFocused;
cls = "";
textResult.html(res);
focusAtEnd($(this).get(0));
})

Change selected text via javascript

window.addEventListener("keydown", function(e){
/*
keyCode: 8
keyIdentifier: "U+0008"
*/
if(e.keyCode === 16 && getSelectionText() != "") {
e.preventDefault();
replaceSelectedText(strcon(getSelectionText()));
}
});
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;
}
function strcon(givenString) {
var b = '';
var a = givenString;
for (i = 0; i < a.length; i++) {
if (a.charCodeAt(i) >= 65 && a.charCodeAt(i) <= 90) {
b = b + a.charAt(i).toLowerCase();
}
else
b = b + a.charAt(i).toUpperCase();
}
return b;
}
function replaceSelectedText(replacementText) {
var sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(replacementText));
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.text = replacementText;
}
}
The code I have right now seems to change the appearance of the actual text instead of actually changing it. For example, when I'm on Facebook and I press the certain key, the text seems to have changed but then when I press enter, the text goes back to what it was before.
I believe the issue is with the function replaceSelectedText but I'm not sure how to fix it.
Any ideas?
No JQuery please.
https://jsfiddle.net/1rvz3696/
You have to get your textarea element to replace the value in it. This is how your replaceSelectedText function should look like,
function replaceSelectedText(text) {
var txtArea = document.getElementById('myTextArea');
if (txtArea.selectionStart != undefined) {
var startPos = txtArea.selectionStart;
var endPos = txtArea.selectionEnd;
selectedText = txtArea.value.substring(startPos, endPos);
txtArea.value = txtArea.value.slice(0, startPos) + text + txtArea.value.slice(endPos);
}
}
And here's the Fiddle.
Without specific id, you can replace txtArea to this.
var txtArea = document.activeElement;
And another Fiddle

How to select unselected text along with selected text in javascript?

I am working on an application which requires to select next line along with the selected line.
Following code is used for text selection
function getSelectedText() {
var text = "";
if (typeof window.getSelection != "undefined") {
text = window.getSelection().toString();
} else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
text = document.selection.createRange().text;
}
// alert('text = ' + text);
return text;
}
How to select next line of text along with selected line in javascript ?
This might help you to get some idea on how to achieve that:
HTML:
<body>
<pre>
Hahahaa. Jacko. Superman. Hulk.
</pre>
</body>
Javascript with JQuery:
function getSelectionTextWithNext() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
var preText = $("pre").text();
var theBeginningTextIndex = preText.indexOf(text) + text.length;
var preTextIndex = preText.indexOf('.', theBeginningTextIndex);
var nextSentence = preText.substring(preText.indexOf(text), preTextIndex + 1);
console.log(nextSentence);
return nextSentence;
}
$(document).ready(function (){
$('pre').mouseup(function (e){
getSelectionTextWithNext();
})
});
Live Demo:
function getSelectionTextWithNext() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
var preText = $("pre").text();
var theBeginningTextIndex = preText.indexOf(text) + text.length;
var preTextIndex = preText.indexOf('.', theBeginningTextIndex);
var nextSentence = preText.substring(preText.indexOf(text), preTextIndex + 1);
console.log(nextSentence);
return nextSentence;
}
$(document).ready(function() {
$('pre').mouseup(function(e) {
getSelectionTextWithNext();
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<pre>
Hahahaa. Jacko. Superman. Hulk.
</pre>
</body>
The sample would find "." as the mark of the end of sentences.
The sample also might be buggy, but hopefully it gives you the ideas.
Pseudo Codes:
Get the selection text.
Go through the original text contained in the html element and use custom made logic to get the next sentence. (In this example, "." is
the mark of the end of sentences).
FYI,
The code posted is an extended version of
http://jsfiddle.net/abdennour/BQSJ3/6/
Tribute for the original creator.
Hope it helps.
Thanks

insert text into selected textarea

When I click a button I want to insert some text into the currently selected textarea at the current caret position. How do I do this with jQuery or just Javascript?
I've come a across code that inserts text into a specific text area but for my project there are multiple textareas.
This does all what you want (except old browser support).
var myText = "sup?",
lastActiveElement = null;
window.addEventListener("focusin", function(e) {
lastActiveElement = e.target;
});
document.getElementById("go").addEventListener("click", function(e) {
if(!lastActiveElement || lastActiveElement.tagName.toUpperCase() !== "TEXTAREA") {
alert("no textarea selected");
return;
}
var selectionStart = lastActiveElement.selectionStart,
value = lastActiveElement.value;
lastActiveElement.value = value.substr(0, selectionStart) + myText + value.substr(selectionStart);
});
Demo: http://jsfiddle.net/rfYZq/2/
The focusin event stores the last focused element into a var.
(function ($, undefined) {
$.fn.getCursorPosition = function() {
var el = $(this).get(0);
var pos = 0;
if('selectionStart' in el) {
pos = el.selectionStart;
} else if('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
}
})(jQuery);
Basically, to use it on a text box, do the following:
$("#myTextBoxSelector").getCursorPosition();
I got this script from somewhere else but I can't find the bookmark for it.
This adds a method to jQuery that will allow you to do the following:
$("#selectedTextarea").insertAtCaret(myText);
Edit: a working fiddle here
And the code:
jQuery.fn.extend({
insertAtCaret: function(myValue)
{
return this.each(function()
{
if(document.selection)
{
//For browsers like Internet Explorer
this.focus();
sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}
else if(this.selectionStart || this.selectionStart == '0')
{
//For browsers like Firefox and Webkit based
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos, this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
}
else
{
this.value += myValue;
this.focus();
}
})
}
});

how to get selected text inside a textarea element by javascript?

I'm not familiar with such attributes,
can someone provide a simple demo?
I need it to be done without any libraries.
<script type="text/javascript">
function ShowSelectionInsideTextarea()
{
var textComponent = document.getElementById('mytextarea');
var selectedText;
// IE version
if (document.selection != undefined)
{
textComponent.focus();
var sel = document.selection.createRange();
selectedText = sel.text;
}
// Mozilla version
else if (textComponent.selectionStart != undefined)
{
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos)
}
alert("You selected: " + selectedText);
}
</script>

Categories

Resources