Let users download files without JS - The download attribute

We often need to prompt our users to download stuffs to their local storage. It can be some documents or even products.

You may think, it requires some Javascript code, But there is an easier way which requires one line of HTML! NO JAVASCRIPT AT ALL!


💯 The HTML5 download attribute

In HTML5, several new attributes are introduced. You may still don't know about the download attribute




In anchor links or the
<a></a> 
tag, you can add the download attribute, which will download the file in given url instead of opening it. For example -

<a 
 href="https://i.giphy.com/media/fuJPZBIIqzbt1kAYVc/giphy.webp"
 download>
Download this GIF
</a>

Download this GIF


😀 As simple as that

We can further add a value to the attribute. This will specify the downloaded file name. So this becomes -

<a 
href="https://i.giphy.com/media/fuJPZBIIqzbt1kAYVc/giphy.webp" 
download="customName.webp">
Download this GIF
</a>
Download this GIF with Name

Alert ⚠️!

The above buttons didn't work? 

Oh well, it Won't if you use Chrome or Firefox.

This is because, download attribute only works for same-origin content in Chrome and Firefox browsers. The GIPHY image is not such a content. So, you can actually mark this as a CON of download attribute. 

The End ✅

Now, you know allowing users to download files from your website is way more easier that what you thought.





👇 Let me know in the comments if you have any question. Suggest me new topics to write about!




Comments