I am new to use html+javascript+jQuery. I am trying to use window.getSelection to get selected text but this is not working.
Can any one suggest solution for this.
Thanks in advance.
Just need simple line of code in java script which done your job
//I am using below line of code which works in both android and web browsers.
function getSelectedText() {
var selection = null;
if (window.getSelection) {
selection = window.getSelection();
} else if (typeof document.selection != "undefined") {
selection = document.selection;
}
var selectedRange = selection.getRangeAt(0);
console.log(selectedRange.toString());
}
NOTE : Don't call this method in post or inside any runnable interface as post or any runnable interface make delay in calling this method(Method call happens after browser selection release). Just call this method like
webView.loadUrl("javascript:getSelectedText()");
I know this is a very old question, but I get this as a first search result when I had tried to resolve the same or similar issue. I didn't find a solution here but after some time I realized that sometimes for phones there should be a short timeout between click and selection to make getSelection() work properly.
So e.g. instead this:
document.getElementById("element").addEventListener('click', function (event) {
window.getSelection().selectAllChildren(this)
});
You should use somethink like this:
document.getElementById("element").addEventListener('click', function (event) {
setTimeout(function(passedThis) {
window.getSelection().selectAllChildren(passedThis)
}, 10, this);
});
Maybe it save some time to somebody.
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.
Try
function getSelected() {
var text = "";
if (window.getSelection && window.getSelection().toString() && $(window.getSelection()).attr('type') != "Caret") {
text = window.getSelection();
return text;
} else if (document.getSelection && document.getSelection().toString() && $(document.getSelection()).attr('type') != "Caret") {
text = document.getSelection();
return text;
} else {
var selection = document.selection && document.selection.createRange();
if (!(typeof selection === "undefined") && selection.text && selection.text.toString()) {
text = selection.text;
return text;
}
}
return false;
}
Related
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/
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 there a way to set the cursor at the end in a textarea element? I'm using Firefox 3.6 and I don't need it to work in IE or Chrome. It seems all the related answers in here use onfocus() event, which seems to be useless because when user clicks on anywhere within the textarea element Firefox sets cursor position to there. I have a long text to display in a textarea so that it displays the last portion (making it easier to add something at the end).
No frameworks or libraries.
There may be many ways, e.g.
element.focus();
element.setSelectionRange(element.value.length,element.value.length);
http://jsfiddle.net/doktormolle/GSwfW/
selectionStart is enough to set initial cursor point.
element.focus();
element.selectionStart = element.value.length;
It's been a long time since I used javascript without first looking at a jQuery solution...
That being said, your best approach using javascript would be to grab the value currently in the textarea when it comes into focus and set the value of the textarea to the grabbed value. This always works in jQuery as:
$('textarea').focus(function() {
var theVal = $(this).val();
$(this).val(theVal);
});
In plain javascript:
var theArea = document.getElementByName('[textareaname]');
theArea.onFocus = function(){
var theVal = theArea.value;
theArea.value = theVal;
}
I could be wrong. Bit rusty.
var t = /* get textbox element */ ;
t.onfocus = function () {
t.scrollTop = t.scrollHeight;
setTimeout(function(){
t.select();
t.selectionStart = t.selectionEnd;
}, 10);
}
The trick is using the setTimeout to change the text insertion (carat) position after the browser is done handling the focus event; otherwise the position would be set by our script and then immediately set to something else by the browser.
Here is a function for that
function moveCaretToEnd(el) {
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = el.value.length;
} else if (typeof el.createTextRange != "undefined") {
el.focus();
var range = el.createTextRange();
range.collapse(false);
range.select();
}
}
[Demo][Source]
textarea.focus()
textarea.value+=' ';//adds a space at the end, scrolls it into view
(this.jQuery || this.Zepto).fn.focusEnd = function () {
return this.each(function () {
var val = this.value;
this.focus();
this.value = '';
this.value = val;
});
};
#Dr.Molle answer is right. just for enhancement, U can combine with prevent-default.
http://jsfiddle.net/70des6y2/
Sample:
document.getElementById("textarea").addEventListener("mousedown", e => {
e.preventDefault();
moveToEnd(e.target);
});
function moveToEnd(element) {
element.focus();
element.setSelectionRange(element.value.length, element.value.length);
}
I have a page with couple of DIV elements. When user presses the CTRL+ENTER button combo, I need to display (via alert()) the text, that user previously selected. I found the solution and it works like a charm, but there is still one thing left.
I need to make event trigger, only when selected text is inside a DIV with class "main_content". I've tried to assign keyup to $('DIV.main_content'), but it does not work.
Is there a way to make event trigger only if text inside $('DIV.main_content') selected?
Here is a working code that triggers on the whole document:
// Get user selection text on page
function getSelectedText() {
if (window.getSelection) {
return window.getSelection();
}
else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
$(document).ready(function(){
$(document).keydown(function(e) {
if(e.which == 13 && e.ctrlKey) {
alert(getSelectedText());
return false;
}
});
});
See the code with markup in jsFiddle
You have an error in the getSelectedText() function: window.getSelection() returns a Selection object, not a string. The fact you're passing the result of this to alert() is masking this, because alert() implicitly converts the argument passed to it into a string.
Here's some code to check whether the selection is completely contained within a <div> element with a particular class. It works in all major browsers.
Live example: http://www.jsfiddle.net/cVgsy/1/
// Get user selection text on page
function getSelectedText() {
if (window.getSelection) {
return window.getSelection().toString();
}
else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
function isSelectionInDivClass(cssClass) {
var selContainerNode = null;
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
selContainerNode = sel.getRangeAt(0).commonAncestorContainer;
}
} else if (document.selection && document.selection.type != "Control") {
selContainerNode = document.selection.createRange().parentElement();
}
if (selContainerNode) {
var node = selContainerNode;
while (node) {
if (node.nodeType == 1 && node.nodeName == "DIV" && $(node).hasClass(cssClass)) {
return true;
}
node = node.parentNode;
}
}
return false;
}
$(document).ready(function(){
$(document).keydown(function(e) {
if(e.which == 13 && e.ctrlKey && isSelectionInDivClass("main_content")) {
alert(getSelectedText());
return false;
}
});
});
It is interesting question. I have the following idea: you need to catch mouseup event on div.
For example:
So, in your case you can do something like this:
var selectedText = "";
$(".yourdiv").mouseup(function(){
if (window.getSelection)
selectedText = window.getSelection();
else if (document.selection)
selectedText = document.selection.createRange().text;
alert(selectedText)
});
And variable selectedText will be store selected text.
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;
}
}