Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to change img src and change image color on file input change with JavaScript.

In this article, we’ll look at how to change img src and change image color on file input change with JavaScript.

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

To change img src and change image color on file input change with JavaScript, we can listen to the change event.

For instance, we write

const fileToRead = document.getElementById("yourFile");

fileToRead.addEventListener(
  "change",
  (event) => {
    const [file] = fileToRead.files;
    if (fileToRead.files.length) {
      console.log("Filename: ", file.name);
      console.log("Type: ", file.type);
      console.log("Size: ", file.size);
    }
  },
  false
);

to select the file input with getElementById.

Then we call addEventListener to listen for the change event on the fileToRead input.

In the event handler, we get the file from the files property.

And we get the file name, type and size from the selected file.

Conclusion

To change img src and change image color on file input change with JavaScript, we can listen to the change event.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *