How to clipboard some text from a div - javascript

How to copy text from div element on mobile devices.
Here is a example:
<div class="banks" onclick="copyAccountNumber(this);">
<div>
<img src="../../../../images/bank/khaan_bank_32x32.png" alt="">
<!-- <input onclick="setTimeout(function() {this.setSelectionRange(0, 9999);}, 1);" value="5037 6391 20" readonly="true"> -->
<div class="js_account">5037 6391 20</div>
<span>Хаан банк</span>
</div>
<div>
<img src="../../../../images/bank/khas_bank_32x32.png" alt="">
<!-- <input onclick="this.setSelectionRange(0, 9999);" value="5002 0860 50" readonly="true"> -->
<div class="js_account">5002 0860 50</div>
<span>Хас банк</span>
</div>
</div>
And javascript:
window.copyAccountNumber = function(elem) {
let divs = elem.querySelectorAll(".js_account");
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener("click", function(e) {
copyToClipboard(this);
});
}
};
function copyToClipboard(el) {
var oldContentEditable = el.contentEditable,
oldReadOnly = el.readOnly,
range = document.createRange();
el.contentEditable = true;
el.readOnly = false;
range.selectNodeContents(el);
var s = window.getSelection();
s.removeAllRanges();
s.addRange(range);
el.setSelectionRange(0, 9999);
el.contentEditable = oldContentEditable;
el.readOnly = oldReadOnly;
document.execCommand('copy');
}
But above not working anyways. I need to clipboard texts from .js_accountbut its not working well. What did i do wrong ? Any advice ?

You can take my code for example and change as per you requirement.. I have validated this code.. It is working fine.. Hope it's helpful for you..
Copying:------
<button onclick="myFunction()">
<div id="js_account">5037 6391 20</div>
</button>
<p>The document.execCommand() method is not supported in IE8 and earlier.</p>
<script>
function myFunction() {
const el = document.createElement('input');
var copyText = document.getElementById("js_account");
el.value = copyText.innerText;
document.body.appendChild(el);
el.select();
document.execCommand("copy");
document.body.removeChild(el);
alert("Copied the text: " + copyText.innerText);
}
</script>

Related

Main page textarea changes

