How to select unselected text along with selected text in javascript? - 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

Related

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

Get start and end of a selection using javascript

i have an html string like this:
<div id="div">Hi how are<span>you?</span> Fine</div>
The text will appear "Hi how are you? Fine".
I would like to select a part of the string using mouse and get the beginning and the end
of the selection looking from the full text string.
For example, if i select "you", i would like to obtain start=11 and end=14;
if i select "are you?", i would like to obtain start=7 and end=15.
I wrote this to obtain the selection:
function getSel() {
console.log(navigator.appCodeName);
if (window.getSelection) {
return window.getSelection();
} else if (document.getSelection) {
return document.getSelection();
} else if (document.selection) {
return document.selection.createRange().text;
}
}
And this code to obtain start and end, but it doesn't work:
$("#div").on('mouseup', function(e){
var text=getSel();
if(text.anchorNode === text.focusNode){
var n = {
node: text.anchorNode.parentNode.id,
start: text.anchorOffset,
end: text.focusOffset
}
//selection from right to left
if(n.start>=n.end) {
var tmp;
tmp=n.start;
n.start=n.end;
n.end=tmp;
}
}
else console.log("error in selection");
});
Your selector is wrong. $('#div') actually selects for any elements that have id='div'.
I have made an example of how it's done. If I am not mistaken of what you're trying to achieve.
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(){
$("#div").on('mouseup', function(e){
var thisText = $(this).text();
var selectedText = getSelectionText();
var start = thisText.indexOf(selectedText);
var end = start + selectedText.length;
if (start >= 0 && end >= 0){
console.log("start: " + start);
console.log("end: " + end);
}
});
});
Fiddle

highlight data into popup in 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/

Can getSelection() be applied to just a certain element (not the whole document)?

I was testing out the getSelection() method, and I wanted my program to get the selected text in a certain paragraph of text and display it in a div tag. I used the following code:
var txt = document.getSelection();
document.getElementById("display").innerHTML = "The text you have selected is: " + txt + ".";
However, I want the program to only get selections made in the paragraph itself, not in the entire document. I tried using document.getElementById("id").getSelection(); but it didn't work.
How can I make it so getSelection() only applies to a certain element?
Here's one approach, tested only in Chromium 19 (Which supports textContent, for Internet Explorer innerText would have to be used instead):
function getSelectedText() {
if (window.getSelection) {
return window.getSelection().toString();
} else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
var b = document.getElementsByTagName('body')[0],
o = document.getElementById('output');
b.onmouseup = function(e){
var selText = getSelectedText(),
targetElem = e.target.tagName.toLowerCase();
if (selText && targetElem == 'p') {
o.textContent = 'You selected the text: "' + selText + '" from a ' + targetElem + ' element.';
}
};​
JS Fiddle demo.
getSelection() is only available as a method of window and document. If you want to get a Range representing just the portion of the user selection that lies within a particular node, here's a function to do that, using my Rangy library (the code to do without the library would be longer and is beyond my enthusiasm to write right now):
function getSelectedRangeWithin(el) {
var selectedRange = null;
var sel = rangy.getSelection();
var elRange = rangy.createRange();
elRange.selectNodeContents(el);
if (sel.rangeCount) {
selectedRange = sel.getRangeAt(0).intersection(elRange);
}
elRange.detach();
return selectedRange;
}
function getSelected() {
if(window.getSelection) { return window.getSelection(); }
else if(document.getSelection) { return document.getSelection(); }
else {
var selection = document.selection && document.selection.createRange();
if(selection.text) { return selection.text; }
return false;
}
return false;
}
written in coffeescript:
getSelected = ->
if window.getSelection
return window.getSelection()
else if document.getSelection
return document.getSelection()
else
selection = document.selection and document.selection.createRange()
return selection.text if selection.text
return false
false
delicious javascript

Can I change the HTML of the selected text?

Can we change the HTML or its attributes of the selected part of the web page using javascript?
For example,
There is a random web page:(A part of it is shown)
with HTML as
...<p>Sample paragraph</p>..
It is possible to get the HTML of the selected text which has already been answered here.
But, is it possible for me change the html of the selected text? Like, add a class or id attribute to the paragraph tag.
The jQuery wrapselection plugin sounds like what you're looking for http://archive.plugins.jquery.com/project/wrapSelection . What you're asking for is not directly possible though, the plugin works by adding in extra nodes around the surrounding text which may not be 100% reliable (particularly in IE6-8)
Here is a working example without a plugin.
http://jsfiddle.net/9HTPw/2/
function getSel() {
var sel = null;
if (
typeof document.selection != "undefined" && document.selection
&& document.selection.type == "Text") {
sel = document.selection;
} else if (
window.getSelection && window.getSelection().rangeCount > 0) {
sel = window.getSelection();
}
return sel;
}
var getSelectionStart = (function () {
function createRangeFromSel(sel) {
var rng = null;
if (sel.createRange) {
rng = sel.createRange();
} else if (sel.getRangeAt) {
rng = sel.getRangeAt(0);
if (rng.toString() == "") rng = null;
}
return rng;
}
return function (el) {
var sel = getSel(),
rng, r2, i = -1;
if (sel) {
rng = createRangeFromSel(sel);
if (rng) {
if (rng.parentElement) {
if (rng.parentElement() == el) {
r2 = document.body.createTextRange();
r2.moveToElementText(el);
r2.collapse(true);
r2.setEndPoint("EndToStart", rng);
i = r2.text.length;
}
} else {
if ( rng.startContainer && rng.endContainer
&& rng.startContainer == rng.endContainer
&& rng.startContainer == rng.commonAncestorContainer
&& rng.commonAncestorContainer.parentNode == el) {
//make sure your DIV does not have any inner element,
//otherwise more code is required in order to filter
//text nodes and count chars
i = rng.startOffset;
}
}
}
}
return i;
};
})();
$("#content").on('mousedown', function () {
$("#content").html(content)
});
var content = $("#content").html();
$("#content").on('mouseup', function () {
var start = getSelectionStart(this);
var len = getSel().toString().length;
$(this).html(
content.substr(0, start) +
'<span style=\"background-color: yellow;\">' +
content.substr(start, len) +
'</span>' +
content.substr(Number(start) + Number(len), content.toString().length));
});
References:
http://bytes.com/topic/javascript/answers/153164-return-selectionstart-div

Categories

Resources