Is there a function to deselect all text using JavaScript? - javascript

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);

Related

Highlight html table cell onclick and copy value with CTRL + C

I found a nice script to highlight html table rows and it works fine :
http://nerds-central.blogspot.ca/2006/12/selectable-table-rows-with-html-and.html
I changed the onclick event for onmouseover and I added a few lines to select a cell onclick. So, I'm able to select it, to check which one is selected and get the value, but I want to copy the cell value on pressing CTRL + C without having to select the content (like in Microsoft Excel).
Just CTRL + C should be ok, but if you also have a clue to do the trick with the right-click dropdown menu, that would be awesome!
Here's a snippet which automatically selects a cell just before copy, though it works with CTRL+C only.
window.onload = function () {
var selected,
selectCell = function (e) {
var cell = e.target,
range, selection;
if (cell.tagName.toLowerCase() !== 'td') {
while (cell = cell.parentElement) {
if (cell.tagName.toLowerCase() === 'td') {
break;
}
}
}
if (!cell || cell.tagName.toLowerCase() !== 'td') {
return;
}
if (selected) {
selected.style.backgroundColor = '';
}
cell.style.backgroundColor = '#ff0';
selected = cell;
},
beforeCopyCell = function (e) {
var range, selection;
if (!selected || !e.ctrlKey || e.which !== 67) {
return;
}
selected.focus();
selection = window.getSelection();
selection.removeAllRanges();
range = document.createRange();
range.selectNode(selected);
selection.addRange(range);
},
afterCopyCell = function (e) {
if (!selected || !e.ctrlKey || e.which !== 67) {
return;
}
selection = window.getSelection();
selection.removeAllRanges();
},
table = document.getElementById('table');
table.addEventListener('click', selectCell);
table.addEventListener('keydown', beforeCopyCell);
document.body.addEventListener('keyup', afterCopyCell);
};
The code seems to work well in FF25, Chrome31 and IE11, but it's not working in IE<9.
A live demo at jsFiddle. (The fiddle demonstrates an alternative code, which doesn't work well with IE.)
Another demo, which somehow implements also copying the cell via contextmenu. This works in FF26, Chrome31 and IE11 only, though if omitting/rebuilding the class toggling of the selected cell, the code is supposed to be IE9+ combatible.

Javascript: How to detect if a word is highlighted

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())
})

jquery: select text event

is it possible that when user selected some text(non textarea nor input), jquery can call my callback to let me know which div's text is selected, and if the select focus is lost also call my callback?
Thanks.
Somewhat surprisingly, there's no simple way to do this. IE has a select event that is implemented on all elements but other browsers have never extended this beyond inputs. You'll have to handle keyup and mouseup events on the whole document, and even then, your callback may well be called when the selection hasn't actually changed.
UPDATE 13 OCTOBER 2013
WebKit browsers have supported the selectionchange event on Document nodes for a couple of years. IE also supports this event back to version 5.5. Example:
document.onselectionchange = function() {
console.log("Selection changed");
};
Here's a simple example:
function selectCallback(selectionParentElement) {
console.log("Selecting, parent element is " + selectionParentElement.nodeName);
}
var mouseOrKeyUpHandler;
if (typeof window.getSelection != "undefined") {
// Non-IE
mouseOrKeyUpHandler = function() {
var sel = window.getSelection();
if (sel.rangeCount > 0) {
var range = sel.getRangeAt(0);
if (range.toString()) {
var selParentEl = range.commonAncestorContainer;
if (selParentEl.nodeType == 3) {
selParentEl = selParentEl.parentNode;
}
selectCallback(selParentEl);
}
}
};
} else if (typeof document.selection != "undefined") {
// IE
mouseOrKeyUpHandler = function() {
var sel = document.selection;
if (sel.type == "Text") {
var textRange = sel.createRange();
if (textRange.text != "") {
selectCallback(textRange.parentElement());
}
}
};
}
document.onmouseup = mouseOrKeyUpHandler;
document.onkeyup = mouseOrKeyUpHandler;
you can use this
use <ELEMENT ondrag = "handler(event);" >
object.addEventListener( "drag", handler, bCapture);

IE8 iframe DesignMode loses selection

