Reputation: 102
i created a copy for a section of my HTML code now what I want is to give download button to download same piece of code in HTML form which copy button I coping but I have no idea and idea and suggestion will be helpful because I still learning js
function copyToClipboard(text) {
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
function copyEvent() {
var elem = document.getElementById("copy").innerHTML;
elem = elem.replace(/\n/g, "")
.replace(/[\t ]+\</g, "<")
.replace( /(<([hr]+)>)/ig, '')
copyToClipboard(elem);
}
const addClickHandlers = (ids) => {
ids.forEach(({ id, icon, text }) => {
const element = document.getElementById(id);
element.addEventListener("click", function handleClick() {
element.innerHTML = `<iconify-icon icon="${icon}"></iconify-icon> ${text}`;
});
});
};
addClickHandlers([
{ id: "copy_btn", icon: "akar-icons:copy", text: "Code Copied" },
{ id: "down_btn", icon: "ri:file-download-line", text: "Downloading" },
]);
<p align="right"><button type="button" class="btn btn-dark" id="down_btn"><iconify-icon icon="ri:file-download-line"></iconify-icon> Download code</button>
<button type="button" class="btn btn-dark" onclick="copyEvent();" id="copy_btn"><iconify-icon icon="akar-icons:copy"></iconify-icon> Copy Code </button></p>
<div id="copy">
<h1> hello my name is shreyash</h1>
<p> a computer sicence student<P>
</div>
Upvotes: 0
Views: 445
Reputation: 790
in your html down btn
<button type="button" class="btn btn-dark" onclick="downEvent()" id="down_btn"><iconify-icon icon="ri:file-download-line"></iconify-icon> Download code</button>
and in js
function downEvent() {
var elem = document.getElementById("copy").innerHTML;
elem = elem.replace(/\n/g, "")
.replace(/[\t ]+\</g, "<")
.replace( /(<([hr]+)>)/ig, '')
var file = new File(["\ufeff"+elem], 'readme.md', {type: "text/plain:charset=UTF-8"});
url = window.URL.createObjectURL(file);
//create a hidden link and set the href and click it
var a = document.createElement("a");
a.style = "display: none";
a.href = url;
a.download = file.name;
a.click();
window.URL.revokeObjectURL(url);
}
Upvotes: 1
Reputation: 685
You can use the following code to download a HTML file -
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
Upvotes: 0