how to trigger a file download in javascript?

Today, We want to share with you download file on button click in javascript.In this post we will show you javascript downloads file automatically, hear for how to downloads image on button click using javascript we will give you demo and example for implement.In this post, we will learn about How to Open URL in New Tab using JavaScript with an example.

download file on button click in javascript (Open New Tab)

Using HTML Code

<button type="submit" onclick="window.open('your_file_name.doc')">Download!</button>

HTML5 downloads attribute.

<a href="Your_full_path_to_file" download="proposed_file_name">Free Download</a>

Using jQuery:

$("#download-btn").click(function() {
    window.location = 'your_file_name.doc';
});

onclick downloads file in html

<!-- Add icon library -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

  
<!--onclick download file in html Auto width -->
<button class="btn"><i class="fa fa-download"></i>Free Download</button>

  
<!--onclick download file in html Full width -->
<button class="btn" 
  style="width:100%"><i class="fa fa-download"></i>Full Download</button> 

Trigger a file download when clicking an HTML button or JavaScript

Read Also:  Delete Table Rows Using PHP JQuery Ajax

<form method="get" action="pakainfo.doc">
   <button type="submit">Free Download!</button>
</form>

How to trigger a file download when clicking an HTML button or JavaScript?

<!DOCTYPE html> 
<html> 
<body> 
	<style> 
		p { 
		color: red; 
		} 
	</style> 
	<p> 
		downloads file on button click in javascript - free Downloads Full Source code Using Jquery, JavaScript and PHP Laravel with MySQLI
	<p> 
		<textarea id="text"> 
			Welcome to Pakainfo.com 
		</textarea> 
		<br/> 
		<input type="button" id="btn"
				value="Download" /> 
		<script> 
			function download(file, text) { 
			
				var btndwl = document.createElement('a'); 
				btndwl.setAttribute('href', 
				'data:text/plain;charset=utf-8, ' 
				+ encodeURIComponent(text)); 
				btndwl.setAttribute('download', file); 
			
			
				document.body.appendChild(btndwl); 
			
				btndwl.click(); 
			
				document.body.removeChild(btndwl); 
			} 
			 
			document.getElementById("btn") 
				var text = document.getElementById("text").value; 
				var filename = "pakainfo.txt"; 
			
				download(filename, text); 
			}, false); 
		</script> 
</body> 
</html> 

I hope you get an idea about downloads file on button click in javascript.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.