Open In App

How to specify that the target will be downloaded by on click in HTML5 ?

Last Updated : 31 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to define that a hyperlink will lead to a download instead of navigating to it when clicked in HTML5. This can be used in cases where content is needed to be downloaded when the link is clicked, like a text file or image hosting service.

Approach:

The <a> element has an attribute download that is used to specify if the hyperlink would be used to download the linked resource, that is, the value specified with the href attribute instead of navigating to it. It has an optional value that can be used to specify the name of the file that would be downloaded. If this value is not used then the original file name would be used instead.

Syntax:

<a href="file_to_download.jpg" download="filename">

The below examples illustrate the download attribute to specify the target would be downloaded.

Example:

HTML




<html>
    
<body>
  <h1 style="color: green;">
    GeeksforGeeks
  </h1>
    
  <h3>
    How to define that a hyperlink will
    lead to a download instead of navigating
    to it when clicked in HTML5?
  </h3>
    
  <p>
    The below links demonstrate the different
    links from which the text file may be 
    viewed or downloaded.
  </p>
  
    
  <a href="example.txt">
    View Link
  </a><br>
    
  <a href="example.txt" download>
    Download Link
  </a><br>
    
  <a href="example.txt" download="geeks">
    Download Link with custom name
  </a>
  
  <p>The below links demonstrate the different
    links from which the image file may be 
    viewed or downloaded.
  </p>
  
    
  <a href="logo.png">
    View Link
  </a><br>
    
  <a href="logo.png" download>
    Download Link
  </a><br>
    
  <a href="logo.png" 
     download="gfglogo">
    Download Link with custom name
  </a>
</body>
    
</html>


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads