I'm writing a Firefox addon that is triggered whenever a word is highlighted. However I need a script that detects when a word is highlighted, and I'm stuck. An example would be nytimes.com (when you're reading an article and you highlight a word, the reference icon pops up). However the nytimes.com script is super complex. I'm 16 and not much of a programmer, so that is definitely way out of my league.
The easiest way to do this is to detect mouseup and keyup events on the document and check whether any text is selected. The following will work in all major browsers.
Example: http://www.jsfiddle.net/timdown/SW54T/
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;
}
return text;
}
function doSomethingWithSelectedText() {
var selectedText = getSelectedText();
if (selectedText) {
alert("Got selected text " + selectedText);
}
}
document.onmouseup = doSomethingWithSelectedText;
document.onkeyup = doSomethingWithSelectedText;
Here is a script:
<script>
function getSelText()
{
var txt = '';
if (window.getSelection)
{
txt = window.getSelection();
}
else if (document.getSelection)
{
txt = document.getSelection();
}
else if (document.selection)
{
txt = document.selection.createRange().text;
}
else return;
document.aform.selectedtext.value = txt;
}
</script>
<input type="button" value="Get selection" onmousedown="getSelText()">
<form name="aform">
<textarea name="selectedtext" rows="5" cols="20"></textarea>
</form>
Courtesy of Code Toad:
http://www.codetoad.com/javascript_get_selected_text.asp
In your case, you would want to call this script when the selection is made, and then you can process it however you wish, with an AJAX request to get relevant information for example, like NYtimes probably does.
In my case I wanted to be able to either highlight a text in a row of the and click in the row and send me to other route like "/entity/:id";
I created one function that detects the mouse is highlighting some text:
export const isHighlighting = () => {
// detects mouse is highlighting a text
return window.getSelection && window.getSelection().type === 'Range';
};
then I added this to the row of the
const handleClick = (id) => {
if (!isHighlighting() {
history.push(`/entity/${id}`)
}
}
{data.map((item) => (
<tr>
<td onClick={() => handleClick(item.id)}>{item.name}</>
</tr>
))}
in this way the user can hightlight then name field or click somewhere else and goes to "/entity/:id"
Using rangy.js and jQuery:
$('#elem').on('keyup mouseup', function(){
var sel = rangy.getSelection()
if (sel.rangeCount === 0 || sel.isCollapsed) return
alert(sel.toString())
})
Related
I want to create a in-window popup when some text is highlighted, similar to how the Google Dictionary extension works. I've already figured out how to do the highlighting portion, just can't figure out how to create the popup.
Here's the code for the highlighting:
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
console.log(text);
}
document.onmouseup = function() {getSelectionText()};
I have a component in Reactjs. This has a p tag. Inside that there is text.
I want that when ever user double click on any word, it should trigger a function, in which I get the selected text, so that I can save that word in an array.
Please help.
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;
}
This should work for all browsers. Attach it to mouseup of your p tag.
I have a text area in which we have some text and a "touchend" event bind on this textarea. But while selecting text on Ipad it works only for it for first time touched select but if I am extending the selection part It will not return the selection string.
I want to return a string as I do selection of string. Below is the Link which I have prepared.
https://jsfiddle.net/22gc6gu4/63/
Any suggestion or help.
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 (){
$('textarea').on(" touchend", function (e){
$("#textUpdate").text(getSelectionText());
})
});
In my web app, I am trying to implement different behaviors for click and mouseup events for text elements. On a mouseup event, I check if there is a selected text and do something with it. On a click event I do something else, like navigating somewhere regarding clicked text. If there is a selected text, however, I won't execute the code on click event and this is the part I got stuck. Here is a modal of what I am doing now:
//the function that returns selected text as string
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 onMouseUp(event) {
var selection = getSelectionText();
if (selection != "") {
alert("Selected text: " + selection);
}
}
function onClick(event) {
alert("You clicked the text.");
}
<body>
<h2 onclick="onClick(); return false;" onmouseup="onMouseUp(); return false;">
text to click or select
</h2>
</body>
I want to do something like this in the onClick handler
function onClick(event)
{
if ( !hasSelectedParts(this) ) // want to implement hasSelectedParts() function
{
alert("You clicked the text.");
}
}
How can I implement that hasSelectedParts(domElement) function? That is,
is there a simple way of detecting whether a dom element has some selected parts in it.
Thanks for any help in comments. Here is what I came up with:
function hasSelectedContend(element)
{
var selection = window.getSelection();
return !selection.isCollapsed // selection data is about currently highlighted text
&& selection.anchorNode !== null // there is a selection
&& selection.anchorNode.parentNode === element; //selection is in the element
}
Is there a function in javascript to just deselect all selected text? I figure it's got to be a simple global function like document.body.deselectAll(); or something.
Try this:
function clearSelection()
{
if (window.getSelection) {window.getSelection().removeAllRanges();}
else if (document.selection) {document.selection.empty();}
}
This will clear a selection in regular HTML content in any major browser. It won't clear a selection in a text input or <textarea> in Firefox.
Here's a version that will clear any selection, including within text inputs and textareas:
Demo: http://jsfiddle.net/SLQpM/23/
function clearSelection() {
var sel;
if ( (sel = document.selection) && sel.empty ) {
sel.empty();
} else {
if (window.getSelection) {
window.getSelection().removeAllRanges();
}
var activeEl = document.activeElement;
if (activeEl) {
var tagName = activeEl.nodeName.toLowerCase();
if ( tagName == "textarea" ||
(tagName == "input" && activeEl.type == "text") ) {
// Collapse the selection to the end
activeEl.selectionStart = activeEl.selectionEnd;
}
}
}
}
For Internet Explorer, you can use the empty method of the document.selection object:
document.selection.empty();
For a cross-browser solution, see this answer:
Clear a selection in Firefox
This worked incredibly easier for me ...
document.getSelection().collapseToEnd()
or
document.getSelection().removeAllRanges()
Credits: https://riptutorial.com/javascript/example/9410/deselect-everything-that-is-selected
For a textarea element with at least 10 characters the following will make a small selection and then after a second and a half deselect it:
var t = document.getElementById('textarea_element');
t.focus();
t.selectionStart = 4;
t.selectionEnd = 8;
setTimeout(function()
{
t.selectionStart = 4;
t.selectionEnd = 4;
},1500);