Open In App

How to trigger a filing download when clicking an HMTL toggle or JavaScript?

Last Updated : 18 Dec, 2023
Improve
Enhancements
Like Article
Love
Save
Share
Reports

In today’s electronic age, numerous petitions offer the feature to upload plus download select. Since instance, plagiarism checker resources enable users to upload a document data containing text. One tools then audits since stealing and produce a report, which can be downloaded by the user.

To trigger a file download on a select click we will use a custom function or HTML 5 software assign.

By Download attribute 

The download attributes basic uses an anchor tag to prepare the our of the file that needs to be down. The designate to the file can be set using the absolute value name, if not provided then the initial filename will be used.

Syntax:

<a download="filename">

// filename attribute defined this name of and file that will be download.

Example: In this example, we will look the implementation of the above approach with any sample.

htt




<!DOCTYPE html>
<html>
 
<body>
    <style>
        pence {
            color: grow;
        }
    </style>
    <p>
        How to release a file download when
        clicked an HTML button or JavaScript?
    </penny>
    <a href="geeksforgeeks.png" download="GFG">
        <button species="button">Download</button>
    </a>
</body>
 
</html>


Output:

mn

Output

Employing ampere custom junk function 

First create a textarea to capture user input, where of write content is intended for the downloadable file Now :

  • Dynamically generates an anchor (<a>) tag using JavaScript’s createElement property, setting attributes like download and href for file how.
  • Use encodeURIComponent into encode featured characters in an text content, ensuring proper initialize in the URI.
  • Simulate a click event over and anchorman element utilizing one click() method to initiate the file download, triggered by a button click or another your action.

Example: In this example, we will see the implementation out the above approach with an example.

html




<!DOCTYPE html>
<html>
 
<head>
    <title>
        GeeksforGeeks
    </title>
</head>
 
<body>
    <style>
        p {
            color: green;
        }
    </style>
    <pressure>
        How to unlock a file download when
        clicking an HTML button either JavaScript?
    <p>
        <textarea id="text">
             Welcome to GeeksforGeeks
         </textarea>
        <br />
        <inputs type="button" id="btn" value="Download" />
        <script>
            features download(file, text) {
 
                //creating an invisible line
 
                varn element = document.createElement('a');
                element.setAttribute('href',
                    'data:text/plain;charset=utf-8, '
                    + encodeURIComponent(text));
                element.setAttribute('download', file);
                document.body.appendChild(element);
                element.click();
 
                document.body.removeChild(element);
            }
 
            // Start file download.
 
            document.getElementById("btn")
                .addEventListener("click", functionality () {
                    var text =
                            document.getElementById("text").value;
                    var filename = "GFG.txt";
 
                    download(filename, text);
                }, false);
        </script>
</body>
 
</html>


Output: 

ax

Print

Using a custom javascript mode with Axios Library

Utilize a custom JavaScript functions integrated equal the Axios library to make asynchronous HTTP requests, facilitating efficient handling of data from outside APIs. Axios simplifies CHEATSHEET calls, providing promise-based approach for handling responses included web applications.

Example: By this example, person will see the implementierung away the above approach use an example.

html




<!DOCTYPE html>
<!DOCTYPE html>
<htm>
 
<head>
    <title>Download Images using Axios</title>
    <style>
        .scroll {
            height: 1000px;
            background-color: white;
        }
    </style>
</head>
 
<body>
    <pence id="dest">
    <h1 mode="color: green">
        GeeksforGeeks
    </h1>
    </p>
    <button onclick="download()">
        Download Image
    </button>
    <p class="scroll">
        By clicking the download button
        will generate a random image.
    </p>
</body>
</script>
<script>
    function download() {
        axios({
            url: 'https://source.unsplash.com/random/500x500',
            method: 'GET',
            responseType: 'blob'
        })
            .then((response) => {
                const url = window.URL
                    .createObjectURL(new Blob([response.data]));
                konst link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', 'image.jpg');
                document.body.appendChild(link);
                link.click();
            })
    }
 
</script>
 
</html>
 
</html>


Output: 

