Created
May 12, 2022 13:33
-
-
Save adactio/0e406cbc2ff0d3eed7a0ffcd0d932aab to your computer and use it in GitHub Desktop.
Show inline previews of images that are going to be uploaded.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Licensed under a CC0 1.0 Universal (CC0 1.0) Public Domain Dedication | |
// http://creativecommons.org/publicdomain/zero/1.0/ | |
(function (win,doc) { | |
'use strict'; | |
if (!win.FileReader || !win.addEventListener || !doc.querySelectorAll) { | |
// doesn't cut the mustard. | |
return; | |
} | |
doc.querySelectorAll('input[type="file"][accept="image/*"]').forEach( function (fileInput) { | |
fileInput.addEventListener('change', function () { | |
var files = fileInput.files; | |
if (files) { | |
files.forEach( function (file) { | |
var fileReader = new FileReader(); | |
fileReader.readAsDataURL(file); | |
fileReader.addEventListener('load', function () { | |
fileInput.insertAdjacentHTML( | |
'afterend', | |
'<img src="' + this.result + '">' | |
); | |
}); | |
} | |
} | |
}); | |
} | |
}(this, this.document)); |
Closing parenthesis are missing on lines 23 and 26 :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Blog post: Image previews with the FileReader API.
You should be able to drop this script into any page that has:
<input type="file" accept="image/*">