The example below is a simple example of an iframe which uses window.parent.[turn designmode on] (this works). In FF all is well, but in IE8 (surprise surprise) any selection made is lost when you click out of the iframe. This totally negates the use of tools outside the iframe. I cannot find a solution 4 days later...
Open in IE8
http://www.chromedigital.co.za/hydrapage/test.htm
On any element in the main document you want not to break the iframe selection, add unselectable="on".
For example:
<div onclick="makeBold()" unselectable="on">Bold</div>
You could try saving the selection when the iframe loses focus. If you're sure the content of the iframe will not change before the user focuses on it again, you can store the currently selected Range or TextRange. The following script (for the main page) includes your original script, is not extensively tested and would be improved with better feature detection but is something to work with:
h_FF=!document.all
h_rt_F=0
function HLC_DM()
{
h_rt_F=document.getElementById("moo").contentWindow
if(h_FF)
{
if(h_rt_F.document.designMode!="on")
{
try
{
h_rt_F.document.designMode="on"
h_rt_F.document.execCommand("redo",false,null)
createEventHandlers();
}
catch(e)
{
setTimeout("HLC_DM",200)
return false
}
}
}
else
h_rt_F.document.body.contentEditable=true
createEventHandlers();
}
function getContentWindow() {
return document.getElementById("moo").contentWindow;
}
function saveSelection() {
var win = getContentWindow();
var doc = win.document;
var sel = win.getSelection ? win.getSelection() : doc.selection;
var range;
if (sel) {
if (sel.createRange) {
range = sel.createRange();
} else if (sel.getRangeAt) {
range = sel.getRangeAt(0);
} else if (sel.anchorNode && sel.focusNode && doc.createRange) {
// Older WebKit browsers
range = doc.createRange();
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
// Handle the case when the selection was selected backwards (from the end to the start in the
// document)
if (range.collapsed !== sel.isCollapsed) {
range.setStart(sel.focusNode, sel.focusOffset);
range.setEnd(sel.anchorNode, sel.anchorOffset);
}
}
}
return range;
}
function restoreSelection(range) {
var win = getContentWindow();
var doc = win.document;
var sel = win.getSelection ? win.getSelection() : doc.selection;
if (sel && range) {
if (range.select) {
range.select();
} else if (sel.removeAllRanges && sel.addRange) {
sel.removeAllRanges();
sel.addRange(range);
}
}
}
var selectedRange;
function blurHandler() {
selectedRange = saveSelection();
}
function focusHandler() {
if (selectedRange) {
restoreSelection(selectedRange);
}
}
var iframeHandlersCreated = false;
function createEventHandlers() {
// Prevent setting up twice
if (!iframeHandlersCreated) {
var iframe = document.getElementById("moo");
var doc;
if (iframe.contentDocument && iframe.contentDocument.addEventListener) {
doc = iframe.contentDocument;
doc.addEventListener("blur", blurHandler, false);
doc.addEventListener("focus", focusHandler, false);
} else if (iframe.attachEvent) {
iframe.attachEvent("onbeforedeactivate", blurHandler);
iframe.attachEvent("onfocus", focusHandler);
}
iframeHandlersCreated = true;
}
}
My Editbox can add images, tables etc where you last clicked in the iframe and works for ie6, ie7 and FF but for ie8 it adds then at the start. They can then be cut and pasted to where you want them but that is a nuisance. MORE SERIOUS is that when I want to change the attributes of a table cell, for example, I have to have some text now in the cell which I must highlight or I can't determine what element I'm in!
Have Microsoft any bug fixes for the selection method or is Firefox or old versions of ie the only course?
regards Mike W

Deselect contents of a textbox with javascript

I understand that with javascript you can select the contents of a textbox with the following code (in jQuery):
$("#txt1").select();
Is there a way to do the opposite? To deselect the content of a textbox? I have the focus event of a series of textboxes set to select the contents within them. There are times now that I want to focus a particular textbox WITHOUT selecting it. What I am planning on doing is calling the focus event for this particular textbox, but then follow it with a call to deselect it.
$("input[type=text]").focus(function() {
$(this).select();
});
//code....
$("#txt1").focus();
//some code here to deselect the contents of this textbox
Any ideas?
Thanks!
what about this:
$("input").focus(function(){
this.selectionStart = this.selectionEnd = -1;
});
If you just assign the value of the textbox to itself, it should deselect the text.
You need to set the selectionStart and selectionEnd attribute. But for some reason, setting these on focus event doesn't work (I have no idea why). To make it work, set the attributes after a small interval.
$(document).ready(function(){
$('#txt1').focus(function(){
setTimeout(function(){
// set selection start, end to 0
$('#txt1').attr('selectionStart',0);
$('#txt1').attr('selectionEnd',0);
},50); // call the function after 50ms
});
});
To "focus a particular textbox WITHOUT selecting it":
I would use the part of the patched jquery plugin jquery-fieldselection
using that you can call
$('#my_text_input').setSelection({"start":0, "end":0}); // leaves the cursor at the left
or use this reduced version that places the cursor at the end of the text (by default)
(function() {
var fieldSelection = {
setSelection: function() {
var e = (this.jquery) ? this[0] : this, len = this.val().length || ;
var args = arguments[0] || {"start":len, "end":len};
/* mozilla / dom 3.0 */
if ('selectionStart' in e) {
if (args.start != undefined) {
e.selectionStart = args.start;
}
if (args.end != undefined) {
e.selectionEnd = args.end;
}
e.focus();
}
/* exploder */
else if (document.selection) {
e.focus();
var range = document.selection.createRange();
if (args.start != undefined) {
range.moveStart('character', args.start);
range.collapse();
}
if (args.end != undefined) {
range.moveEnd('character', args.end);
}
range.select();
}
return this;
}
};
jQuery.each(fieldSelection, function(i) { jQuery.fn[i] = this; });
})();
used this way:
$('#my_text_input').setSelection(); // leaves the cursor at the right
Rather than selecting and then deselecting, why not just temporarily store a boolean on the dom element?
$("input[type=text]").focus(function() {
if($(this).skipFocus) return;
$(this).select();
});
//code....
$("#txt1").skipFocus = true;
$("#txt1").focus();
I'd like to suggest a simple solution
$("input[type=text]").focus(function() {
$(this).select();
});
$("input[type=text]").blur(function() {
$('input[type="hidden"][value=""]').select();
});
//code....
$("#txt1").focus();
Here is a simple solution without jquery
<input type="text" onblur="this.selectionStart = this.selectionEnd = -1;">
If you want to deselect a text box using jQuery do the following:
$(your_input_selector).attr('disabled', 'disabled');
$(your_input_selector).removeAttr('disabled');

Categories