How can I copy text (<p>) to the clipboard on an image click using jQuery in the most simple way? - javascript

I am looking for the simplest possible solution to copy text within a html p tag on an image click to the clipboard.
I tried some small (code wise) solutions from this thread Click button copy to clipboard using jQuery, but it just won't copy the text. In my case I need it to work with an image click rather than a button click.
$("#clipboardImage").click(function() {
$("#didText").select();
document.execCommand("copy");
alert("Text copied")
});
#didText {
color: #1816A9;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<div id="didContainer">
<p id="didText" type="text">I hopefully end up in the form field anytime soon!</p>
<img id="clipboardImage" src="" alt="Click me, to bring him down!">
</div>
<br>
<form>
Worked?
<input type="text" name="copied Text">
</form>
</html>

If I understand well your goal is to put the text from the p tag into the input field.
Just select the text with JQuery .text() and put it into the input filed as a value
EDIT
So, if the main goal is to put some text from an element to the clipboard I suggest to use a dedicated function, there's a workaround that create an invisible and readonly textarea and use it as a "proxy" to store and copy the text to your clipboard.
NB: to avoid passing the text to the input field just get rid of $("input").val(text); row.
function copyToClipboard (str) {
var 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
var selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : 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
}
};
$("#clipboardImage").click(function() {
var didText = $("#didText");
var text = didText.text();
copyToClipboard(text);
$("input").val(text);
alert("Text copied")
});
#didText {
color: #1816A9;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<div id="didContainer">
<p id="didText" type="text">I hopefully end up in the form field anytime soon!</p>
<img id="clipboardImage" src="" alt="Click me, to bring him down!">
</div>
<br>
<form>
Worked?
<input type="text" name="copied Text">
</form>
</html>

Related

How to make text bold that function got as parameter

I would like to make a text bold by using a function which gets the text as a parameter, here is my code:
<script>
function font(b)
{
b.style.fontWeight = "bold";
alert(b);
}
</script>
<input onclick="font('aaaa');" type="button" value="Font (1)">
My problem that I'm not getting the desired response, though without b.style.fontWeight = "bold"; it alerts "aaaa".
I don't see what is the problem here, I tried to put the parameter in a variable and then change its property but it doesn't work either.
Any ideas on how to resolve this?
Create an input field where you'll write your text and create a button which will change the font-weight of the text. After that attach an event listener to the button. When you click the button your font will change to bold.
working demo: https://jsfiddle.net/4kzsq2tb/
HTML
<button id="font-button">
change font to bold
</button>
<input id="input-field" type="text"/>
JS
document.getElementById('font-button').addEventListener('click', () => {
const inputField = document.getElementById('input-field');
font(inputField);
})
function font(b) {
b.style.fontWeight = "bold";
}
<div id="c"></div>
<input onclick="font('aaaa');" type="button" value="Font (1)">
<script>
function font(b)
{
document.getElementById('c').style.fontWeight = "bold";
document.getElementById('c').innerHTML=b;
}
</script>
works fine function gets text as parameter and makes it bold, well makes div style bold not text itself as guys said u cant make text or variable bold

Working clipboard script not compatible with Chrome. Works with Edge/IE

