In my code, I am trying to copy iframe code using copy to clipboard button but I am not satisfied with it because when I copy using button it copies < and > instead of < and > secondly it won't highlights the text area so is there any alternate solution to copy as HTML code thanks
Here is my JSfiddle
Here is a sample copied text
<iframe src='http://localhost/secvideo/cms/watch?v=30Rt9r' frameborder='0' style='overflow: hidden; position: absolute;' height='100%' width='100%'></iframe>
and Here is my JS
function copyToClipboard(elementId) {
var aux = document.createElement("input");
// Assign it the value of the specified element
aux.setAttribute("value", document.getElementById(elementId).innerHTML);
document.body.appendChild(aux);
aux.select();
document.execCommand("copy");
document.body.removeChild(aux);
alert("Copied!");
}
I think you are creating an element unnecessarily here. You already have a text area with the iframe content.
All you need is to select the text area and do a document.execCommand("copy");
Modify your script to
window.copyToClipboard = function(elementId) {
// Create a "hidden" input
var aux = document.getElementById(elementId);
// Highlight its content
aux.select();
// Copy the highlighted text
document.execCommand("copy");
alert("Copied!");
}
jsfiddle
https://jsfiddle.net/yhpe990k/1/
var copyToClipboard = function (text) {
var $txt = $('<textarea />');
$txt.val(text)
.css({ width: "1px", height: "1px" })
.appendTo('body');
$txt.select();
if (document.execCommand('copy')) {
$txt.remove();
}
};
Related
This question already has answers here:
How do I copy to the clipboard in JavaScript?
(27 answers)
Closed 2 years ago.
How do I actually copy some fixed text to clipboard using javascript?
This is my code and it's not working maybe there's another way and I don't know.
<button onclick="Copy()">Copy</button>
<script>
function Copy() {
document.execCommand("copy","Some text here");
}
</script>
I want to copy some fixed text using just button, so I don't have to select texts manually and copy them.
Thanks.
You can try this approach:
<script>
function Copy() {
var copyText = document.createElement("input");
copyText.style="display:none";
copyText.value = "This is a paragraph";
document.body.appendChild(copyText);
copyText.select();
copyText.setSelectionRange(0, 99999); /*For mobile devices*/
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
</script>
try it:
var copy_text_val = document.querySelector('.copy_text');
function Copy() {
copy_text_val.select();
document.execCommand("copy");
console.log(copy_text_val.value);
}
<button onclick="Copy()">Copy</button>
<input type="text" class="copy_text" value="blablabla">
For this action you have to select the text dynamically before actually copying it:
Here is an example:
function copy_text(node){
if(document.body.createTextRange){
const range = document.body.createTextRange();
range.moveToElementText(node);
range.select();
document.execCommand('copy');
}
else if(window.getSelection){
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(node);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
}
else {
console.warn("Could not select text in node");
}
}
// This copy_text function ensures cross-browser compatibility
// What it does is select the text within the range of the node holding the text
// Then executes the "copy" command on that selected text
function clear_selection(){
if(window.getSelection){
window.getSelection().removeAllRanges();
}
else if(document.selection){
document.selection.empty();
}
}
// This clear_selection function clears any selection from the document
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("clipboard-exec").onclick = function(){
copy_text(document.getElementById("clipboard-text"));
// Copy the text on clicking the button
setTimeout(() => { clear_selection() }, 500);
// Clear the selection after 0.5s
}
});
<span id="clipboard-text">This is the text that will be copied to your clipboard when you click on the "Copy" button.</span>
<button><span id="clipboard-exec"><i class="fa fa-copy"> Copy</i></span></button>
Of course with this function you can just restructure it to fit your needs.
Also note that what you are trying to accomplish by copying directly to the keyboard without a valid text node actually holding the text won't work, I guess for security purposes
But you can create a node in the document with the text but hide it from view then select it using this function .. NOTE the text you are copying to the clipboard has to be actually in the document, for you to execute the "copy" command on it
I spent a good 20 min searching online for this, but couldn't find it. What I want is to to be able to copy a text string on click without a button. The text string will be inside a "span" class.
User hovers over text string
User clicks text string
Text string is copied to clipboard
Any help would be greatly appreciated. Thanks!
You can attach copy event to <span> element, use document.execCommand("copy") within event handler, set event.clipboardData to span .textContent with .setData() method of event.clipboardData
const span = document.querySelector("span");
span.onclick = function() {
document.execCommand("copy");
}
span.addEventListener("copy", function(event) {
event.preventDefault();
if (event.clipboardData) {
event.clipboardData.setData("text/plain", span.textContent);
console.log(event.clipboardData.getData("text"))
}
});
<span>text</span>
Try this .document.execCommand('copy')
click the element and copy the text and post with tmp input element
Then copy the text from this input
function copy(that){
var inp =document.createElement('input');
document.body.appendChild(inp)
inp.value =that.textContent
inp.select();
document.execCommand('copy',false);
inp.remove();
}
<p onclick="copy(this)">hello man</p>
This is the Code pen.
<link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<p style="color:wheat;font-size:55px;text-align:center;">How to copy a TEXT to Clipboard on a Button-Click</p>
<center>
<p id="p1">This is TEXT 1</p>
<p id="p2">This is TEXT 2</p><br/>
<button onclick="copyToClipboard('#p1')">Copy TEXT 1</button>
<button onclick="copyToClipboard('#p2')">Copy TEXT 2</button>
<br/><br/><input class="textBox" type="text" id="" placeholder="Dont belive me?..TEST it here..;)" />
</center>
Jquery Code here
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
Use the Clipboard API!
The simplest modern solution is:
navigator.clipboard.writeText(value)
That value can later be accessed with:
navigator.clipboard.readText()
NOTE: To use in an iframe, you'll need to add write (and maybe read) permissions
<iframe src='' allow='clipboard-read; clipboard-write'/>
NOTE: To use in an browser extension (on a webpage), you'll need either to:
call from a user triggered event (click...)
add the 'clipboardWrite' permission to the manifest
NOTE: To use in the dev console, use copy() instead
copy('string')
W3Schools Tutorial
CanIUse
Along with copying the text , you also have to make sure that any previously selected component remains selected after copying to clipboard.
Here's the full code :
const copyToClipboard = str => {
const el = document.createElement('textarea'); // Create a <textarea> element
el.value = str; // Set its value to the string that you want copied
el.setAttribute('readonly', ''); // Make it readonly to be tamper-proof
el.style.position = 'absolute';
el.style.left = '-9999px'; // Move outside the screen to make it invisible
document.body.appendChild(el); // Append the <textarea> element to the HTML document
const selected =
document.getSelection().rangeCount > 0 // Check if there is any content selected previously
? document.getSelection().getRangeAt(0) // Store selection if found
: false; // Mark as false to know no selection existed before
el.select(); // Select the <textarea> content
document.execCommand('copy'); // Copy - only works as a result of a user action (e.g. click events)
document.body.removeChild(el); // Remove the <textarea> element
if (selected) { // If a selection existed before copying
document.getSelection().removeAllRanges(); // Unselect everything on the HTML document
document.getSelection().addRange(selected); // Restore the original selection
}
};
ps adding the source
HTML:
<button type='button' id='btn'>Copy</button>
JS
document.querySelect('#btn').addEventListener('click', function() {
copyToClipboard('copy this text');
});
JS / Function:
function copyToClipboard(text) {
var selected = false;
var el = document.createElement('textarea');
el.value = text;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
if (document.getSelection().rangeCount > 0) {
selected = document.getSelection().getRangeAt(0)
}
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
};
guest271314's answer applied to multiple elements:
spans = document.querySelectorAll(".class");
for (const span of spans) {
span.onclick = function() {
document.execCommand("copy");
}
span.addEventListener("copy", function(event) {
event.preventDefault();
if (event.clipboardData) {
event.clipboardData.setData("text/plain", span.textContent);
console.log(event.clipboardData.getData("text"))
}
});
}
<span class="class">text</span>
<br>
<span class="class">text2</span>
This is the most suitable way to do it. It will copy all text in elements with the class "copy" in them.
var copy = document.querySelectorAll(".copy");
for (const copied of copy) {
copied.onclick = function() {
document.execCommand("copy");
};
copied.addEventListener("copy", function(event) {
event.preventDefault();
if (event.clipboardData) {
event.clipboardData.setData("text/plain", copied.textContent);
console.log(event.clipboardData.getData("text"))
};
});
};
.copy {
cursor: copy;
}
<p><span class="copy">Text</span></p>
<p><span class="copy">More Text</span></p>
<p><span class="copy">Even More Text</span></p>
u can also use onclick like
function copyCode() {
const Code = document.querySelector("input");
Code.select();
document.execCommand("copy", false);
}
<input type="input" />
<button onclick={copyCode()}>Copy</button>
function copy(that){
var inp =document.createElement('input');
document.body.appendChild(inp)
inp.value =that.textContent
inp.select();
document.execCommand('copy',false);
inp.remove();
}
<p onclick="copy(this)">hello man</p>
I want text within a textarea that has the hash # character to be replaced with an anchor link as they're typing.
eg. something #somethingelse somethingsomethingelse its actual code would be
something #somethingelse somethingelse
but in the textarea, I'd only want #somethingelse to be highlighted as I don't want it to actually have anchor code, kinda like how twitter and fb does it.
how does it work?
$('textarea').on("keyup", function() {
var str = $(this).val();
if (!str.match(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?#([a-zA-Z0-9]+)/g)) {
if (!str.match(/#([a-zA-Z0-9_]+)#/g)) {
str = str.replace(/#([a-zA-Z0-9_]+)/g, '#$1');
$('textarea').html(str)
}
}
});
.hashtag {
background: #000;
color: #fff;
}
I write it in javascript :
Html :
<textarea id="textArea" onkeyup="changeHash()"></textarea>
Javascript :
var outputString="";
function changeHash(){
var getObject= document.getElementById('textArea');
outputString =getObject.value.toString();
var checkTheLastChar = outputString.slice(-1);
if(checkTheLastChar=="#"){
outputString = outputString.substring(0, outputString.length - 1);
outputString += "⚓"; //Change it with anything you want
}
getObject.value = "";
getObject.value = outputString;
}
https://jsfiddle.net/emilvr/q27xgshe/1/
What you need to do is have a div below a transparent text area and duplicate the text from the textarea into the div with the links appended. If you append the text for a html tag to a text area it won't render because anything in a textarea only renders as editable text.
I want to set the focus to a b tag (<b>[focus should be here]</b>).
My expected result was that the b tag into the div has the focus and if I would write, that the characters are bold.
Is this impossible? How can I do this?
Idea was from here:
focus an element created on the fly
HTML:
<div id="editor" class="editor" contentEditable="true">Hallo</div>
JS onDomready:
var input = document.createElement("b"); //create it
document.getElementById('editor').appendChild(input); //append it
input.focus(); //focus it
My Solution thanks to A1rPun:
add: 'input.tabIndex = 1;' and listen for the follow keys.
HTML:
<h1>You can start typing</h1>
<div id="editor" class="editor" contentEditable="true">Hallo</div>
JS
window.onload = function() {
var input = document.createElement("b"); //create it
document.getElementById('editor').appendChild(input); //append it
input.tabIndex = 1;
input.focus();
var addKeyEvent = function(e) {
//console.log('add Key');
var key = e.which || e.keyCode;
this.innerHTML += String.fromCharCode(key);
};
var addLeaveEvent = function(e) {
//console.log('blur');
// remove the 'addKeyEvent' handler
e.target.removeEventListener('keydown', addKeyEvent);
// remove this handler
e.target.removeEventListener(e.type, arguments.callee);
};
input.addEventListener('keypress', addKeyEvent);
input.addEventListener('blur', addLeaveEvent);
};
You can add a tabIndex property to allow the element to be focused.
input.tabIndex = 1;
input.focus();//now you can set the focus
jsfiddle
Edit:
I think the best way to solve your problem is to style an input tag with font-weight: bold.
I had to cheat a little by adding an empty space inside the bold area because I couldn't get it to work on the empty element.
This works by moving the selector inside the last element in the contentEditable since the bold element is the last one added.
It can be edited to work on putting the focus on any element.
http://jsfiddle.net/dnzajx21/3/
function appendB(){
var bold = document.createElement("b");
bold.innerHTML = " ";
//create it
document.getElementById('editor').appendChild(bold); //append it
setFocus();
}
function setFocus() {
var el = document.getElementById("editor");
var range = document.createRange();
var sel = window.getSelection();
range.setStartAfter(el.lastChild);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
el.focus();
}
The SetFocus function I took was from this question: How to set caret(cursor) position in contenteditable element (div)?
How can I add custom text to already written text in textarea using javascript??Thanks...
function addText(elId,text) {
document.getElementById(elId).value += text;
}
or:
function addText(elId,text) {
var obj = document.getElementById(elId);
var txt = document.createTextNode(text);
obj.appendChild(txt);
}
myTextarea.value += "text to add to the textarea"
Grab the existing text in the textarea (the element's .value)
Combine your existing text (append, prepend, insert, or whatever you need)
Write the result back to the textarea.
Tah-dah!