If anyone from the forum can help it would be much appreciated.
Here is a script I have, by clicking a button, textarea changes, but the issue I have is the page always opens with a textarea.one visible as in CSS I have display:none for textarea.two and textarea.three.
My question is if before this page I have another page with 3 links and by clicking
link 1 - this script opens, textarea.one is visible, textarea.two and textarea.three are hidden.
link 2 - this script opens, textarea.two is visible, textarea.one and textarea.three are hidden.
link 3 - this script opens, textarea.three is visible, textarea.one and textarea.two are hidden.
Something similar to the language selection, if I have selected language on the page, it already knows that it should start with textarea.two visible instead of textarea.one and all similar pages will be opened based on this first choice of 'language'.
function hide1() {
document.querySelector("textarea.one").style.display = "block";
document.querySelector("textarea.two").style.display = "none";
document.querySelector("textarea.three").style.display = "none";
document.querySelector("button.menucopy1").style.display = "block";
document.querySelector("button.menucopy2").style.display = "none";
document.querySelector("button.menucopy3").style.display = "none";
}
function hide2() {
document.querySelector("textarea.one").style.display = "none";
document.querySelector("textarea.two").style.display = "block";
document.querySelector("textarea.three").style.display = "none";
document.querySelector("button.menucopy1").style.display = "none";
document.querySelector("button.menucopy2").style.display = "block";
document.querySelector("button.menucopy3").style.display = "none";
}
function Copytextfunction2() {
var value = document.getElementById("myInput2").value;
var copyText = document.createElement("textarea");
copyText.value = value;
copyText.style.position = "fixed";
copyText.style.top = "-1000vh";
document.body.append(copyText);
copyText.select();
copyText.setSelectionRange(0, 99999);
document.execCommand("copy");
console.log(value);
copyText.remove();
}
function Copytextfunction3() {
var value = document.getElementById("myInput3").value;
var copyText = document.createElement("textarea");
copyText.value = value;
copyText.style.position = "fixed";
copyText.style.top = "-1000vh";
document.body.append(copyText);
copyText.select();
copyText.setSelectionRange(0, 99999);
document.execCommand("copy");
console.log(value);
copyText.remove();
}
function Copytextfunction1() {
var value = document.getElementById("myInput1").value;
var copyText = document.createElement("textarea");
copyText.value = value;
copyText.style.position = "fixed";
copyText.style.top = "-1000vh";
document.body.append(copyText);
copyText.select();
copyText.setSelectionRange(0, 99999);
document.execCommand("copy");
console.log(value);
copyText.remove();
}
function hide3() {
document.querySelector("textarea.one").style.display = "none";
document.querySelector("textarea.two").style.display = "none";
document.querySelector("textarea.three").style.display = "block";
document.querySelector("button.menucopy1").style.display = "none";
document.querySelector("button.menucopy2").style.display = "none";
document.querySelector("button.menucopy3").style.display = "block";
}
<textarea class="one" id="myInput1" name="myInput1" readonly>
One
One
One</textarea>
</div>
<div class="textniz">
<textarea class="two" id="myInput2" name="myInput2" readonly>
Two
Two
Two</textarea>
</div>
<div class="textniz">
<textarea class="three" id="myInput3" name="myInput3" readonly>
Three
Three
Three</textarea>
</div>
<div class="navbar">
<div class="container">
<a class="logo" href=".//templates/chat.html">test</a>
</div>
</div>
<div>
<button class="menu">menu</button>
<button class="image">image</button>
<button onclick="hide1()" class="en">hide1</button>
<button onclick="hide2()" class="gr">hide2</button>
<button onclick="hide3()" class="ru">hide3</button>
<button onclick="Copytextfunction1()" class="menucopy1">copy1</button>
<button onclick="Copytextfunction2()" class="menucopy2">copy2</button>
<button onclick="Copytextfunction3()" class="menucopy3">copy3</button>
</div>
Hopefully, this is clear enough, I have made huge progress with the help of this forum, but unfortunately, as I move forward there is more and more I cannot figure out on my own, so whoever will be able to help it would be appreciated.
You can use this code and set links like this for textarea 1:
This link will show textarea 1 and hide the others.
Please note the changes made to your functions and the html where id is used instead of class.
But let me tell you, what you are trying to achieve is very definitely better done in another way.
// Get textarea from url parameters
const urlParams = new URLSearchParams(window.location.search);
let textarea = urlParams.get('textarea')
function show(textarea) {
for (let check = 1; check <= 3; check++) {
document.getElementById('myInput' + check).style.display = "none";
document.getElementById('menucopy' + check).style.display = "none";
}
document.getElementById('myInput' + textarea).style.display = "block";
document.getElementById('menucopy' + textarea).style.display = "block";
}
function Copytextfunction(textarea) {
var value = document.getElementById('myInput' + textarea).value;
var copyText = document.createElement("textarea");
copyText.value = value;
copyText.style.position = "fixed";
copyText.style.top = "-1000vh";
document.body.append(copyText);
copyText.select();
copyText.setSelectionRange(0, 99999)
document.execCommand("copy");
console.log(value);
copyText.remove();
}
// Run the hide function with the textarea number from parameters
if (textarea) {
show(textarea);
}
<div class="textniz">
<textarea id="myInput1" name="myInput1" readonly>
One
One
One
</textarea>
</div>
<div class="textniz">
<textarea id="myInput2" name="myInput2" readonly>
Two
Two
Two
</textarea>
</div>
<div class="textniz">
<textarea id="myInput3" name="myInput3" readonly>
Three
Three
Three
</textarea>
</div>
<div class="navbar">
<div class="container">
<a class="logo" href=".//templates/chat.html">test</a>
</div>
</div>
<div>
<button class="menu">menu</button>
<button class="image">image</button>
<button onclick="show(1)" id="en">hide1</button>
<button onclick="show(2)" id="gr">hide2</button>
<button onclick="show(3)" id="ru">hide3</button>
<button onclick="Copytextfunction(1)" id="menucopy1">copy1</button>
<button onclick="Copytextfunction(2)" id="menucopy2">copy2</button>
<button onclick="Copytextfunction(3)" id="menucopy3">copy3</button>
</div>
First of all, inline style should only be reserved as a last resort, use classes instead.
Second, avoid duplicating code, use centralized function for common usage.
If I understood you correctly, you need make one page to "communicate" with another page somehow? For that you can either use url parameters or hash #mydata, cookies or localStorage.
Here is an example of using localStorage to store the selected textarea id:
https://jsfiddle.net/veo6thy0/
Every time you refresh the page, it will show last shown textarea
let taId;
try
{
taId = localStorage.getItem("taId"); //get stored id
}
catch(e){}
if (!document.getElementById(taId))
taId = document.querySelector(".textniz textarea").id; //fallback to default first textarea
show(taId); //show text area
function show(taId) {
document.body.setAttribute("show", taId);
try
{
localStorage.setItem("taId", taId); //store textarea id
}
catch(e){}
}
function Copytextfunction(taId)
{
var value = document.getElementById(taId).value;
var copyText = document.createElement("textarea");
copyText.value = value;
copyText.style.position = "fixed";
copyText.style.top = "-1000vh";
document.body.append(copyText)
copyText.select();
copyText.setSelectionRange(0, 99999)
document.execCommand("copy");
console.log(value)
copyText.remove()
}
textarea[data-ta], /* hide textareas */
.menucopy[data-ta] /* hide copy buttons */
{
display: none;
}
body[show="myInput1"] [data-ta="myInput1"],
body[show="myInput2"] [data-ta="myInput2"],
body[show="myInput3"] [data-ta="myInput3"]
{
display: initial;
}
<div class="textniz">
<textarea class="one" id="myInput1" name="myInput1" data-ta="myInput1" readonly>
One
One
One</textarea>
</div>
<div class="textniz">
<textarea class="two" id="myInput2" name="myInput2" data-ta="myInput2" readonly>
Two
Two
Two</textarea>
</div>
<div class="textniz">
<textarea class="three" id="myInput3" name="myInput3" data-ta="myInput3" readonly>
Three
Three
Three</textarea>
</div>
<div class="navbar">
<div class="container">
<a class="logo" href=".//templates/chat.html">test</a>
</div>
</div>
<div>
<button class="menu">menu</button>
<button class="image">image</button>
<button onclick="show(this.dataset.ta)" class="en" data-ta="myInput1">textarea1</button>
<button onclick="show(this.dataset.ta)" class="gr" data-ta="myInput2">textarea2</button>
<button onclick="show(this.dataset.ta)" class="ru" data-ta="myInput3">textarea3</button>
<button onclick="Copytextfunction(this.dataset.ta)" class="menucopy" data-ta="myInput1">copy1</button>
<button onclick="Copytextfunction(this.dataset.ta)" class="menucopy" data-ta="myInput2">copy2</button>
<button onclick="Copytextfunction(this.dataset.ta)" class="menucopy" data-ta="myInput3">copy3</button>
</div>
P.S.
Just a little clarification in case it's too confusing. This code uses data-* attributes to "link" textareas with it's corresponded buttons. That attribute also used in CSS to hide/display needed textareas and "copy" buttons. The value of that attribute can be accessed in javascript via dataset property of the element, i.e. attribute data-blah="ok" in javascript can be accessed via myElement.dataset.blah

