So I was working with this line of code to convert an input image into an URL, however, the return doesn't seem to be working as I can't access the constant anywhere else in the document where I actually need it.
window.addEventListener('load', function() {
document.querySelector('input[type="file"]').addEventListener('change', function() {
if (this.files && this.files[0]) {
const imageURL = URL.createObjectURL(this.files[0]);
return imageURL;
}
});
});
I'm still new to JavaScript so for the life of me I can't find why it doesn't work, thanks in advance!
That's because constant imageURL is scoped in if block, if you want it to be accessed in whole file declare it outside addEventListener() function. For e.g.
let imageURL;
window.addEventListener('load', function() {
document.querySelector('input[type="file"]').addEventListener('change', function() {
if (this.files && this.files[0]) {
imageURL = URL.createObjectURL(this.files[0]);
}
});
});
console.log(imageURL)