Making a button copy a text - javascript

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.

Related

How can I use clipboard.js with a span tag onselect event?

I was able to create a simple web-page that uses clipboard.js with a button that pastes predefined text using the
data-clipboard-text="Just because you can doesn't mean you should — clipboard.js" property as the documentation at the clipboard.js site shows, but now I want to place some text in a <span> tag and copy it when this text is selected.
However, I don't know how to 'tie' the data-clipboard-action="copy" data-clipboard-target="span" properties to a <span> tag and cause it to copy the <span>'s content with the onselect event.
Are there procedural statements that I can use in javaScript to perform the copying and pasting functions?
My goal is to embed code to copy selected text into the HTML part of an email and allow the recipient of the email to simply copy the selected text to the clipboard so that it can then be pasted from the clipboard into an input text box in a web-application's page.
This would simplify copy/paste on touch-screen devices, such as tablets and cell-phones.
You can use this code to get the selection of the screen and can use 'success' and 'error' event. Read Events and Advance section of the clipboard js
var clipboard = new ClipboardJS('button', {
text: function (trigger) {
return document.getSelection().toString()
}
});
Please see iAmADeveloper's comments for the answer.
Thanks, iAmADeveloper.

How to make a span from user selection (js)

I want to make a text editor. It should work the way all text editors work (including this one i am using right now), so the user makes a selection of the text, presses a button or whatever, and then some function is executed.
I want my editor to work in the following way:
1. User selects
2. Function selected() is triggered that makes a span around the selected text.
3. When user clicks a button such as "B" or "I", they invoke functions that change .style of the span element.
For now I figured out how to get string from user selection, nothing more than that.
<body>
<textarea onselect="selected()">Some text here, more text here.</textarea>
</body>
<script>
function selected() {
var preselection = window.getSelection();
selection = preselection.toString();
console.log(selection);
}
</script>
textareas can't contain spans, so you will need to use something like this if you decide to use spans:
<p contenteditable="true" ...
You probably don't want to fire your function every time a user makes a selection. Instead, just run the function if a user presses a button (like the bold button) and then pick up the selected text, if any, using something like:
document.getSelection().toString()
Now adding a <span> object to an HTML element is pretty easy, but the big challenge here is that you don't know if your selection will cross other span objects (like if the user already added some formatting). Notice that stackoverflow inserts characters like ** in the edit area and then does one pass to add in tags like <strong>. This is possible in a text area as well, so you wouldn't need contenteditable="true".
It is possible to analyze what is in your selection and then collect all elements involved, and rewrite them as needed. You would have to get all parent objects involved in the selection and then add <span> elements around the text inside each of the parent objects.
To simplify this, you might make a rule that only one level of tags is allowed in your editable region, and then always re-write for that so that the results would only have one level of span:
<span class="bold">This whole sentence is italic and </span><span class="italic_bold">this half is also bold.</span> with no nesting of these span tags.
Investigating these properties might help with dealing with nesting: https://developer.mozilla.org/en-US/docs/Web/API/Selection
These string commands might also help:
https://www.w3schools.com/jsref/jsref_obj_string.asp

Editable content of a DIV not working properly

I have draggable objects, and each content of an object can be editable.
Here is a sample:
http://jsfiddle.net/ashish41191/UH9UE/366/
The problem is when I type some words initially in an object, let's say the text is test for copy paste action. This is enclosed in a DIV <div> content </div>. If I select all of the typed words (ctrl + A or cmd + A) then paste it on the same text field, the pasted texts are not appended on the DIV. It rather creates a <span> copy paste words </span> inside the DIV. Can it be just appended on the DIV, like <div> content copy paste words </div>?
+1 for making me learn a HTML5 feature.
After a research, this is my inference:
HTML5 contentEditable is for Rich Text Editing. So each browser which supports contentEditable has its own way of presenting the style of the pasted content.
For your problem, I could not find a straight forward way to disable the rich text pasting.
Below the workaround,
$('body').on('paste', '.ui-widget-content', function (e) {
setTimeout(function() {
console.log($(e.target).html($(e.target).text()));
}, 100);
});
Updated Jsfiddle,
http://jsfiddle.net/UH9UE/372/

setting text in textarea using javascript