I have a working clipboard script that I have to use on our portal page to utilize clipboard functionality. We are moving from IE/Edge to Chrome, and it seems this script will not function in Google Chrome. I would love it if we can find a way to make the code chrome/multi browser compatible without having to make a new script for Chrome-only.
While I do have a working script for Chrome, it would mean i would have to re-build hundreds of pages using clipboard, and I would rather make the script already embedded in all these pages chrome compatible. Below is the script i am using:
(function() {
'use strict';
// click events
document.body.addEventListener('click', copy, true);
// event handler
function copy(e) {
// find target element
var
t = e.target,
c = t.dataset.copytarget,
inp = (c ? document.querySelector(c) : null);
// is element selectable?
if (inp && inp.select) {
// select text
inp.select();
try {
// copy text
document.execCommand('copy');
inp.blur();
// copied animation
t.classList.add('copied');
setTimeout(function() { t.classList.remove('copied'); }, 1500);
}
catch (err) {
alert('please press Ctrl/Cmd+C to copy');
}
}
}
})();
// Button must include data-copytarget="#website" with the #xxx matching the element id
Results: In IE/Edge, you click on the button and the assigned text to that button is added to the clipboard for pasting. In Chrome however, clicking on the button and nothing happens.
Your code works fine in Chrome as long as the input is visible.
Chrome does not allow copying from a hidden input. There are multiple workarounds. In the example below, I've moved the input of screen using absolute positioning.
(function() {
"use strict";
// click events
document.body.addEventListener("click", copy, true);
// event handler
function copy(e) {
// find target element
var t = e.target,
c = t.dataset.copytarget,
inp = c ? document.querySelector(c) : null;
// is element selectable?
if (inp && inp.select) {
// select text
inp.select();
try {
// copy text
document.execCommand("copy");
inp.blur();
// copied animation
t.classList.add("copied");
setTimeout(function() {
t.classList.remove("copied");
}, 1500);
} catch (err) {
alert("please press Ctrl/Cmd+C to copy");
}
}
}
})();
#vishidden {
position: absolute;
top: -9999px;
left: -9999px;
}
<div>
<input type="text" id="text" value="visible test" readonly="true">
<button type="button" data-copytarget="#text">copy</button>
</div>
<div>
<input type="hidden" id="hidden" value="hidden test" readonly="true">
<button type="button" data-copytarget="#hidden">copy hidden</button>
</div>
<div>
<input type="text" id="vishidden" value="visually hidden test" readonly="true">
<button type="button" data-copytarget="#vishidden">copy visually hidden</button>
</div>
<div>
<textarea cols="30" rows="10" placeholder="paste here to test"></textarea>
</div>
Another example: Using execCommand (Javascript) to copy hidden text to clipboard
Clipboard.js is a useful library to do this. It also uses a visually hidden input behind the scenes (in a similar but more robust way than in my example).

Change caret position in textarea by click on button

I have a textarea with this content :
[supreme] a test text or anything [/supreme]
I have a button too. I want to when button clicked , textarea selected and change caret position to this :
[supreme] a test text or anything <caret postion> [/supreme]
How can i do this with javascript or jquery ?
Thanks .
Here is a quick example. It could be done cleaner but it should get you started.
$(document).ready(function() {
$('.button').click(function(e) {
var $textArea = $('.textArea');
var prevValue = $textArea.val();
$textArea.focus().val('').val(prevValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="textArea">a test text or anything</textarea>
<button class="button">
CLick Me
</button>

Add elements to textarea by clicking a button

I want to add text to textarea when user clicks a button. I have used the code bellow :
<script>
document.addEventListener('DOMContentLoaded', start, false);
function start(){
document.getElementById("button0").addEventListener("click", function(){
addText(this);
});
function addText(elem) {
document.getElementById("transcript").innerHTML += elem.value;
}
};
</script>
When the users click the button the text added to the textarea but the moment they type using their keyboard they won't be able to add the text using the button anymore.
use .value not .innerHTML.
.innerHTML overwrites the markup of the element, not just the text. Since it's a form element you should be manipulating its value only.
document.getElementById("button0").addEventListener("click", function() {
document.getElementById("transcript").value += "huh";
});
#transcript {
height: 100px;
}
<button id="button0">Click Me</button>
<textarea id="transcript"></textarea>

Delete the previous and next HTML element by javascript

I want to delete the previous and next HTML element after using the mouse highlighting the selected text by javascript, but I only know how to get the selected/highlighted text, can anyone help me? Thank you.
function text() {
if (window.getSelection)
return window.getSelection();
if (document.getSelection)
return document.getSelection();
if (document.selection)
return document.selection.createRange().text;
return "";
}
function delete_Tag () {
var txt = text();
// txt already have the selected text
// I don't know how to do in here !!!
// I use the use the find the parentNode, but don't know how to delete the </span>
}
<input type='button' value='Delete Tag' onclick='delete_Tag ()' />
<p id='text'>
<span class="B">I am </span>
<span class="B">working in </span>
<span class="C">ABC company.</span>
</p>
e.g. I use the mouse to highlight the 'working in ' OR 'orkin' (the selected must be within the ) and click the button, it will show
Expected Result:
<p id='text'>
<span class="B">I am </span>
working in
<span class="C">ABC company.</span>
</p>
You can use something like the following:
var span = document.getElementsByClassName("B").item(0);
var parent = span.parentNode;
var sibling = span.nextSibling;
var textNode = document.createTextNode(span.innerHTML);
parent.removeChild(span);
parent.insertBefore(textNode, sibling);
You can use Jquery hide method.
It would seem that your having trouble deleting the elements, it may be more efficient to hide the selected elements rather than using jQuery.
You need do some extra stuff. You need catch document.body.onmousedown and document.body.onmouseup. If targets of this events are the same node then you have to save this node for further use.
I have created working example for you

Categories

Resources