I am new to website development and try to figure out how can I make my user automatically copy a code in to his/her mouse(clip board) when clicked on a link (using html, php or javascript). For example, I am trying to create this personal website, when a user click on a link or a button in my website, it should automatically copy that text code to the clip board. I have seen sites like retailmenot.com do this: Example:-
Please show me with an example if you can
Updated:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$("#link").click(function(){
var holdtext = $("#clipboard").innerText;
Copied = holdtext.createTextRange();
Copied.execCommand("Copy");
});
</script>
</head>
<body>
<hr>
Click here to copy the Code <button onclick="copyToClipboard()">Copy Text</button>
<hr>
</body>
</html>
Here is the function which might can help you or future referer.
function copyToClipboard(id) {
var text = $("#td_id_" + id).text(); //getting the text from that particular Row
//window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
if (window.clipboardData && window.clipboardData.setData) {
// IE specific code path to prevent textarea being shown while dialog is visible.
return clipboardData.setData("Text", text);
} else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
var textarea = document.createElement("textarea");
textarea.textContent = text;
textarea.style.position = "fixed"; // Prevent scrolling to bottom of page in MS Edge.
document.body.appendChild(textarea);
textarea.select();
try {
return document.execCommand("copy"); // Security exception may be thrown by some browsers.
} catch (ex) {
console.warn("Copy to clipboard failed.", ex);
return false;
} finally {
document.body.removeChild(textarea);
}
}
}
Unit test in all Browser not done.
try this.
$("#link").click(function(){
var holdtext = $("#clipboard").innerText;
Copied = holdtext.createTextRange();
Copied.execCommand("Copy");
});
Related
I am very new here and I have no clue how javascript works, so please excuse me in advance if I do something incorrectly.
I found this javascript code on github which I use as a Chrome bookmarklet.
It does exactly what I want which is copying the document.title.
But when pasting it, it has additional text which I would like to remove.
For example if I go to https://www.geeksforgeeks.org/ and run the bookmarklet there, the output is "GeeksforGeeks | A computer science portal for geeks"
I would like to have the "| A computer science portal for geeks" removed so it only pastes GeeksforGeeks.
javascript:(function() {
function copyToClipboard(text) {
if (window.clipboardData && window.clipboardData.setData) {
return clipboardData.setData("Text", text);
} else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
var textarea = document.createElement("textarea");
textarea.textContent = text;
textarea.style.position = "fixed";
document.body.appendChild(textarea);
textarea.select();
try {
return document.execCommand("copy");
} catch (ex) {
console.warn("Copy to clipboard failed.", ex);
return false;
} finally {
document.body.removeChild(textarea);
}
}
}
var markdown = document.title;
copyToClipboard(markdown);
})();
Can you please help me on this?
I'm trying to allow users to upload files without causing the page to change when they upload the files. To do this, I'm using an iframe, which I'm adding a form and a file input to, then submitting the form within the (hidden) iframe. This works just fine on Chrome, but not on Firefox.
Below is code which causes this problem.
<!DOCTYPE html>
<html>
<head>
<style>
#pretty-button { background: blue; }
#hidden-uploader { display: none; }
</style>
<script>
window.addEventListener('DOMContentLoaded', function() {
var btn = document.getElementById('pretty-button');
var filename_output = document.getElementById('filename');
var upload_iframe = document.getElementById('hidden-uploader');
btn.addEventListener('click', function() {
document.body.appendChild(upload_iframe);
_document = upload_iframe.contentDocument;
var form = _document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('enctype', 'multipart/form-data');
form.setAttribute('action', '.');
var file_input = _document.createElement('input');
file_input.setAttribute('type', 'file');
file_input.setAttribute('name', 'document');
form.appendChild(file_input);
_document.body.appendChild(form);
file_input.click();
file_input.addEventListener('change', function() {
console.log('file selected');
form.submit();
upload_iframe.addEventListener('load', function() {
console.log('file uploaded');
});
});
});
});
</script>
</head>
<body>
<button id="pretty-button">Choose a File</button>
<span id="filename"></span>
<iframe id="hidden-uploader"></iframe>
</body>
</html>
On firefox, this fails with NS_ERROR_UNEXPECTED: on line 33, which is form.submit(), when a file is selected.
Any idea what might be happening here?
I think I figured the problem, which is in the line
document.body.appendChild(upload_iframe);
This causes the iframe to reload itself, which means that the contentDocument of the iframe before it is re-appended to the document body is different from the contentDocument of the iframe after it is re-appended to the document body. The reloading occurs while the file dialog is open.
This can be verified by making the following changes:
<!DOCTYPE html>
<html>
<head>
<style>
#pretty-button { background: blue; }
#hidden-uploader { display: none; }
</style>
<script>
window.addEventListener('DOMContentLoaded', function() {
var btn = document.getElementById('pretty-button');
var filename_output = document.getElementById('filename');
var upload_iframe = document.getElementById('hidden-uploader');
btn.addEventListener('click', function() {
document.body.appendChild(upload_iframe);
_document = upload_iframe.contentDocument;
var form = _document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('enctype', 'multipart/form-data');
form.setAttribute('action', '.');
var file_input = _document.createElement('input');
file_input.setAttribute('type', 'file');
file_input.setAttribute('name', 'document');
form.appendChild(file_input);
_document.body.appendChild(form);
file_input.click();
// So far, the iframe hasn't reloaded.
file_input.addEventListener('change', function() {
/* Because the iframe loads in less time than it
* takes for the user to select a file, the iframe
* has now reloaded, and _document refers to the
* contentDocument of an iframe which is no longer
* attached to the page.
*/
console.log('file selected');
var _newDocument = upload_iframe.contentDocument;
console.log(_document === _newDocument); // false in Firefox, true in Chrome
form.submit();
upload_iframe.addEventListener('load', function() {
console.log('file uploaded');
});
});
});
});
</script>
</head>
<body>
<button id="pretty-button">Choose a File</button>
<span id="filename"></span>
<iframe id="hidden-uploader"></iframe>
</body>
</html>
By removing the offending line, the above starts working in Firefox.
I've been printing my page using the code below:
window.print();
An image below is what the print preview in Google chrome browser looks like. It has two main buttons: print and cancel.
I want to know if the user has clicked the print or cancel buttons. What I did uses jquery:
HTML Code of the Print Preview:
<button class="print default" i18n-content="printButton">Print</button>
<button class="cancel" i18n-content="cancel">Cancel</button>
Jquery Code:
$('button > .cancel').click(function (e) {
alert('Cancel');
});
$('button > .print').click(function (e) {
alert('Print');
});
I tried the code above with no luck. What am I missing?
You can not access Chrome's internal windows (printing dialog in this case) directly from a regular web page.
(function () {
var beforePrint = function () {
alert('Functionality to run before printing.');
};
var afterPrint = function () {
alert('Functionality to run after printing');
};
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function (mql) {
//alert($(mediaQueryList).html());
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
}());
Or, If you want to do something when the print preview gets opened, you can try below:
$(document).bind("keyup keydown", function (e) {
if (e.ctrlKey && e.keyCode == 80) {
setTimeout(function () { CallAfterWindowLoad();}, 5000);
return true;
}
});
function CallAfterWindowLoad()
{
alert("Open and call");
}
Reference:
How to capture the click event on the default print menu called by Javascript window.print()
Maybe if you provide your requirements for this two buttons click event, we can provide you an alternate solution.
it is very easily possible:
<body onafterprint="myFunction()">
The myFunction() that you can define within a tag will be fire when either the printing job is done or the cancel button was pressed.
As far as I know, the print preview is not part of any document your JS can access. These might interest you:
Detecting browser print event
ExtJS 4 - detecting if the user pressed "Print" on the print dialog that was called programatically
<script>
window.print();
onafterprint = function () {
window.location.href = "index.html";
}
</script>
This should do the trick. I've used jQuery v2.2.0 which is included in the html file.
$("#print").click(function() { // calls the id of the button that will print
document.body.style.visibility = 'hidden'; //code for hiding the body
document.getElementById('printthis').style.visibility = 'visible'; // div to be printed
document.getElementById('printthis').style.position = 'absolute'; //some code/css for positioning. you can adjust this
document.getElementById('printthis').style.top = '40px';
document.getElementById('printthis').style.left = '0px';
if (print()) { // shows print preview.
} else { // else statement will check if cancel button is clicked.
document.body.style.visibility = 'visible';
document.getElementById('printthis').style.position = '';
document.getElementById('printthis').style.top = '';
document.getElementById('printthis').style.left = '';
alert("Print Canceled");
}
});
I guess this might as well be used as a way to print certain divs in your html. Just hide the body element and only show the div that you want to print with some positioning css. Hope it works in yours. I've tried it and I can say that it worked for me.
var name = document.getElementById('name');
name.value = localStorage.name || '';
name.addEventListener('blur', function() {
if ( this.value ) localStorage.setItem('name', this.value);
});
window.addEventListener('storage', function() {
console.log('updated');
}, false);
The code above is copied directly from a Tuts+ Premium course called HTML5 Fundamentals. My problem is that the Javascript is detecting the localStorage update but is not updating the other tab. In the tutorial, it works flawlessly. I do have a suspicion that this is happening because I'm using .value and firefox has issues with that. I'm running on a Ubuntu 13.04 virtualbox using Firefox version 21.0. Thank you
It turns out that I just needed to add "name.value = localStorage.name;" within the "window.addEventListener('storage', function(e) {" and it worked. Thank you
I test this code in Firefox 22 and it works well:
My HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="text" id="input"/>
<script>
function onLoad(){
var name=document.getElementById("input");
name.value = localStorage.name || '';
name.addEventListener('blur',function(e){
if (this.value) {
localStorage.setItem('name',this.value)
};
});
window.addEventListener('storage',function(){
console.log('updated');
name.value = localStorage.name;
},false);
}
window.onload = onLoad();
</script>
</body>
</html>
And result is....
First tab:
Second one:
If you have any further question welcome to discuss.
if you want to change input value on another tab edit your storage handler:
name.value = localStorage.name;
instead of
console.log('updated');
works in Chrome 27.0 and FF 21.0 under Ubuntu 12.04
DEMO
(of course you have to open it in 2 tabs to check)
I have a page with a "Print" link that takes the user to a printer-friendly page. The client wants a print dialog box to appear automatically when the user arrives at the print-friendly page. How can I do this with javascript?
window.print();
unless you mean a custom looking popup.
You could do
<body onload="window.print()">
...
</body>
I like this, so that you can add whatever fields you want and print it that way.
function printPage() {
var w = window.open();
var headers = $("#headers").html();
var field= $("#field1").html();
var field2= $("#field2").html();
var html = "<!DOCTYPE HTML>";
html += '<html lang="en-us">';
html += '<head><style></style></head>';
html += "<body>";
//check to see if they are null so "undefined" doesnt print on the page. <br>s optional, just to give space
if(headers != null) html += headers + "<br/><br/>";
if(field != null) html += field + "<br/><br/>";
if(field2 != null) html += field2 + "<br/><br/>";
html += "</body>";
w.document.write(html);
w.window.print();
w.document.close();
};
If you just have a link without a click event handler:
Print Page
I do this to make sure they remember to print landscape, which is necessary for a lot of pages on a lot of printers.
Print Me...
or
<body onload="alert('Please be sure to set your printer to Landscape.');window.print();">
etc.
</body>
You can tie it to button or on load of the page.
window.print();
I know the answer has already been provided. But I just wanted to elaborate with regards to doing this in a Blazor app (razor)...
You will need to inject IJSRuntime, in order to perform JSInterop (running javascript functions from C#)
IN YOUR RAZOR PAGE:
#inject IJSRuntime JSRuntime
Once you have that injected, create a button with a click event that calls a C# method:
<MatFAB Icon="#MatIconNames.Print" OnClick="#(async () => await print())"></MatFAB>
(or something more simple if you don't use MatBlazor)
<button #onclick="#(async () => await print())">PRINT</button>
For the C# method:
public async Task print()
{
await JSRuntime.InvokeVoidAsync("printDocument");
}
NOW IN YOUR index.html:
<script>
function printDocument() {
window.print();
}
</script>
Something to note, the reason the onclick events are asynchronous is because IJSRuntime awaits it's calls such as InvokeVoidAsync
PS: If you wanted to message box in asp net core for instance:
await JSRuntime.InvokeAsync<string>("alert", "Hello user, this is the message box");
To have a confirm message box:
bool question = await JSRuntime.InvokeAsync<bool>("confirm", "Are you sure you want to do this?");
if(question == true)
{
//user clicked yes
}
else
{
//user clicked no
}
Hope this helps :)
<script>
const _print = () => {
window.print();
}
</script>
or
<body onload="window.print();"></body>
see the documentation here : https://developer.mozilla.org/en-US/docs/Web/API/Window/print
I know this is an old question, but after fighting with this similar issue, I figured out a way to open a print screen and NOT have to open a new tab, and not have to enable popups.
Hopefully, this helps someone else.
/*
Example:
Print
*/
//LISTEN FOR PRINT URL ITEMS TO BE CLICKED
$(document).off('click.PrintUrl').on('click.PrintUrl', '.print-url', function(e){
//PREVENT OTHER CLICK EVENTS FROM PROPAGATING
e.preventDefault();
//TRY TO ASK THE URL TO TRIGGER A PRINT DIALOGUE BOX
printUrl($(this).attr('href'));
});
//TRIGGER A PRINT DIALOGE BOX FROM A URL
function printUrl(url) {
//CREATE A HIDDEN IFRAME AND APPEND IT TO THE BODY THEN WAIT FOR IT TO LOAD
$('<iframe src="'+url+'"></iframe>').hide().appendTo('body').on('load', function(){
var oldTitle = $(document).attr('title'); //GET THE ORIGINAL DOCUMENT TITLE
var that = $(this); //STORE THIS IFRAME AS A VARIABLE
var title = $(that).contents().find('title').text(); //GET THE IFRAME TITLE
$(that).focus(); //CALL THE IFRAME INTO FOCUS (FOR OLDER BROWSERS)
//SET THE DOCUMENT TITLE FROM THE IFRAME (THIS NAMES THE DOWNLOADED FILE)
if(title && title.length) $(document).attr('title', title);
//TRIGGER THE IFRAME TO CALL THE PRINT
$(that)[0].contentWindow.print();
//LISTEN FOR THE PRINT DIALOGUE BOX TO CLOSE
$(window).off('focus.PrintUrl').on('focus.PrintUrl', function(e){
e.stopPropagation(); //PREVENT OTHER WINDOW FOCUS EVENTS FROM RUNNING
$(that).remove(); //GET RID OF THE IFRAME
if(title && title.length) $(document).attr('title', oldTitle); //RESET THE PAGE TITLE
$(window).off('focus.PrintUrl'); //STOP LISTENING FOR WINDOW FOCUS
});
});
};
if problem:
mywindow.print();
altenative using:
'<scr'+'ipt>print()</scr'+'ipt>'
Full:
$('.print-ticket').click(function(){
var body = $('body').html();
var ticket_area = '<aside class="widget tickets">' + $('.widget.tickets').html() + '</aside>';
$('body').html(ticket_area);
var print_html = '<html lang="tr">' + $('html').html() + '<scr'+'ipt>print()</scr'+'ipt>' + '</html>';
$('body').html(body);
var mywindow = window.open('', 'my div', 'height=600,width=800');
mywindow.document.write(print_html);
mywindow.document.close(); // necessary for IE >= 10'</html>'
mywindow.focus(); // necessary for IE >= 10
//mywindow.print();
mywindow.close();
return true;
});