Implementing the linking of a URL to an HTML hidden button that is dynamically displayed through a Javascript program

I'm currently developing a basic webpage that has a feature allowing users to download the final result as an image file in the last step.

To achieve this, I've added a hidden HTML button for downloading the result image and used CSS to set its display property to None. Then, with a simple JavaScript program, I changed the visibility of the button from None to block.

Here is what my code looks like:

<!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>

My JavaScript file contains the following code:

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

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

Additionally, I am looking for a way to link a URL to the button so that when a user clicks on it, the download will automatically start in their browser. Can this be done using vanilla JS?

Please provide an explanation with pure JavaScript.

Answer №1

If you are looking to download an image upon button click, here is a solution for you. Please note that Chrome 65 and newer versions only support same-origin download links if the download attribute is used.

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

Answer №2

To make a button trigger a JavaScript function when clicked, use the HTML onClick attribute. This function can be used to redirect users to a download link. Learn more about how to redirect using JavaScript here.

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

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

Check out these resources to understand how to attach functionality to a button and change the browser's address through redirection.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to center an image without relying on margin or padding to achieve alignment

Is it possible to center all tags except for the img without using margins or paddings? header { display: flex; flex-direction: column; align-items: center; } .logo { border-radius: 50%; width: 100px; height: 100px; margin: 10px 0 0 10px; ...

Finding all elements with a specified attribute in jQuery: A comprehensive guide

While looking for an example, I came across one that searches only inputs instead of all elements: https://api.jquery.com/attribute-equals-selector/ Is there a way to modify this example so that it can search all elements in the DOM, and not just inputs ...

Having trouble with your HTML iFrame not functioning properly?

My code is not working as expected and I'm puzzled by it. It was working fine yesterday but now it's giving me trouble. <iframe allowfullscreen="" allowtransparency="true" frameborder="0" height="2000" scrolling="no" src="http://www.google.co ...

Update the background image every minute with a smooth transition effect

I am currently in the process of developing a personal dashboard that requires dynamic background images to change every minute. To achieve this functionality, I have integrated the [Pixabay API][1] and formulated the following API request: https://pixaba ...

Tips for initializing a jstree with no content?

When I click a button, I send a key to the controller and retrieve my lists using JSON. The array inside my lists serves as my children in my jstree. $("#btnSearch").on("click", function () { alert("I'm also here"); $.ajax({ ...

Safari's Failure to Execute Ajax Requests

My HTML page includes an ajax request that is functioning properly on Firefox, but does not work on Safari. While debugging, I noticed that the readystate is undefined and the status is "". Can anyone suggest why it might not be working on Safari? Javascr ...

Protractor Cucumber: Issue with locating spec file patterns (identifying 2 features)

I am facing an issue with running 2 different cucumber features. After adding the following lines to my protractor.conf.js file: specs: ['add.feature', 'delete.feature'] I encountered a problem when running the tests stating pattern ...

The error message encountered with React Easy DatePicker is: "Uncaught ReferenceError: process is not defined."

I am attempting to integrate the stylish DatePicker from https://www.npmjs.com/package/sassy-datepicker?activeTab=readme Here is my implementation : import DatePicker from "sassy-datepicker"; function App() { const [date, setDate] = useSta ...

The function that can be used in Ajax for setting

I'm currently utilizing Ajax to automatically submit a form when a key is pressed. After the form is submitted, the page displays the resulting information success: function (response){ $("#search_results<?php echo $HoursID ?>").html(response) ...

Exploring the features of Vue.js with the code snippet 'ts 1109'

I need some assistance with my code as I seem to have one incorrect answer when using the if statement. The error code that I am encountering is ts1109 and I am not sure why VS Code is showing this. Thank you in advance for any help provided :) var calcu ...

An Ajax call nested within another Ajax call

I've implemented an AJAX request to load my "home" page and "about" page into a designated "container" when a menu link button is clicked on my index.php. Now, I have three links on my "home" page and I want each of these links to open within the same ...

Why is the time input field in AngularJS programmed to expect a date instead?

When booking, I stored the time using $filter('date')($scope.booktime, 'mediumTime'). After booking, I have an editbooking function where I pass the time and encounter an error in the console: Error: [ngModel:datefmt] Expected 11:59:00 ...

Setting up various connections is made possible through Node.js Socket.io

In the process of developing a straightforward chat application using socket.io and incorporating passport.js for user authentication, an issue arises when users log out and then back in. The previous socket connection remains active, resulting in two conn ...

No files located by the server

My experience with writing a basic express script to serve a webpage with embedded Javascript has been quite frustrating. The server seems to struggle finding the files I provide, and what's even more aggravating is that it sometimes works but then su ...

How can I clear the div styling once the onDismiss handler has been triggered

Seeking assistance with resetting a div on a Modal after it has been closed. The issue I am facing with my pop-up is that the div retains the previous styling of display: none instead of reverting to display: flex. I have searched for a solution without su ...

Tips for automatically refreshing a Next.js application following an update in an external library

I have a monorepo containing two applications: The first is a Next.js web app The second is a UI library using Tailwind CSS and Microbundle Currently, the only way I can get the web app to recognize changes made in the UI library is by following these st ...

Adding a CSS class to an HTML element using JQuery

I have a collection of tabs, and I want to dynamically add an <hr> element with the class "break-sec" when a certain class is active. This element should be placed within a <span> element with the class "vc_tta-title-text" after the text. Here ...

Presenting XML data on a webpage using AJAX technology

I am currently working on setting up a web radio station with a program that allows streaming (jazler) to send xml files via ftp to a web server to automatically update information such as the current song playing and previous songs. The code for NowOnAir ...

Using jQuery to Toggle Visibility of Table Rows

I'm facing a challenge in creating a basic table layout where all the table rows are initially hidden when the document loads. The goal is to display specific rows when a corresponding button is clicked, but my current implementation doesn't seem ...

Why am I seeing numbers in the output when I log the data from the res.write(data) function in Node.js?

While working with Node.js on my Raspberry Pi, I encountered an issue where reading a local file 'test.html' resulted in hex output instead of the expected HTML format. Can someone explain why this might be happening? Additionally, I am aware tha ...