I am working on a website where I would like to be able to display a box containing syntax-highlighted source code for the user to copy. When I click on the box, giving it focus (Chrome shows its focus outline), and type Ctrl+A, the text of the entire page is selected, whereas I would like only the syntax-highlighted source code within the box to be selected.
Is it possible to restrict the range of select all/Ctrl+A to only the text within the box, preferably without using an <iframe>?
My first thought was to try contenteditable. When I click in the box and the editor caret appears, typing Ctrl+A selects only the text within the box, as desired, but it also allows the user to change the code, and I think that the editor-interface aspect of making the box contenteditable will be confusing to users. If I wrap the source code text within a <div> having contenteditable="false" within the <div> having contenteditable="true", then the source code text is read-only, but typing Ctrl+A selects the text of the entire page again.
Here is a test page: http://jsfiddle.net/5crgL/
You can use the document.createRange(); method to select the text from a particular element.
and to handle the ctrl+a you can use the jQuery keydown method and can call the JS code to select the DIV text.
var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().addRange(range);
please see jsfiddle here jsfiddle.
Related
So i have a text element on the canvas with fabricjs, when clicked on the text box some jquery fires and part of that code is supposed to push the cursor focus to a textarea while maintaining the active canvas object (the object stays selected just fine when i click into the textarea).
The problem is that the focus isn't being put to the textarea.
So if we have textarea with id "editing-box" and run something like this:
fabric.on('object:selected',function(e){
// set textbox to edit mode here
// focus on textbox
if(the object is textbox){
$('#editing-box').focus();
}
});
The fabric textbox goes into editing fine but the texarea doesn't take the focus for the typing.
I want to make the "COPY ADDRESS" button copy a text I specify. I already tried to do it myself, but couldn't do it. It is very simple, I just have minimal knowledge.
http://porcelaincoins.com
<a class="btn btn-lg" href="#">copy address</a>
This code will copy the text abc to the clipboard.
function copy(text) {
document.body.insertAdjacentHTML("beforeend","<div id=\"copy\" contenteditable>"+text+"</div>")
document.getElementById("copy").focus();
document.execCommand("selectAll");
document.execCommand("copy");
document.getElementById("copy").remove();
}
<button onclick="copy('abc')">Copy</button>
How does it work?
Firstly, it makes a contenteditable div with the id of copy (don't use this ID anywhere else on your page). contenteditable elements are elements which are designed to be edited by the user, and there is extensive native JavaScript around them in the form of document.execCommand provided to help people make rich text editors. Part of document.execCommand is a copy method, to add text to the clipboard - however this only works reliably with selected text in a contenteditable element.
The next step is for the code to focus on the div. This is as if the user had clicked on it - inputs are known as focused when they are active - for example the focused element in a form will receive the keyboard events
The code then uses document.execCommand to select all of the text inside of the contenteditable div. In the first step, we ensured that this text was the text passed to the function.
Then, it copies that content to the clipboard using document.execCommand("copy"). This is actually surprisingly simple.
Finally, it removes the div from the DOM (i.e. destroys the div)
These actions should all happen so fast that the user will not realise that a div has even been created, however the text will appear on their clipboard.
I have been doing research on this simple sounding issue for a couple of days and I have not seen any result.
In a nutshell my problem is as follows: I would like to select text in a some input field, move focus to another field (or generally speaking some other element), but not lose my selected text.
Such a situation could correspond to a use-case in which I select text in a field, right-click and display a custom popup menu, but do not wish to lose focus of selected text, because I want to do some operations on the previously selected text.
A small code test sample would be (for my initial simple scenario - here I am forcing text selection when the second input field gains focus):
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<input type="text" id="text1" size="20" value="Test1"/>
<input type="text" id="text2" size="20" value="Test2"/>
<script>
$('#text2').focus( function (evt) {
var target = $('#text1')[0];
target.select();
console.log('active/focused element: ' + document.activeElement.id);
});
</script>
</body>
</html>
I have been searching SO and web for a solution to this and have not seen much if any help.
I am not sure this is even really possible (due to the link between blur and selection lost and focus and selection). I have seen a style property called preventDeselect, in another SO answer - this does not work and I have not even such documentation or browser support for this.
I am quite struggling with this and would appreciate some help: even saying I can't do this at all or maybe some ways to go.
UPDATE:
Just for the record, my user scenario, which refers to text selection and context menu, is a common one (it slipped my mind to mention): just select some text in this page (or in an input type field) and right click to get the browser's default context menu - my scenario is different in that i want to use a custom menu, but with similar behavior to the browser's context menu - which normally allows to select some text, cut/copy the selection, navigate within the context menu without losing the selected text. So I think it should be possible somehow :) to do all these things with a context menu and still have your selection.
Attempting to answer this part of your question:
Such a situation could correspond to a use-case in which I select text
in a field, right-click and display a custom popup menu, but do not
wish to lose focus of selected text, because I want to do some
operations on the previously selected text.
For this use-case, I created a quick fiddle: http://jsfiddle.net/4XE9a/1/
Note: Am using the same getSelection function from #David's answer.
If you select any text and then right-click on the input, a custom popup menu appears. Click "option 1". You will find that the selection is not lost even though the focus has shifted to that anchor tag.
However, for the second part of your question regarding focus shifting to another textbox, #David's answer suffices.
Update: (after your comments)
Please see this updated fiddle: http://jsfiddle.net/783mA/1/
Now, when you select some text and right-click on the input it will show the custom popup menu with three options. Use tab to navigate and press space or click on the highlighted option. (Due to paucity of time I could not implement up/down arrow keys, but the concept remains the same)
This demonstrates your question in the comment that the selection is still not lost while navigating the menu.
Note: You are wanting to visually keep the selection highlight and not lose the selection while clicking anywhere else. Please note that this is not possible because text selection behavior is OS implemented. Browser, html etc do not play a role here. The text selection is lost as soon as you click anywhere outside the context of selection. This is because the system starts expecting a new selection as soon as you click anywhere outside. However, controls without text surface are exempt. Button, scrollbar arrows etc will not cause selection to lose.
To view this behaviour, in the fiddle, select some text and then click any dropdown on the left pane. The text selection is not lost, even visually for that matter.
This is why in the new fiddle above, I purposely used buttons to demonstrate.
You can save each selection in an interval, then retrieve it when you like. Here is an example that pulls the selection when the input has focus and clears the interval on blur:
function getSelection(elm) {
var start = elm.selectionStart;
var end = elm.selectionEnd;
return elm.value.substring(start, end);
}
$('input').focus(function() {
var self = this;
$(this).data('interval', setInterval(function() {
$(self).data('selection', getSelection(self));
},20));
}).blur(function() {
clearInterval($(this).data('interval'));
});
Now you can stuff like:
$('#text2').focus(function() {
console.log('selection in #text1 was: '+$('#text1').data('selection'));
});
Demo: http://jsfiddle.net/qCCY5/
I have a form panel with several text and text area fields and would like to copy (or move) the text from one field to another by dragging. (The fields itself should stay in place).
ExtJs provides the example, which does almost what I need: field-to-grid-dd.
The problem is that it is now not possible to enter the text into the draggable text field. I assume that's because the 'mousedown' event is intercepted by the Ext.dd.DragZone object, whose method getDragData() initiates the dragging if the mouse is clicked inside the draggable element.
It there a way to put the cursor inside the text field if the user just clicks it without dragging?
I tell you how to change the ExtJS Example file (field-to-grid-dd.js), then you can change your own app codes.
Go to line 148 and comment or remove the code below:
// i.unselectable();
Then go to line 164 and add the code below before (or after, it doesn't matter) e.stopEvent();:
t.focus(); // Add This
e.stopEvent();
Of course, you can not select the value of textfield with dragging the mouse, but it does what you want.
I want the user selection from a text area in my page. I have a context menu that user can use on right-clicking the selection. This is my code to retrieve selected content from a textarea in IE8,
var textComponent = document.getElementById('myTextArea');
var selectedText;
// IE version
if (document.selection != undefined)
{
textComponent.focus();
selectedText= document.selection.createRange();
alert(sel.text);
}
Now I notice that before allowing the blocked content (i.e. the Javascript) I can select a text in the text area and on right click it does not get deselected.
But, when I allow the script, on right clicking the text that I selected gets deselected. Which is why I cannot retrieve the content.
I searched the web but didn't get any solution. Can anyone please tell me what the problem is?
Calling the focus() method of the texbox or using the focus() method of any element on the page will clear the text selection.
Take a look here for a great answer:
Keep text selection when focus changes