$(document).ready(function() { $('#downloadBtn').on('click', function(e) { // Prevent default if you want to perform logic first var fileUrl = "https://example.com"; // Dynamically update the anchor tag attributes $('#myAnchor').attr({ 'href': fileUrl, 'download': 'Monthly_Report.pdf' }); }); }); Use code with caution. 3. Programmatic Downloads (Dynamic Anchor Creation)
function downloadFile(url, fileName) { // 1. Create a temporary anchor element var $tempAnchor = $(' '); // 2. Set the necessary attributes $tempAnchor.attr('href', url); $tempAnchor.attr('download', fileName); // 3. Append to body (required for some browsers), trigger click, and remove $('body').append($tempAnchor); $tempAnchor[0].click(); // Note: use [0] to get the native DOM element $tempAnchor.remove(); } Use code with caution. 4. Downloading Generated Data (Blobs) download file using anchor tag jquery
If you are generating data on the client side (like a CSV from a table), you can use Blob objects and URL.createObjectURL() . javascript $(document)
In modern web development, adding the download attribute to an tag tells the browser to treat the linked resource as a download. Download Create a temporary anchor element var $tempAnchor =