How to change img src and change image color on file input change with JavaScript?

Estimated read time 2 min read

You can change the src attribute and color of an image dynamically based on a file input change event using JavaScript. Here’s an example:

<img id="myImage" src="" width="300" height="200">

<input type="file" id="fileInput">

  var img = document.getElementById("myImage");
  var fileInput = document.getElementById("fileInput");

  fileInput.addEventListener("change", function() {
    var file = fileInput.files[0];
    var reader = new FileReader();

    reader.addEventListener("load", function() {
      img.src = reader.result; = "grayscale(100%)";

    if (file) {

In this example, we have an image element with an empty src attribute and a file input element. We use the FileReader API to read the contents of the selected file and set the result as the src of the image.

We also use the style.filter property to change the color of the image to grayscale by setting it to “grayscale(100%)”.

Finally, we add a change event listener to the file input that triggers when a file is selected. The event listener sets the src of the image to the contents of the file and changes the color using the style.filter property.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply