Skip to content

Instantly share code, notes, and snippets.

@LauraBeatris
Created April 11, 2020 11:33
Show Gist options
  • Save LauraBeatris/57a551bbc649cacaedbe5c703464f7bf to your computer and use it in GitHub Desktop.
Save LauraBeatris/57a551bbc649cacaedbe5c703464f7bf to your computer and use it in GitHub Desktop.
JS module for a photo manager
const PhotoUpload = {
input: null,
files: [],
uploadLimit: 6,
hasLimit(event){
const { files: FileList } = event.target
if ((FileList.length > PhotoUpload.uploadLimit) || ((FileList.length + PhotoUpload.files.length) > PhotoUpload.uploadLimit)) {
event.preventDefault()
alert(`Você só pode realizar o upload de até ${PhotoUpload.uploadLimit} fotos`)
return true
}
return false
},
handleFileInput(event){
PhotoUpload.input = event.target
const { files: FileList } = PhotoUpload.input
if (PhotoUpload.hasLimit(event)) return true
if (PhotoUpload.files.length === 0) {
PhotoUpload.addLabel("Fotos do seu anúncio")
}
Array.from(FileList).forEach(file => {
const reader = new FileReader()
PhotoUpload.files.push(file)
reader.onload = () => {
const image = new Image()
image.src = reader.result
const photoContainer = PhotoUpload.getContainer()
const previewContainer = PhotoUpload.getPreviewContainer()
photoContainer.appendChild(image)
previewContainer.appendChild(photoContainer)
}
reader.readAsDataURL(file)
})
event.target.files = PhotoUpload.getAllFiles()
console.log(event.target.files.length)
},
getContainer(){
const container = document.createElement('div')
container.appendChild(PhotoUpload.getRemoveButton())
container.classList.add('photo')
return container;
},
getPreviewContainer(){
const preview = document.querySelector('.js-photos-preview')
return preview
},
getRemoveButton(){
const button = document.createElement('i')
button.classList.add('material-icons')
button.classList.add('remove-button')
button.innerHTML = 'clear'
button.onclick = PhotoUpload.removePhoto
return button;
},
getAllFiles() {
const dataTransfer = new ClipboardEvent("").clipboardData || new DataTransfer()
PhotoUpload.files.forEach(file => dataTransfer.items.add(file))
return dataTransfer.files
},
removePhoto(event){
const previewPhotos = Array.from(PhotoUpload.getPreviewContainer().children)
const photoContainer = event.target.parentNode
const photoIndex = previewPhotos.indexOf(photoContainer)
PhotoUpload.files.splice(photoIndex, 1)
PhotoUpload.input.files = PhotoUpload.getAllFiles()
photoContainer.remove()
},
addLabel(labelText){
const previewWrapper = document.querySelector('.js-photos-preview-wrapper')
const label = document.createElement('label')
label.innerHTML = labelText
previewWrapper.appendChild(label)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment