Home > Net >  How to bind URL to the HTML hidden button which is dynamically shown by Javascript program
How to bind URL to the HTML hidden button which is dynamically shown by Javascript program

Time:07-02

i am working in a simple webpage that requires to download the result as image file in the last step.. So, basically i have done is-

firstly i have created a hidden HTML button for downloading result image and set its display to None by CSS.. Now i have changed it's visibility from None to block using a simple Javascript program...

My program looks, something like this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<style>
    #down_button
    {
        display: none;
    }
</style>
</head>
 <body>
  <h1>Press the button to start downloading</h1>
   <input type="button" id="down_button" value="Download noww !" >
    <script src="testing.js"></script>
  </body>
</html>

and my JS file looks like this:

const btn = document.getElementById('down_button');

down_button.style.display='block'; //displays the button

but my question is- Is it possible to bind a URL with the button such that whenever a user press the button; the downloading will start in to the browser.. Please explain with plain or simple JS without any framework or library.. thanks :)

CodePudding user response:

Try this if you need to download the image on button click, but be aware, Chrome 65 and above only supports same-origin download links if you use download attribute.

const link = document.createElement("a");
link.href = "image.jpg";
link.download = "download.jpg";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

CodePudding user response:

Use the HTML onClick attribute to specify the JavaScript function to run when the button is clicked. In the JS function, redirect your user to the download link. Here's how to redirect with JS.

//button HTML
<input type="button" id="down_button" value="Download noww !" onClick="download()">

//JS function
function download(){
   window.location.replace("http://stackoverflow.com");
}

Please read through those resources so you can develop an understanding of both binding functionality to a button and redirecting the browser's address.

  • Related