I have a hidden text area like this with some values set:
<textarea style="display: none;" id="element_html"></textarea>
On click of a button, I try to copy its content to clipboard using this JS code:
$('#element_html').select();
document.execCommand('copy');
It works only if the text area is visible. How can I copy the hidden text area content to clipboard?
opacity: .01;
does the job. You should combine it with:
height:0;
position:absolute;
z-index: -1;
Do not use pointer-events:none; as it will stop .select() from working, as well.
function copyContents() {
$('#element_html').select();
document.execCommand('copy');
}
#element_html {
position: absolute;
opacity: .01;
height: 0;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="element_html">Which textarea?</textarea>
<button onclick="copyContents()">Copy</button>
<input type="text" placeholder="Paste it here...">
You can create a temporary input element that is appended to the body, set it its value to the textarea's content and then use it for the copy function. Then you remove it from the dom. This will work - irrespective of the display state of the text area.
Note that I did not create this method - I got it from somewhere (possibly another SO answer) and have used it since in a number of instances.
function copyContents() {
var $temp = $("<input>");
var content = $('#element_html').text();
$("body").append($temp);
$temp.val(content).select();
document.execCommand("copy");
$temp.remove();
}
#element_html {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="element_html">Hidden textarea content</textarea>
<button onclick="copyContents()">Click to copy</button>
<input type="text" placeholder="Paste here">
The problem is that since the textarea has its display property set to none, its content can not be selected. You can absolutely position the textarea to the left with position: absolute and left: -9999px. You should also add z-index: -9999 so it will always be placed under other elements (unless they have a lower z-index).
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea style="position: absolute; left: -9999px;" id="element_html">Text inside textarea</textarea>
<button onClick="copy()">
Copy
</button>
<p/>
<textarea placeholder="Paste text here..."></textarea>
<script>
function copy(){
$('#element_html').select();
document.execCommand('copy');
}
</script>
The Following codes worked for my problem. paste the js code inside your script tag/file.also add the css style to hide the textarea. Also, I found the following ideas through stackoverflow forum so all credit to those folks.
HTML code:
function cpy(n)
{
var id=n;
var txt=document.getElementById(id);
txt.select();
document.execCommand("copy");
};
/* The Following Code is to Hide textarea from The user view area */
textarea{
opacity: 0;
position: absolute;
z-index: -9999;
pointer-events: none;
}
<!-- readonly attribute is used because i found that in mobile devices, keyboard poped-up while i clicked the button to copy text-->
<textarea id="c1" readonly>
This is a text from textarea One.
</textarea><br>
<!--The cpy(this.id) passes button id to js function-->
<button id="c1" onclick="cpy(this.id)">Copy</button>
<input type=text placeholder="Paste Here to test">
Related
I am trying to make a simple text editing box so that I can eventually post text to another section of a website. I'm attempting to make buttons to make text bold, italicized, add a code box etc, (hence insertAdjacentHTML not insertAdjacentText) but I decided to just start making sure I could get plain text to print to a textarea.
I have achieved this easily but now my question becomes how do I make it so that the button still affects the text area after a user has added text to it? the code below will happily type out "hello"'s up until you click on the textarea, and from that point on it refuses to and I can't figure out why.
window.hello = function(textarea) {
var obj = document.getElementById("text");
obj.insertAdjacentHTML('beforeend', 'hello');
}
<body>
<button onclick="hello()">hello</button>
<form>
<p></p>
<textarea id="text"></textarea>
</form>
</body>
As you can read from MDN a textarea can contain only Character data.
This is the reason because you cannot use insertAdjacentHTML and instead you can use the value.
If you need to add text in bold or ... you can use a contenteditable div element.
The snippet:
window.helloDiv = function() {
var obj = document.getElementById("textDiv");
obj.insertAdjacentHTML('beforeend', 'hello');
};
window.helloTxtArea = function() {
var obj = document.getElementById("textTxtArea");
obj.value += 'hello';
}
div {
width: 300px;
height: 100px;
border: 1px;
border-style: solid;
}
textarea {
width: 300px;
height: 100px;
margin-top: 10px;
}
<button onclick="helloDiv()">helloDiv</button>
<button onclick="helloTxtArea()">helloTextArea</button>
<form>
<p></p>
<div id="textDiv" contenteditable="true"></div>
<textarea id="textTxtArea" contenteditable="true"></textarea>
</form>
Thanks for viewing my question. I have a form below that has a file input field. Safe to say I have hidden this input field, and am now using the label as the primary "button" to select the files. Once a user clicks on the "Upload Picture..." label, I want the text inside the label to change from "Upload Picture..." to the file name. I'm following this tutorial below however the javascript written (in the tutorial) is for multiple files being able to be selected by the user. I only am allowing my users to select ONE file. This is a change your profile picture page to give a little insight as to what this form does.
Here is the code:
<!-- Change Picture Form -->
<div class="changepic-wrap">
<form action="changepicauth.php" method="post">
<input type="file" name="profilepic" id="profilepic" class="inputfile">
<br>
<label for="profilepic">
<img src="/images/profile/upload.png" />
Upload Picture...
</label>
<br>
<div class="button-wrap">
<button>Change Picture</button>
</div>
</form>
</div>
Here is the tutorial:
http://tympanus.net/codrops/2015/09/15/styling-customizing-file-inputs-smart-way/
Can someone help explain to me what i have to do? I'm thinking something along the lines of an eventlistener but i'm not sure about javascript. I'm a backend dev and know very little about javascript. I do NOT WISH TO USE JQUERY. Straight javascript only.
Thanks again for your help StackOverflow members! :D
Edit:
Some people have said that the text is changing already. It's not... I want the LABEL text to change. The "File Input" tag has two parts to it. The button, and the text next to the button. I've hidden the input tag using the following SASS code. This way only the "Upload Picture..." label text is displayed. Please make sure to add this SASS code to your file so you can see that the LABEL text does not change.
.inputfile
width: 0.1px
height: 0.1px
opacity: 0
overflow: hidden
position: absolute
z-index: -1
You can use the javascript onchange event to detect when the value of the #profilepic input changes.
When it does, you can capture the new value of the #profilepic input and replace the text of the label with that value.
Example:
var profilePic = document.getElementById('profilepic'); /* finds the input */
function changeLabelText() {
var profilePicValue = profilePic.value; /* gets the filepath and filename from the input */
var fileNameStart = profilePicValue.lastIndexOf('\\'); /* finds the end of the filepath */
profilePicValue = profilePicValue.substr(fileNameStart + 1); /* isolates the filename */
var profilePicLabelText = document.querySelector('label[for="profilepic"]').childNodes[2]; /* finds the label text */
if (profilePicValue !== '') {
profilePicLabelText.textContent = profilePicValue; /* changes the label text */
}
}
profilePic.addEventListener('change',changeLabelText,false); /* runs the function whenever the filename in the input is changed */
<div class="changepic-wrap">
<form action="changepicauth.php" method="post">
<input type="file" name="profilepic" id="profilepic" class="inputfile">
<br>
<label for="profilepic">
<img src="/images/profile/upload.png" />
Upload Picture...
</label>
<br>
<div class="button-wrap">
<button>Change Picture</button>
</div>
</form>
</div>
You can use change event, select element having for attribute value equal to event.target: #profilepic element id, set the .innerHTML of selected element to event.target.files[0] .name
document.getElementById("profilepic")
.addEventListener("change", function(e) {
document.querySelector("[for=" + e.target.id + "]")
.innerHTML = e.target.files[0].name;
})
.inputfile {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
<!-- Change Picture Form -->
<div class="changepic-wrap">
<form action="changepicauth.php" method="post">
<input type="file" name="profilepic" id="profilepic" class="inputfile">
<br>
<label for="profilepic">
<img src="/images/profile/upload.png" />Upload Picture...
</label>
<br>
<div class="button-wrap">
<button>Change Picture</button>
</div>
</form>
</div>
I have a form and need to append a field as many times as required. If the button CLICK TO ADD ANOTHER FIELD is clicked the div should be appended. After the first append (onload), the div responses correctly but from the second one on, I am not getting the similar response from the div. Here is my JSFiddle
If I click on the TEST BUTTON , I get alert for the first div but on adding another div (by clicking the CLICK TO ADD ANOTHER FIELD button) , the button (TEST) doesn't work anymore for the second div onwards.
I tried clone() to help this but unable solve this one. May be I am not using it correctly.
To replicate the issue please follow the steps::
Click on the CLICK TO ADD ANOTHER FIELD button to add div
Click on the TEST button on the second div onwards
Please take a look and suggest. Thanks in advance.
You have to use delegation like $(document).on('click','.test',function(){
var count = 1;
$.fn.addclients = function(add){
var mydiv = '';
mydiv = '<div class="dataadd"><fieldset><legend>Test: '+add+'</legend><b>Test Name :</b> <input type="text" id="ct'+add+'" name="cname" value="" style="width:250px" />'+
' <button class="test" id="test" style="float:left;">TEST</button>'+
'<br>'+
'</fieldset></div>';
//$(".dataadd").clone().appendTo('#registerForm');
$('#registerForm').append(mydiv);
}
$.fn.addclients(count);
$(document).on('click','#btn',function(){
++count;
$.fn.addclients(count);
return false;
});
$(document).on('click','.test',function(){
alert("test");
return false;
});
.zend_form{
font-weight:bold;
font-size:10px;
width:358px;
float: left;
}
.dataadd{
font-weight:bold;
font-size:10px;
width:358px;
//border: 1px solid;
margin-top: 15px;
margin-bottom: 15px;
//padding: 5px;
//float:left;
}
.selectbox{
margin-top: 15px;
width:155px;
height:100px;
}
.buttonc{
background-color: #fff;
width:145px;
height:45px;
}
.selection_area{
font-weight:bold;
font-size:10px;
}
input {
width: 200px;
}
dt {
width:50%; /* adjust the width; make sure the total of both is 100% */
}
dd {
width:80%; /* adjust the width; make sure the total of both is 100% */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="registerForm" enctype="application/x-www-form-urlencoded" method="post" action=""><dl class="zend_form">
<dt id="firstname-label"><label for="firstname" class="required">First Name:</label></dt>
<dd id="firstname-element">
<input type="text" name="firstname" id="firstname" value="" style="width:200px; float:left;" /></dd>
<dt id="middlename-label"><label for="middlename" class="optional">Last Name</label></dt>
<dd id="middlename-element">
<input type="text" name="middlename" id="middlename" value="" style="width:200px" /></dd>
</form>
<div style='display:table;background-color:#ccc;width:99%;padding:5px;'>
<button class='buttonc' name='btn_sub' id='btn' style='float:left;'>CLICK TO ADD ANOTHER FIELD</button>
</div>
You write:
$('#btn').click(function(){ ... });
but this will only bind the event handler to elements currently on the page when running this code. So elements added later will not be covered by this code.
But first tip: do not use a HTML ID (#btn) if you want to repeat it. So instead use a class (.btn), to capture all elements.
And then the best way is to write something like:
$(document).on('click', '.btn', function() { ... } )
This will capture any click event on the document (you could use a container div instead --just easier to show now), and only run the callback if it matches the given selector (.btn).
all elements created after body load must use delegation to work
$("body").on("click",".test",function(){
alert("test");
return false;
});
This way, the event is attached to the body, witch always exists, but only triggers when the matched elements appear, no matter when they're created (before or after js is loaded)
Does anyone knows a javascript only way to open the browser-standard colorpicker, without using a html field? so i want a javascript what does exactly the same a a click on the html input color field.
Bart
You are going to have to use the input field, you can just hide it off the page. Issue here is the fact that the color dialog requires a click in browsers in order to open up the color dialog. It will not work if you just call click()
document.getElementById("xxx").addEventListener("click", function() {
document.getElementById("c").focus();
document.getElementById("c").value = "#FFCC00";
document.getElementById("c").click();
});
.hidden {
position: absolute;
left: -10000px;
top: auto;
width: 1px;
height: 1px;
overflow: hidden;
}
<input type="color" id="c" tabindex=-1 class="hidden">
<input type="button" id="xxx" value="Click Me!">
Here's a good old "hover-hack" solution that works even in MS Edge:
<input type="color" style='opacity:0;width:100px;position:absolute;'/>
<button>clickme</button>
then bind onchange to the colro element
https://jsfiddle.net/Lnzm0sry/2/
I have absolutely positioned an input inside a div element, but the input is unresponsive :
<div style="position: absolute; z-index: 2; height: 48px;">
<input id="myinput">
</div>
To test I tried:
$("#myinput").click(function(){
$(this).focus().select();
});
This gives the input focus, but the value still won't change!
If you are not getting any js errors and all the files are loaded, try this:
$("#myinput").on('click', function () {
// if you are clicking on it, you do not need to focus()
$(this).select();
})
here you go:
http://jsfiddle.net/FY2CF/
<div style="position: absolute; z-index: 2; height: 48px;">
<input id="myinput" type="text" />
</div>
$("#myinput").click(function(e){
this.select();
});