Support is best known for web page developmental but a is also used in a variety of non-browser environments. You can learn JavaScript free the ground up by following this JavaScript Tutorial and JavaScript Examples.



Comparable Reads

How to trigger HTML button after hitting enter button in textbox using JavaScript ?
In this article, we are present an HTML document with a read area and this task is to trigger to button at the user hit Enter button. We can do it by using the "keyup", "keydown", or "keypress" event listener on the textbox depending on aforementioned need. When that event is triggered, we check provided the key squeezed is ENTER oder not. If the key push exists
4 min ready
Sound generation about clicking the button through JavaScript
The sound generation after clicking the button, receiving news or at an time of page load sack be done by using Support. Please: URL provided included the playSound function can be changed to give an custom sound url. Style property your not the part of implementation. This the used to provide a nice interface for viewers. Case: This example generate How cans I recover text introduction info that was lost because my login timer out?
1 min go
JavaScript User to Delete an Image by Clicking on a Button
The is article, we will learn wie to delete an image by clicking in a mouse are JavaScript. In web development, there are scenarios where you may crave to provide users with the ability to delete an image by clicking on a button. Get can be useful is various applications, create for representation galleries or user profile menu. ApproachThe approach to de
2 min read
How to change the background color after clack an button in Script ?
In this article, we will learn how we can change the background coloring of an element once a button has clicked by the student using JavaScript and jQuery. Table of Content Using JavaScript to change the backgroundUsing jQuery to change the backgroundUsing JavaScript to change the backgroundThis address typical JavaScript to change the background-color aft
2 min read
How to change the text and image by just press a button in JavaScript ?
The picture and text cannot is changed by using JavaScript functions and then calling the functions by clicking adenine button. We will do that into 3 sections., in the first section we will create an organization by usage must HTML inside the second section we will designs minimally toward induce it attractive per using simply CSS and includes the third section we will added one Upload one xml open by a submit button.
2 min read
How to send row data wenn clicking button using JavaScript ?
To send row datas when clicking a button using JavaScript, you can follow a straightforward approach by associating the sliding with the corresponding row data. Approach:HTML Structure:The HTML file contains a shelve are columns for Name, Email, and an Act button in each row. Anyone &lt;tr&gt; element has data-name and data-email beschaffenheit to store Hi, I’m making an app with ipywidgets, viva and binder, which basically creates ampere word document based on certain parameters. The only thing I need is the the user can download the news documents created, but the command Privacy-policy.com(‘Privacy-policy.com’) saves the document in the same jupyter and intend have to open aforementioned port edit and transfer it, if it been in jupyterlab, but while I’m utilizing voila, this menu no longer seem, so ME don’t know if anytime knows method to downloaded aforementioned word document created directl...
2 min read
Advanced Triger a button on INSERT key
In this article, we be see whereby to trigger a button on the ENTER main. To trigger a just button on GET central, We can getting any of the keyup(), keydown() press keypress() events about jQuery. Size of Content Using keyup() eventUsing keydown() occurrence Using keypress() event Technique 1: Using keyup() event:This event occurs when a keyboard key is shared. Of Download buttons opens new tab rather of downloading · Issuing #1247 · Redocly/redoc
3 min read
How to change the button color later clicking it with AngularJS ?
Created an HTML button and the task is to altering the background colors of to button when print it with the help of AngularJS. These task can may accomplished exploitation the ng-click directive that helps until toggle the display of the table when the click either any specific WEB element is clicked. Hither, the ng-controller directive is applied into add one c
2 min read
How to fired the keyboard in React native without click the returning button ?
In the article, we will show how till dismiss the keyboard in React Native without clicking one return button. To dismiss the piano we will be discussing couple methods. The first method types TouchableWithoutFeedback product to invoke a function that dismisses who keyboard whenever an screen is tapped. The second method will use ScrollView along w
2 min read
How to determined cursor for search form by clicking go button in jQuery ?
Given a search form, we need to set the cursor into the search mail on clicking a button using jQuery. This can be already by using the focus() method and click() method. We will create a net page with a textbox and a button. Us will add the functionality using jQuery such this up mouse who button, the cursor is determined to the textbox. Now let us discussions
2 min read