Copy All Script on Forum HTML TextBox - javascript

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

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

How to change the innerHTML of various divs when clicking on various buttons?

In my web-page I have various buttons (in the class .addbutton). When the first of these is clicked, a <div> appears with a drop-down, from which the user can select any of 2 options (#p1, `#p2), which vary depending on which button was clicked.
When each of these options is clicked, I want it to appear in the <div> that corresponds with the initial .addbutton that was clicked. (e.g if the first .addbutton is clicked (#bradd) I want the options selected in the first div (#bdiv))I managed to do this so that they always appear in the #bdiv, no matter what .addbutton was clicked, but I can't work out how to make each appear in the corresponding one.
JS to set the innerHTML of the 2 options
document.getElementById("bradd").onclick = function() {
document.getElementById("p1").innerHTML = "Cereal"
document.getElementById("p2").innerHTML = "Juice"
}
document.getElementById("mmadd").onclick = function() {
document.getElementById("p1").innerHTML = "2x small fruit"
document.getElementById("p2").innerHTML = "Big fruit"
}
JS to change the innerHTML of the first div (#bdiv)
document.getElementById("p1").onclick = function() {
var newItem = document.createElement("div")
newItem.innerHTML = document.getElementById("p1").innerHTML document.getElementById("bdiv").appendChild(newItem)
}
document.getElementById("p2").onclick = function() {
var newItem = document.createElement("div")
newItem.innerHTML = document.getElementById("p2").innerHTML
document.getElementById("bdiv").appendChild(newItem)
}
My HTML:
<h1>Meal Plan Customizer</h1>
<div id="list">
<input type="checkbox">
<p>Breakfast:</p>
<button class="addbutton" id="bradd">+</button>
<div id="bdiv"></div>
<br>
<input type="checkbox">
<p>Mid-Morning:</p>
<button class="addbutton" id="mmadd">+</button>
<div id="mdiv"></div>
<br>
<input type="checkbox">
<div id="dropdownList">
<p id="p1">Option1</p><br><br>
<p id="p2">Option2</p><br><br>
</div>
</div>
</div>
Your code should work.
Please check this:
https://jsfiddle.net/oliverdev/3wsfgov1/
If your code is not working, it is because Javascript code is loaded before loading the HTML.
You can modify the Javascript code like this:
window.onload = function(e){
document.getElementById("bradd").onclick = function() {
document.getElementById("p1").innerHTML = "Cereal"
document.getElementById("p2").innerHTML = "Juice"
}
document.getElementById("mmadd").onclick = function() {
document.getElementById("p1").innerHTML = "2x small fruit"
document.getElementById("p2").innerHTML = "Big fruit"
}
}
It will work for you
You are making this far more complicated and repetitive than necessary.
By storing your data in a structured object and using classes for the content elements you can make generic event listeners for all of this
Following is by no means complete but will give you a good idea how to approach something like this
var data = {
bradd: {
p1: "Cereal",
p2: "Juice"
},
mmadd: {
p1: "2x small fruit",
p2: "Big fruit"
}
}
var selectedButton = null;
var opts = document.querySelectorAll('#dropdownList p');
for (let p of opts) {
p.addEventListener('click', updateContent)
}
// generic event handler for all the options
function updateContent() {
const content = selectedButton.closest('.item').querySelector('.content')
content.innerHTML = this.innerHTML
togglePopup()
}
document.querySelector('#xbutton').addEventListener('click', togglePopup)
// generic event handler for all buttons
function addButtonClicked() {
selectedButton = this;// store selected for use when option selected
var wantedData = data[selectedButton.id];
for (let p of opts) {
p.innerHTML = wantedData[p.id]
}
togglePopup();
}
for (let btn of document.getElementsByClassName("addbutton")) {
btn.addEventListener("click", addButtonClicked)
}
function togglePopup() {
var popStyle = document.getElementById("addPopUp").style;
popStyle.display = popStyle.display === "block" ? 'none' : 'block'
}
#addPopUp {
display: none
}
<h1>Meal Plan Customizer</h1>
<div id="list">
<div class="item">
<p>Breakfast:</p>
<button class="addbutton" id="bradd">+</button>
<div class="content"></div>
</div>
<div class="item">
<p>Mid-Morning:</p>
<button class="addbutton" id="mmadd">+</button>
<div class="content"></div>
</div>
</div>
<div id="addPopUp">
<h3 id="h3">Select what you would like to add:</h3>
<span id="xbutton"><strong>×</strong></span>
<div class="dropdown">
<div id="dropdownList">
<p id="p1">Option1</p>
<p id="p2">Option2</p>
<!-- <p id="p3">Option3</p><br><br>
<p id="p4">Option4</p>-->
</div>
</div>
</div>

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 clipboard some text from a div

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>

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>

Categories