javascript event fire only one

I am having a problem with the code below.
The code should handle the slider and changes between them when the img is
clicked, it works only once.
when I changed the onClick event to
document.getElementById("left").onclick = function(){
console.log("0");
}
It worked fine, but when I reverted, it doesn't change the slider more than once
snippet:
var index = 0;
document.getElementById("left").onclick = function(){
console.log("0");
}
document.getElementById("left").onclick = function(){
var slider = document.getElementsByClassName("slider");
slider[index].style.display = "none";
if(index == 0){ index = slider.length;}
slider[--index].style.display = "block";
}
document.getElementById("right").onclick = function(){
var slider = document.getElementsByClassName("slider");
slider[index].style.display = "none";
if(index >= slider.length){ index = 0;}
slider[++index].style.display = "block";
};
<div class="slider" style="display: block">
<div id = "left"><img src="Images/arrow-left.png" alt=""></div>
<div class="text">
<h2>welcome to the <span>classic</span></h2>
<p>Lorem ipsum is a name for a common type of placeholder text. Also known as filler or dummy text, this is simply copy that serves to fill a space</p>
</div>
<div id = "right"><img src="Images/arrow-right.png" alt=""></div>
</div>
thanks guys, the problem was that I gave multiple div the same ID which made the onclick event only fire once (with the first div only)