I am trying to process the text in textarea [on Facebook group page. 'write post' has one text area] and replace it with new text. This is done using Greasemonkey script
textHolder = document.getElementsByClassName( "uiTextareaAutogrow input mentionsTextarea textInput" )[0];
var vntext=textHolder.value;
var vn2text=Encrypt(vntext);
textHolder.value=vn2text;
So new text is seen in text-area but the when the 'post' button is clicked the new text is not taken instead old text is posted
But if we manually insert at least a character to the processed text then the resulting text is posted after click on post button. So I am not getting why it is directly not taking the new text without inserting the text manually.
There are other events being called in textarea element, but I do not know what they are doing exactly.
So what should be done so that new text will be posted?
DOM for text-area on Facebook page is as follows:
<textarea
class="uiTextareaAutogrow input mentionsTextarea textInput DOMControl_placeholder"
title="Write something..." name="xhpc_message_text" placeholder="Write something..."
onfocus="return wait_for_load(this, event, function() {if (!this._has_control) { new TextAreaControl(this).setAutogrow(true); this._has_control = true; } return wait_for_load(this, event, function() {JSCC.get('j4ef51acb72eb241587530255').init(JSCC.get('j4ef51acb72eb241587530256'));;JSCC.get('j4ef51acb72eb241587530256').init(["buildBestAvailableNames","hoistFriends"]);JSCC.get('j4ef51acb72eb241587530253').init({"max":10}, null, JSCC.get('j4ef51acb72eb241587530255'));;;});});"
autocomplete="off" style="direction: ltr; "
>
Write something...
</textarea>
Can you link to the page in question?
That page could be tracking that textarea's value in JS or even AJAX-posting it with every keystroke. Clicking the 'post' button might merely tell the page/server to use the last saved version of the text.
Since the GM script changes the textarea value independently of mouse and focus events, the page and/or server tracking mechanism won't be triggered.
So, if you can, find the appropriate JS function and call it after changing the text.
If that's too difficult, try setting the focus to the textarea, then elsewhere and then back to the textarea.
Or try sending a keystroke event to the text area.
Link to the page, or a full-code snapshot of it, for more detailed help.

Problems with contenteditable in Firefox

I am working on a Javascript WYSIWYG editor in Firefox. I am using a div with the contenteditable attribute set to true in order to accomplish this (I cannot use a contenteditable iframe for this particular project). This contenteditable div is nested in another div that is not contenteditable. I am encountering the following two problems when using execCommand to apply formatting, including font style and size, as well as bold, italic, and underline:
When all text in the div is selected, execCommand simply does not work. execCommand works fine when only part of the text is selected, but does nothing when all of the text is selected.
Applying formatting with no text selected yields unexpected results. For example, when calling execCommand('bold') with no text selected and then typing results in bold text being typed until a spacebar is inserted, at which point the bold formatting is lost (until another space is inserted, interestingly enough; then the text becomes bold again).
To see what I mean, please try running the following HTML code in Firefox 3:
<html>
<head><title></title></head>
<body>
<button onClick="execCommand('bold', false, null);">Bold</button>
<div style="width: 300px; border: 1px solid #000000;">
<div contenteditable="true">Some editable text</div>
</div>
</body>
</html>
Please try the following:
Select the word "Some" only. Click the Bold button. This will make the text bold, as expected.
Select the entire phrase "Some editable text" (either manually or using CTRL-A). Click the Bold button. Nothing happens. This demonstrates the first bug shown above.
Hit the backspace key to clear the div. Click the Bold button and begin typing. Type a few words with spaces. This will demonstrate the second bug.
Any ideas on what could be causing these problems and how to work around them would be greatly appreciated!
Interesting. In Firefox 3.6.3, I can't replicate the first problem: selecting all of the editable text and pressing the button toggles boldness as expected. However, the other two issues I do see. They'll be bugs in Mozilla's implementation of contenteditable.
Interestingly, the alternate-words-bold problem doesn't happen if you use designMode rather than contenteditable. I suspect it will solve your other problem too. This involves making the whole document editable, rather than just elements within it:
window.onload = function() {
document.designMode = "on";
};
If this isn't an option and you need the fine control that contenteditable provides, you'll need to implement your own version of the bold command using DOM manipulation and Ranges. This will be quite involved to get working in IE and non-IE browsers.

Categories

Resources