Saving highlighted text to a string - javascript

I'm making a web application that splits the screen into two windows, with one side a web based text editor and the other side just a normal window.
I am trying to find a way to be able to have a user highlight some text on the browser side and then auto-save the highlighted text into a string where I would then be able to manipulate the string.
Does anybody have any ideas? Any help would be greatly appreciated.

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;
}
$(document).ready(function (){
$('div').mouseup(function (e){
alert(getSelectionText())
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Hello, this is a highlight text test
</div>

So you'll have two steps here.
Capture the mouseup event.
Return the selected text.
Whatever text is selected on the document can be accessed via the js call:
window.getSelection()
But this is browser specific. So you can use this code snippet to cover grabbing the selected text from all browsers.
function getSelectedText () {
var txt = ''
if (window.getSelection) {
txt = window.getSelection();
} else if (document.getSelection) {
txt = document.getSelection();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
return txt;
}
I assume you are using a library like jQuery. So that can help with the mouseup events. You probably don't want to capture selections on the whole document. So you could bind to whatever element you need. Something like my jsfiddle here: http://jsfiddle.net/xh799/

Related

HTML - 2 elements focused at the same time

I'm slightly rewriting TinyMCE editor so that it better suited my needs.
One of the changes I want to do is font size input - no select but straight input where you would write any value you want.
I began to experiment with TextBox, but there is a problem.
When I go into that text box, selection from editor is lost, so any change is applied to nothing.
Is there some possibility how to access the text box and not lose the focus in the editor, or some other workaround?
Dialog is not the possibility, as it would completely beat the purpose of simplicity.
Thanks for any advice in advance.
No, it's not possible to do as such, but you could maybe re-ceate this functionality with some javascript+css. That may be a bit tricky though, so I would suggest leaving it for later on and go further on actual functionalities of whatever you're developing.
You can try and save the selection, and then restore it once the the user completes the input.
function saveSelection() {
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
return sel.getRangeAt(0);
}
} else if (document.selection && document.selection.createRange) {
return document.selection.createRange();
}
return null;
}
function restoreSelection(range) {
if (range) {
if (window.getSelection) {
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (document.selection && range.select) {
range.select();
}
}
}
Make sure you always save the selection by recalling saveSelection when the selection changes:
document.getElementById("editor").onmouseup = function () {
tinyRange = saveSelection();
}
document.getElementById("btn").onclick = function(){
restoreSelection(tinyRange);
document.getElementById("editor").focus();
}
check out this jFiddle: http://jsfiddle.net/SpacePineapple/5QLDT/

Javascript - Check highlighted text within Contenteditable has link tags

Im currently building a very simple inline-editor, for content editable areas within a website. I have managed to do the basics (Bold, Italic etc) and now I have hit a pitfall.
I'm allowing the user to create links, by highlighting text and creating the link via text input. My problem is if the highlighted/selected text is already wrapped in tags I wish the text input to display the current link. Thus giving the user the ability to terminate the link or update/edit it.
My code for creating a link by highlighting selected text HTML:
<div contenteditable='TRUE' class="editable">This Contenteditable text</div>
<!-- Add Url to Highlighted Text -->
<div class="text-button" unselectable="on" onmousedown="event.preventDefault();" onclick="displayUrlInserter();">Add Url</div>
<!-- Show URL Input and Submit -->
<div class="text-button-panel" id="text-button-panel">
<input type="text" id="url" placeholder="Paste or Type your link">
<div class="text-panel-done" onmousedown="event.preventDefault();" onclick="doneUrl()">Done</div>
<div class="text-panel-cancel" onmousedown="event.preventDefault();" onclick="cancelUrl()">Cancel</div>
</div>
Javascript :
function saveSelection() {
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
return sel.getRangeAt(0);
}
} else if (document.selection && document.selection.createRange) {
return document.selection.createRange();
}
return null;
}
function restoreSelection(range) {
if (range) {
if (window.getSelection) {
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (document.selection && range.select) {
range.select();
}
}
}
var selRange;
function displayUrlInserter() {
selRange = saveSelection();
// Display
document.getElementById("text-button-panel").style.display = "block";
// Focus
document.getElementById("url").focus();
}
function doneUrl() {
var url = document.getElementById("url").value;
// No Url
if (url === "") {
return false;
}
// Check for HTTP
if (!url.match("^(http|https)://")) {
url = "http://" + url;
}
restoreSelection(selRange);
**// THIS IS WHERE I NEED TO CHECK FOR EXISTING A TAGS**
document.execCommand("CreateLink", false, url);
// Hide Panel
document.getElementById("text-button-panel").style.display = "none";
// Reset Input
document.getElementById("url").value = "";
}
function cancelUrl() {
document.getElementById("text-button-panel").style.display = "none";
}
The saveSelection and restoreSelection saves the currently selected text and allows me to create the link within doneUrl() via the execCommand.
This all works fine, all i need is to be able check and get the if it is present. Any guidance would be appreciated.
Try : Grande.js
https://github.com/mduvall/grande.js
Look like this when you selected texts
Live : http://mattduvall.com/grande.js/
Here is a function to check if the current selection is a link.
function itemIsLinked(){
if(window.getSelection().toString() != ""){
var selection = window.getSelection().getRangeAt(0);
if(selection){
if (selection.startContainer.parentNode.tagName === 'A' || selection.endContainer.parentNode.tagName === 'A') {
return [true, selection];
} else { return false; }
} else { return false; }
}
}
Then you can run something like
var isLink = itemIsLinked();
If it is linked it will return :
isLink[0] -> true
isLink[1] -> the link object.
To then get the HREF from that selection use:
isLink[1].startContainer.parentNode.href
That's worked really well for me. Good luck.

Javascript-Android get selected text script

I tried to get selected text from an html page on each touchend event in android device but am not able to get selected text.
Javascript code is :
if(window.getSelection)
{
t = window.getSelection();
}
else if(document.getSelection)
{
t = document.getSelection();
}
else if(document.selection)
{
t = document.selection.createRange().text;
}
Thanks in Advance.
Are you doing this in a webview ?
window.getSelection() returns the Selection object. You can get the text by calling toString()
if( window.getSelection){
t = window.getSelection().toString();
}
If you want to call a function right after a text selection, you can use the "selectionchange" event:
document.addEventListener("selectionchange", handleSelection);
It's working for android chrome and iOS safari (but not for android mozilla and opera).

Is it possible to retrieve text a user has highlighted using JavaScript, if the text is not inside a form?

I would like to retrieve any text a user may have highlighted with the mouse. I would like to be able to do so from within any arbitrary element. Is this possible?
Absolutely!
Check this out.
http://www.java2s.com/Code/JavaScript/HTML/CapturingaTextSelection.htm
Here's a function that works in all major browsers:
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type == "Text") {
text = document.selection.createRange().text;
}
return text;
}

Javascript functions return lines of function code or "{[native code]}," what am I doing wrong?

I am writing some code to find the user selection in a contenteditable div, I'm taking my code from this quirksmode article.
function findSelection(){
var userSelection;
if (window.getSelection) {userSelection = window.getSelection;}
else if (document.selection){userSelection = document.selection.createRange();} // For microsoft
if (userSelection.text){return userSelection.text} //for Microsoft
else {return userSelection}
}
I'm testing it in Chrome and Firefox, if I do an alert(userSelection) within the function or an alert(findSelection();) outside the function, it returns function getSelection() {[native code]}. If I do console.log(findSelection();) it gives me getSelection(). Is there something I've done wrong?
getSelection is a function... you need to execute it to get the selection?
if (window.getSelection) {userSelection = window.getSelection();}
Change it to
  if (window.getSelection) {userSelection = window.getSelection();}
(getSelection())
This is to get the text of the selection. Even with the typo fixed, you've got inconsistent behaviour: IE is returning the selection's text as a string while other browsers will return a Selection object that will give you the selection text string only when its toString() method is called.
The following would be better:
function getSelectionText(){
if (window.getSelection) {
return "" + window.getSelection();
} else if (document.selection && document.selection.createRange) {
return document.selection.createRange().text;
}
}

Categories

Resources