To force the browser to download image files when clicked using JavaScript, you can create a link element (<a>
) with the image as its href
attribute and add the download
attribute to it.
To do this, we write:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Download Image on Click</title>
</head>
<body>
<!-- Image to be downloaded -->
<img id="imageToDownload" src="image.jpg" alt="Image">
<script>
// Function to download the image when clicked
function downloadImage() {
// Get the image source
var imageSrc = document.getElementById('imageToDownload').src;
// Create a link element
var downloadLink = document.createElement('a');
// Set the href attribute to the image source
downloadLink.href = imageSrc;
// Set the download attribute to force download
downloadLink.download = 'image.jpg'; // Specify the filename here
// Simulate a click on the link to trigger the download
downloadLink.click();
}
// Add click event listener to the image
document.getElementById('imageToDownload').addEventListener('click', downloadImage);
</script>
</body>
</html>
In this example, we have an <img>
element with the ID imageToDownload
that represents the image we want to download.
We define a downloadImage()
function that will be called when the image is clicked.
Inside the function, we create a new link element (<a>
) programmatically using document.createElement('a')
.
We set the href
attribute of the link to the image source and the download
attribute to specify the filename.
Finally, we simulate a click on the link element using the click()
method to trigger the download.
When the user clicks on the image, the browser will initiate a download of the image file with the specified filename.