I want to write a simple html page where there is an img tag and an input tag.
I am trying to write the javascript that will read the users image file selection and change or add the 'src' in the img tag to show the users image without uploading it to a server.
This isn't working and I cannot figure it out:
<input type="file" id="file">
<img id="user_img" src="user_img">
<script type="text\javascript" >
const user_img = document.querySelector('#img')
document.querySelector('#file').addEventListener('input', event => {
if (event.target.files.length === 0) {
console.error('No file provided')
return
}
const reader = new FileReader()
reader.addEventListener('loadend', () => {
user_img.src = reader.result
})
reader.readAsDataURL(event.target.files[0])
})
</script>