how to delete a particular element in javascript

I want to make a function to create a new box when I click 'add new box' button and after that, it will also able to delete the box when I click the particular delete button which is related with the box. How to make the function in javascript? Should I save in an array for every new element that it creates?
My code:
function addBox() {
var el = document.getElementById('target');
var clone = el.cloneNode(true);
var frame = document.getElementById('container');
var attr = document.createAttribute('val');
attr.value = 'demo';
el.setAttributeNode(attr);
frame.appendChild(clone);
}
<div id="container">
<div id="target" class="foo" val="demo">
<div class="content" style="width:100px;height:100px;background:orange;margin:1px" ></div>
</div>
</div>
<button onclick="addBox();">Add box</button>
<button onclick="deleteBox();">Delete box</button>
I wanted to be like this!
You need to target the button element using this as an argument on the deleteBox() function and then the parent of the button by using parentNode and then apply remove() method on it:
function addBox() {
var el = document.getElementById('target');
var clone = el.cloneNode(true);
var frame = document.getElementById('container');
var attr = document.createAttribute('val');
attr.value = 'demo';
el.setAttributeNode(attr);
frame.appendChild(clone);
}
function deleteBox(e){
e.parentNode.remove()
}
.content{
width: 100px;
height: 100px;
margin-bottom: 10px;
background: #F5A623;
display: inline-block;
vertical-align: middle;
}
<div id="container">
<div id="target" class="foo" val="demo">
<div class="content" style="width:100px;height:100px;background:orange;margin:1px"></div>
<button onclick="deleteBox(this);">Delete</button>
</div>
</div>
<button onclick="addBox();">Add box</button>
As a sidenote, I strongly recommend you to have unique ids on elements.
Try this,
<div id="container">
<div id="target" class="foo" val="demo">
<div class="content">aaa</div>
<button onclick="deleteBox(this);">Delete box</button>
</div>
</div>
<button onclick="addBox();">Add box</button>
function addBox() {
var el = document.getElementById('target');
var clone = el.cloneNode(true);
var frame = document.getElementById('container');
var attr = document.createAttribute('val');
attr.value = 'demo';
el.setAttributeNode(attr);
frame.appendChild(clone);
}
function deleteBox(obj){
obj.parentElement.remove();
}
JQuery:
function deleteBox(){
$( "#target" ).remove();
}
Javascript:
function deleteBox(){
document.getElementById('target').remove()
}
This is alternative example, You can try in your code :)
var sentenceIndex = 1;
function addSentence() {
var n = sentenceIndex;
var html = '<div class="form-item-wrap" id="sentencebox' + n + '">'+
'<div class="form-item">'+
'<input class="form-control" type="text" id="sentence'+n+'" name="sentence[' + n + ']">'+
'</div>'+
'<div class="course-region-tool">'+
'<a href="javascript:void(0);" onclick="removeSentence('+n+');" class="delete" title="delete">'+
'<i class="icon md-recycle"></i></a></div></div>';
$("#addSentenceDiv").append(html);
sentenceIndex = sentenceIndex + 1;
}
function removeSentence(id) {
console.log(id);
$("#sentencebox"+id).remove();
}

trigger onmouseup element correctly

