<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
meta
charset
=
"UTF-8"
/>
<
meta
name
=
"viewport"
content
=
"width=device-width, initial-scale=1.0"
/>
<
title
>Download Button with Timer</
title
>
<
style
>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
font-family: sans-serif;
}
h1 {
color: #308d46;
}
#downloadButton {
padding: 10px 20px;
font-size: 16px;
background-color: #007bff;
color: #fff;
border: none;
cursor: pointer;
}
#countdown {
display: none;
font-size: 24px;
margin-top: 20px;
}
</
style
>
</
head
>
<
body
>
<
h1
>GeeksForGeeks</
h1
>
<
h4
>
This is a download button
with a timer attached
</
h4
>
<
button
id
=
"downloadButton"
>
Download
</
button
>
<
div
id
=
"countdown"
></
div
>
<
script
>
const downloadButton = document.getElementById("downloadButton");
const countdown = document.getElementById("countdown");
const downloadLink = "download_content/sample_text_file.txt";
let timer;
let countdownValue = 5;
downloadButton.addEventListener("click", function () {
countdown.style.display = "block";
timer = setInterval(function () {
if (countdownValue <= 0) {
clearInterval(timer);
countdown.innerHTML = "Downloading...";
setTimeout(function () {
const a = document.createElement("a");
a.style.display = "none";
a.href = downloadLink;
a.setAttribute("download", "");
document.body.appendChild(a);
a.click();
}, 1000);
} else {
countdown.innerHTML =
`Starting download in ${countdownValue} seconds...`;
}
countdownValue--;
}, 1000);
});
</
script
>
</
body
>
</
html
>