How do I copy portion of <p> text onClick - javascript

I have an HTML document with a 'p' element which I would like a portion of copied to the clipboard when the whole element is clicked.
<p class="pageID"><strong>Page ID: </strong>#A16</p>
Which returns: PageID: #A16
I want to have it so when I click anywhere on this line the page ID (#A16) is copied to the clipboard but nothing else. I've seen some similar questions on here and tried a bunch of different JavaScript solutions but nothing is working.
Any ideas?
Thanks!

You could try something like this:
<p class="pageID"><strong>Page ID: </strong><span id="toCopy">#A16</span></p>
<script>
document.querySelector(".pageID").addEventListener('click', function() {
var temp_input = document.createElement("INPUT");
temp_input.value = document.querySelector('#toCopy').innerHTML;
temp_input.select();
document.execCommand("copy");
});
</script>
No jQuery needed!

Off the top of the head, I'd wrap whatever you're trying to copy into it's own element and copy the text of the element.
ex: <p class="pageID"><strong>Page ID: </strong><span class="your-class-name">#A16</span></p>

You should wrap that text in element with some id and then focus on it and copy like this
varĀ el = document.getElementById("myText");
el.select();
document.execCommand("copy");

You can do something like this:
<div id="myId"><p class="pageID" id="myElement"><strong>Page ID: </strong>#A16</p></div>
<script>
$('#myId').onClick(function() {
var copyText = document.getElementById("myElement");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value); // do whatever you want with this text.
});
</script>

Related

Copy text string on click

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>

Can I use setAttribute to change the text inside the text node?

I know that I can use nodeValue to change the text inside the text likeelement.firstChild.nodeValue = text but can I use setAttribute to do the same thing?
HTML :
<p id="description">Some text here.</p>
JS :
var description = document.getElementById("description");
description.setAttribute(nodeValue, text);
It doesn't work. Does it means that "nodeValue" is not an attribute of an element?
No. setAttribute does, well, set an attribute. It doesn't set contents.
However, you can use CSS to display an attribute as if it were content.
var description = document.getElementById("description");
description.setAttribute('data-content', 'Updated text');
#description::after {
content: attr(data-content);
}
<p id="description" data-content="Some text here."></p>
This should only be used for styling purposes, not to insert real content.
You want to set node content here and not node attribute so you could use .textContent instead :
// Set the text content:
description.textContent = text;
Hope this helps.
var description = document.getElementById("description");
var text = 'New text';
description.textContent = text;
<p id="description">Some text here.</p>
No you cannot. setAttribute is used to manipulate HTML element attributes.
For example, if you wanted to update a button to be disabled you would do something like:
var button = document.querySelector('my-button');
button.setAttribute('disabled', 'disabled');
To change the text you should use textContent:
var description = document.getElementById("description");
description.textContent = 'New text here.';

Onclick event on a paragraph is triggered under the paragraph

I wich to replace a paragraph with a textarea tag when clicking on the paragraph, the textarea should contain the text that was in the paragraph:
<div id="right"><p><pre><?php echo $descri; ?></pre></p></div>
Jquery script :
$(function(){
$('#right').on('click', 'p', function(){
var $p = $(this);
var old = $p.html();
if(/<textarea rows="4" cols="40" id="descri" name="descri"/.test(old))
return;
$p.html('<textarea rows="4" cols="40" id="descri" name="descri" value="' + old + '"/>')
.find('textarea')
.focus()
.on('blur', function(){
var value = this.value;
$.post('listener_updates.php', {description: value})
.done(function(){
$p.html(value);
})
.fail(function(){
$p.html(old);
alert('Could not update title');
});
});
});
});
Now when I click on the paragraph text, nothing happens but when I click a little under the paragraph text, then the textarea appears and is empty.
Thank you for your help
This is because you can't put a pre element inside a p element, so the browser's correcting the invalid DOM. The content model of p is phrasing content, but pre isn't valid in phrasing content, only flow content.
When you give this to Chrome:
<div class="right"><p><pre>This is the text</pre></p></div>
...it actually creates this DOM:
<div class"right"><p></p><pre>This is the text</pre><p></p></div>
Note that the pre is no longer in any p.
If you want the pre, simply use pre on its own (without the p). pre is a lot like like p: They both have the same content model, they're both valid in the same places, and they're both display: block by default.
Alternately, if your only goal is not to have line wrapping and other such, on modern browsers you can get rid of the pre (keeping the p or using a div if the semantics of p aren't appropriate) and use the CSS white-space property (e.g., white-space: pre) instead.
Re your comment below:
but I can't get the text inside the pre tag to show on the textarea
Just put the pre's contents() into the textarea, put the textarea in the DOM where you want it, and remove or hide the pre. This removes it, for instance: Live Example
$(".right").on("click", "pre", function() {
var $pre = $(this);
var $textarea = $("<textarea>");
$textarea.append($pre.contents());
$pre.replaceWith($textarea);
return false;
});

How do I get HTML tags inside of a Javascript Text Node?

my question was pretty much explained up in the title. How do I get HTML tags inside of a Javascript Text Node? The result of my code on the page is...
Click Here
However, I want "Click Here" to be a link. I am new to Javascript, so this would help me out a lot. Below is an example of what I'm talking about...
<div id="mydiv">
</div>
<script type="text/javascript">
var mynode=document.createTextNode('Click Here');
document.getElementById('mydiv').appendChild(mynode);
</script>
You can't put links in a text node. Links are elements. Elements can (sometimes) contain text nodes, but the reverse is not true.
You need to create an element, set attributes on it, then append text to that element.
var link = document.createElement('a');
link.setAttribute('href', 'http://www.example.com');
link.appendChild(document.createTextNode('Click Here'));
document.getElementById('mydiv').appendChild(link);
<div id="mydiv">
</div>
<script type="text/javascript">
var element = document.createElement('a');
element.setAttribute("href","http://www.example.com");
element.appendChild(document.createTextNode('Click Here'));
document.getElementById('mydiv').appendChild(element); </script>
</script>
You're looking for document.createElement, not document.createTextNode. Text-nodes cannot contain HTML.
An easy alternative, if you're not using complex Javascript (which it seems you aren't) would just be:
document.getElementById('mydiv').innerHTML.='Click Here';
I needed to insert an element in the middle of a text node (replace a word with a span). I did it by replacing the text node altogether:
(uses jQuery)
function replace_text(element, search, replacement_html){
if(!element) element=document.body;
var nodes=element.childNodes;
for(var n=0;n<nodes.length;n++){
if(nodes[n].nodeType==Node.TEXT_NODE){
if(nodes[n].textContent.match(new RegExp(that.escapeRegExp(search),'gi'))){
var newtextContent=nodes[n].textContent.replace(
new RegExp(escape_regex(search),'gi'), replacement_html);
$(nodes[n]).before(newtextContent).remove();
}
} else {
replace_text(nodes[n], search, replacement_html);
}
}
}
function escape_regex(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
And then calling:
$('.highlight_terms_here').each(function(){
replace_text(this,
the_word,
'<span style="background-color: yellow">'+the_word+'</span>');
})
Or simply:
replace_text($('#contents')[0], the_word,
'<span style="background-color: yellow">'+the_word+'</span>');

Add text to text area using javascript

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!

Categories

Resources