Saving an image source to your local disk: A step-by-step guide

I have included an image code in my HTML file:

<span style="display:inline">
        <img NAME="anImage" height="250" src="https://chart.googleapis.com/chart?" alt="">
       </span>

Now, I would like to enhance this by adding a button. When the button is clicked, I want a system "save as" dialog to pop up so that users can save the image to their local disk.

<input id="saveImage" type="button" value="Save Image"></input>
   <script type="text/javascript">
    .............
   </script>

Any ideas on how to achieve this functionality?

Answer №1

To achieve the default browser behavior for an image, you can simply trigger the context menu event of the image by following these steps:

Firstly, assign an id to your image for this method to work with pure JavaScript!

var ev
  , image = document.getElementById('your-image-id')
  , button = document.getElementById('saveImage');

button.onclick = function () {
  if (document.createEvent) { // Check if it's not an Internet Explorer browser
    ev = document.createEvent('HTMLEvents');
    ev.initEvent('contextmenu', true, false);
    image.dispatchEvent(ev);
  } else {
    image.fireEvent('oncontextmenu');
  }
};

Answer №2

By using this snippet of code, the user is able to trigger a download of the file example.jpg by clicking on the button with the id saveImage.

$('#saveImage').click(function() {

window.location.assign('http://localhost/example.jpg');

});

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

What is the process for writing <p></p> and showcasing it on your website?

Is there a way to display the code <p></p> as text on an HTML page without it being processed as HTML, resulting in an empty paragraph? ...

I'm looking to extract various data from a SQLite table using the URL with ExpressJS. What's the best way to achieve

I need to access data from a SQLite database table that contains information on accounts, movies, and reviews. Specifically, the structure of the reviews-table is as follows: CREATE TABLE IF NOT EXISTS reviews ( id INTEGER PRIMARY KEY, authorId INT ...

Convert the dynamic table and save it as a JSON file

Looking for the most effective method to save dynamic table data into JSON format. I have two tables that need to be saved into a single JSON file. While I can easily access and console log the regular table data, I'm having trouble retrieving the td ...

Tips for implementing custom styles on React components that have been imported locally

I'm currently struggling with applying CSS successfully to components imported from an npm library. My main challenge seems to be my use of css-loader in the react starter kit (https://github.com/kriasoft/react-starter-kit) without a full understandin ...

What is the best way to include query parameters in a redirect using the res.redirect function in node.js/express.js?

Trying to navigate users to a Google Authorization page within my application poses a challenge. In this scenario, utilizing any Google API modules is not an option. To achieve the redirection, I am aware that I can structure my res.redirect() function in ...

Is there a way to integrate Prettify with Blogger/BlogSpot?

I am currently utilizing blogger.com as a platform to showcase programming texts and I am interested in incorporating Prettify (similar to Stack Overflow) to enhance the appearance of my code samples. What is the best method for installing the Prettify sc ...

Upon upgrading to webpack 5.x, I encountered the error message `Error: getaddrinfo ENOTFOUND localhost:8081` when trying to run `npm run serve`. What could be causing

Recently, I was tasked with upgrading a Vue project from webpack 4.x to webpack 5.x. Prior to the upgrade, my vue.config.js file looked like this: devServer: { port: 8081, public: process.env.PUBLIC_ADDRESS, }, The variable PUBLIC_ADDRESS was defined ...

A guide on managing file uploads in Next.js with the help of Formidable

I'm currently working on a project with Next.js and I'm trying to implement file uploads. I am using the formidable library to handle file uploads on the server side, but I'm facing some issues. Whenever I try to upload a file, I receive a ...

Exploring TingoDB: Trouble encountered when passing global variable to insert operation

During my testing and benchmarking of several embedded databases using node.js, I have encountered an interesting issue with TingoDB. Does anyone have insight into why the following code snippet works as expected: var test = { hello:'world' }; f ...

Ways to change the visibility of a view depending on a state in vuex?

If I have a button <Button> Log me in! </Button>, and I want to dynamically change its style based on the state of my Vuex app (state.user is not null). How should I properly implement this functionality? I'm considering creating a field ...

Pattern for handling errors in an efficient and streamlined manner

Currently, I am exploring the use of Express for developing a basic JSON API. However, I have concerns about how to effectively manage input parameter validation and error handling in my project. Errors can occur during both the validation process and when ...

When utilizing array.push() with ng-repeat, it appears that separate scopes are not generated for each item

I'm currently working on an Angular View that includes the following code snippet: <div ng-repeat="item in items track by $index"> <input ng-model="item.name"/> </div> Within the controller, I utilize a service to retrieve a Js ...

Is a table cell's border considered as part of its content?

A discrepancy is observed in the rendering of a document on Firefox and Chrome browsers: <!DOCTYPE html> <html> <head> <title>Testing table rendering</title> <style> table { ...

Guidance on loading JSON array information into highcharts using AngularJS

I am working on a project in Play Framework (play-java) where I need to display a bar graph using Highcharts. The Java API returns data in JSON format with a field called 'name' containing values like 'Data', 'Gadgets', ' ...

What is the output of the createRange() function?

I am encountering an issue with my code that is causing the highlighted text to always appear at the end of the page when it pops up. Is there a way to make it show in the middle of the line or below the selected text instead? I have included the current ...

Transferring information about service events to a controller in Angular

I am facing an issue with some audio elements in my service that listen for the "ended" event. I am looking for a way to pass this message to an angular controller. Currently, my service code looks like this: Audio.addEventListener "ended", (-> ...

svg viewbox cannot be adjusted in size

Struggling with resizing an SVG to 20px by 20px. The original code size of the SVG is quite large at 0 0 35.41 35.61: <!doctype html> <html> <head> <meta charset="utf-8"> <title>SVG</title> ...

Retrieving the text of a selected option by its value

I need to create a menu that returns text based on a given value. For example, if the value is 0, I want it to return “zero”, and if it's 1, then “one”, and so on. I don't need to know which option is selected or auto-select anything, I j ...

Cannot seem to get my AJAX code working correctly to show comments

Having some trouble with my comment system code. The PHP part is working fine, comments are being inserted into the table without any issues. However, I am struggling with the Ajax part. The comments are not being displayed unless the page is reloaded. C ...

How can I export an array in Ajax/PHP to the user as a .txt file?

Currently, I am working on a PHP file named "php-1" that is responsible for generating an HTML page. This particular file requests input from the user and once the user clicks on a button labelled "getIDs" (it's worth noting that there are multiple b ...