I have following html structure:
<div id="grandparent">
<div id="parent">
<p>
high light me with mouse!! highlight me with mouse!!highlight me with mouse!!
</p>
</div>
</div>
And I have this js code:
$(document).mouseup(function (event) {
var target=event.target;
target=$(target);
var parent = target.parent();
console.log(parent.parent().attr("id"));
if (window.getSelection) {
var selection = window.getSelection();
selectedText = selection.toString();
console.log(selectedText);
}
});
So this piece of code just console logs selected text.
But I have a problem - when I click not on my <p> element and just on document - and then I move mouse to select text holding left button I can't get the id of parent div because
var target=event.target;
target becomes document element
Change $(document).mouseup( for $("#parent").mouseup( .
Code:
$("#parent").mouseup(function (event) {
var target=event.target;
target=$(target);
var parent = target.parent();
console.log(parent.parent().attr("id"));
if (window.getSelection) {
var selection = window.getSelection();
selectedText = selection.toString();
console.log(selectedText);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="grandparent">
<div id="parent">
<p>
high light me with mouse!! highlight me with mouse!!highlight me with mouse!!
</p>
</div>
</div>

Copy All Script on Forum HTML TextBox

I am trying to code a HTML text box, with a button to COPY all the text contents of a particular div class.
The code does copy text, however, it copys text from the entire page (multiple posts on a forum) instead of the one post of interest. Is there a way to stop it doing this?
My code below so far,
Many Thanks for your help
<div class="main">
<div class="container">
<div class="codebox">
<div class="ipsCode_citation">
<div style="float:right">
<button onclick="copyText()">Copy</button>
</div>
Code:
</div>
<p> </p>
</div>
</div>
</div>
<p> </p>
<div id="output"></div>
<script>
function copyText(){
var outputText = "";
var targets = document.getElementsByClassName('codebox');
for (var i = 0; i < targets.length; i++) {
outputText += targets[i].innerText;
}
var output = document.getElementById('output');
output.innerText = outputText;
var range = document.createRange();
range.selectNodeContents(output);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
output.style.display = 'none';
}
</script>
In an attempt to apply Matt Webbs suggestion. Is this on the correct lines?
<div class="codebox">
<div>
<button class="codeBtn">Copy</button>
</div>
<p> </p> Some text to copy
</div>
<script>
var copyBtn = document.querySelector('.codeBtn');
copyBtn.addEventListener('click', function(event) {
var copyText = document.querySelector('.codebox');
copyText.select();
var successful = document.execCommand('copy');
});
</script>
Here is a sample of what you need, this will copy the contents within .codebox to the clip board.
HTML
<div>
<textarea class="codebox">function helloWorld() {}</textarea>
</div>
<div>
<button class="codeBtn">Copy</button>
</div>
JS
var copyBtn = document.querySelector('.codeBtn');
copyBtn.addEventListener('click', function(event) {
var copyText = document.querySelector('.codebox');
copyText.select();
var successful = document.execCommand('copy');
});
Sample:
JsFiddle
UPDATE
To get the text (or html) form the specific area where the button is, using the html you have provided, you can do something like this, notice I have used a hidden textarea so we can still utilise the document.execCommand('copy'):
HTML
<div class="codebox">
<div class="ipsCode_citation">
<div style="float:right">
<button class="codeBtn">Copy</button>
</div>
Code:
<textarea style="display:none" id="hidden-codebox"></textarea>
</div>
</div>
JAVASCRIPT
var copyBtn = document.querySelector('.codeBtn');
copyBtn.addEventListener('click', function(event) {
// copy element text:
var copyText = document
.querySelector('.codeBtn') // button
.parentElement // div
.parentElement // div.ipsCode_citation
.parentElement.innerText; // div.codebox
// push to HIDDEN textarea:
var hiddenCode = document.getElementById('hidden-codebox');
hiddenCode.value = copyText;
hiddenCode.select();
try {
var status = document.execCommand('copy');
if (!status) {
console.error("Cannot copy text");
} else {
console.log("The text is now on the clipboard");
}
} catch (err) {
console.log('Unable to copy.');
}
});
Sample:
JsFiddle

Categories