Skip to content

Instantly share code, notes, and snippets.

@elipettingale
Created January 6, 2022 07:06
Show Gist options
  • Select an option

  • Save elipettingale/ce9174914e579af334cf61524e060198 to your computer and use it in GitHub Desktop.

Select an option

Save elipettingale/ce9174914e579af334cf61524e060198 to your computer and use it in GitHub Desktop.
Image file upload preview
export default class ImageUpload {
constructor(root) {
this.root = root;
this.input = root.querySelector('input');
this.preview = root.querySelector('img');
this.input.addEventListener('change', (event) => this.onChange(event));
}
onChange(event) {
let file = event.target.files[0];
if (!file) {
return;
}
let reader = new FileReader();
reader.readAsDataURL(file);
reader.addEventListener('load', () => this.updatePreview(reader.result));
}
updatePreview(url) {
this.preview.style.backgroundImage = `url('${url}')`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment