简体   繁体   中英

How to add a textarea to the image preview when uploading

I've been struggling with this problem 3 entire days. Any help would be appreciated!

I have a button 'ADD MY PHOTO' and when clicked, it comes a popup with the option to upload a picture or more. So, when I click 'Select Files' button or I drag & drop a picture or more, it will preview the pictures on the right side.

What I need help with is: when I upload a picture or 2, I want on the right side of every picture to display a textarea where the user can write something (like a caption). Also, after the pictures and captures are displayed I need the option to remove one or all of them. Here is a picture:

在此处输入图片说明

Here is the CodePen code: https://codepen.io/anon/pen/VEQMwm

Thanks in advance for help.

Also, here is the code:

 // ---------- THIS IS FOR THE POPUP ---------- // function CustomAlert() { this.performCustomAlert = function (dialog) { var windowWidth = window.innerWidth; var windowHeight = window.innerHeight; var dialogoverlay = document.getElementById('dialogoverlay'); var dialogbox = document.getElementById('dialogbox'); dialogoverlay.style.display = "block"; dialogoverlay.style.height = windowHeight + "px"; dialogbox.style.display = "block"; } this.ok = function () { document.getElementById('dialogbox').style.display = "none"; document.getElementById('dialogoverlay').style.display = "none"; } } var newAlert = new CustomAlert(); // ------------- TABS ----------------- // function openTab(evt, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(tabName).style.display = "block"; evt.currentTarget.className += " active"; } document.getElementById("defaultOpen").click(); // ---------------- UPLOAD --------------------------// // ************************ Drag and drop ***************** // let dropArea = document.getElementById("drop-area") // Prevent default drag behaviors ;['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { dropArea.addEventListener(eventName, preventDefaults, false) document.body.addEventListener(eventName, preventDefaults, false) }) // Highlight drop area when item is dragged over it ;['dragenter', 'dragover'].forEach(eventName => { dropArea.addEventListener(eventName, highlight, false) }) ;['dragleave', 'drop'].forEach(eventName => { dropArea.addEventListener(eventName, unhighlight, false) }) // Handle dropped files dropArea.addEventListener('drop', handleDrop, false) function preventDefaults (e) { e.preventDefault() e.stopPropagation() } function highlight(e) { dropArea.classList.add('highlight') } function unhighlight(e) { dropArea.classList.remove('active') } function handleDrop(e) { var dt = e.dataTransfer var files = dt.files handleFiles(files) } let uploadProgress = [] let progressBar = document.getElementById('progress-bar') function initializeProgress(numFiles) { progressBar.value = 0 uploadProgress = [] for(let i = numFiles; i > 0; i--) { uploadProgress.push(0) } } function updateProgress(fileNumber, percent) { uploadProgress[fileNumber] = percent let total = uploadProgress.reduce((tot, curr) => tot + curr, 0) / uploadProgress.length console.debug('update', fileNumber, percent, total) progressBar.value = total } function handleFiles(files) { files = [...files] initializeProgress(files.length) files.forEach(uploadFile) files.forEach(previewFile) } function previewFile(file) { let reader = new FileReader() reader.readAsDataURL(file) reader.onloadend = function() { let img = document.createElement('img') img.src = reader.result document.getElementById('gallery').appendChild(img) } } function uploadFile(file, i) { var xhr = new XMLHttpRequest() var formData = new FormData() xhr.open('POST', true) xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest') // Update progress (can be used to show progress indicator) xhr.upload.addEventListener("progress", function(e) { updateProgress(i, (e.loaded * 100.0 / e.total) || 100) }) xhr.addEventListener('readystatechange', function(e) { if (xhr.readyState == 4 && xhr.status == 200) { updateProgress(i, 100) // <- Add this } else if (xhr.readyState == 4 && xhr.status != 200) { // Error. Inform the user } }) formData.append('upload_preset', 'ujpu6gyk') formData.append('file', file) xhr.send(formData) }
 .add-photo{ width: 18%; background-color: #00a100; color: #fff; padding: 11px 13px; border: 3px solid #00a100; -webkit-transition: 0.3s ease; transition: 0.3s ease; cursor: pointer; text-align: center; font-size: 13px; font-weight: 550; border-radius: 1px; margin-left: 41%; } * { box-sizing: border-box; } #dialogoverlay { display: none; opacity: 0.5; /*so that user can see through it*/ position: fixed; top: 0px; left: 0px; background: black; z-index: 10; height: 100%; width: 100%; } #dialogbox { display: none; position: fixed; background: #ffffff; border-radius: 1px; border: 0.5px solid #ccc; z-index: 10; left: 25%; top: 20%; width: 50%; height: 400px; -webkit-animation: fadeEffect 0.3s; animation: fadeEffect 0.3s; } #close-popup { float: right; background-color: red; color: #474747; font-size: 15px; } .header{ position: absolute; width: 100.2%; background-color: white; height: 11%; top: 5.4%; left: 50%; transform: translate(-50%, -50%); } .content-centre{ width: 99%; height: 77%; margin-left: 3px; margin-top: 46px; } #content-leftside{ width: 65%; height: 100%; float: left; } .tab { overflow: hidden; } .tab button { width: 33.3%; height: 14%; background-color: #acacac; float: left; color: white; outline: none; cursor: pointer; padding: 6px; transition: 0.3s; border-right: 1px solid #fff; } .tab button:hover { background-color: #474747; } .tab button.active { background-color: #474747; } .tabcontent { display: none; padding: 6px 12px; } #content-rightside{ width: 35%; height: 100%; float: right; background-color: #ffffff; border-left: 1px solid #dddddd; } #right-topbar{ width: 100%; height: 9%; background-color: #474747; color: #fff; padding: 5px; text-align: center; transition: 0.3s; } .footer{ position: absolute; width: 100.2%; background-color: #474747; height: 11%; bottom: -5.6%; left: 50%; /* top: calc(50% - 50px); */ transform: translate(-50%, -50%); } /*------------------- UPLOAD AREA -----------------------*/ #drop-area { border: 2px dashed #ccc; border-radius: 8px; width: 98%; margin: 24px auto; padding: 15px; } #progress-bar{ display: none; } #gallery { margin-top: 5%; } #gallery img { width: 55px; height: 50px; margin-bottom: 10px; margin-left: 10px } .button { display: inline-block; padding: 10px; background: #00a100; color: #fff; cursor: pointer; border-radius: 5px; } #fileElem { display: none; } #upload-button{ font-size: 40px; color: #00a100;
 <button class="add-photo" onclick="newAlert.performCustomAlert()">ADD MY PHOTO</button> <div class="popup-upload"> <div id="dialogoverlay"></div> <!--------------- SELECT MEDIA BOX ----------------> <div id="dialogbox"> <!--------------- HEADER OF THE BOX ----------------> <div class="header"> <!--------------- CLOSE POPUP ----------------> <button id="close-popup" onclick="newAlert.ok()"><i class="fa fa-times" style="margin-top: 8px; margin-right: 7px;"></i></button> <div class="select-media"> <i class="fa fa-camera" id="select-camera"></i> <h2 id="select-media">SELECT YOUR MEDIA</h2> </div> </div> <!--------------- CONTENT OF THE BOX ----------------> <div class="content-centre"> <!--------------- LEFT CONTENT ----------------> <div id="content-leftside"> <div class="tab"> <button class="tablinks" id="defaultOpen" onclick="openTab(event, 'Desktop')"><span class="fa fa-desktop"></span>&nbsp; Desktop</button> <button class="tablinks" onclick="openTab(event, 'Facebook')"><span class="fa fa-facebook"></span>&nbsp; Facebook</button> <button class="tablinks" onclick="openTab(event, 'Instagram')"><span class="fa fa-instagram"></span>&nbsp; Instagram</button> </div> <div id="Desktop" class="tabcontent"> <div id="drop-area"> <form class="my-form"> <span class="fa fa-cloud-upload" id="upload-button"></span> <p id="drag-text">Drag & Drop Your <br> Photos or Videos <br> To Upload</p> <input type="file" id="fileElem" multiple accept="image/*" onchange="handleFiles(this.files)"> <label class="button" for="fileElem">or Select Files</label> </form> </div> </div> <div id="Facebook" class="tabcontent"> <h3>Facebook</h3> </div> <div id="Instagram" class="tabcontent"> <h3>Instagram</h3> </div> </div> <!--------------- RIGHT CONTENT ----------------> <div id="content-rightside"> <!--------------- RIGHT TOPBAR ----------------> <div id="right-topbar"> <h1>Selected Media</h1> </div> <progress id="progress-bar" max=100 value=0></progress> <div id="gallery"/></div> </div> </div> <div class="footer"> </div> </div> </div> </div>

Look into below code, I made some changes on previewFile() function. I hope, by looking below code you can get idea.

 // ---------- THIS IS FOR THE POPUP ---------- // function CustomAlert() { this.performCustomAlert = function(dialog) { var windowWidth = window.innerWidth; var windowHeight = window.innerHeight; var dialogoverlay = document.getElementById('dialogoverlay'); var dialogbox = document.getElementById('dialogbox'); dialogoverlay.style.display = "block"; dialogoverlay.style.height = windowHeight + "px"; dialogbox.style.display = "block"; } this.ok = function() { document.getElementById('dialogbox').style.display = "none"; document.getElementById('dialogoverlay').style.display = "none"; } } var newAlert = new CustomAlert(); // ------------- TABS ----------------- // function openTab(evt, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(tabName).style.display = "block"; evt.currentTarget.className += " active"; } document.getElementById("defaultOpen").click(); // ---------------- UPLOAD --------------------------// // ************************ Drag and drop ***************** // let dropArea = document.getElementById("drop-area") // Prevent default drag behaviors ; ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { dropArea.addEventListener(eventName, preventDefaults, false) document.body.addEventListener(eventName, preventDefaults, false) }) // Highlight drop area when item is dragged over it ; ['dragenter', 'dragover'].forEach(eventName => { dropArea.addEventListener(eventName, highlight, false) }) ; ['dragleave', 'drop'].forEach(eventName => { dropArea.addEventListener(eventName, unhighlight, false) }) // Handle dropped files dropArea.addEventListener('drop', handleDrop, false) function preventDefaults(e) { e.preventDefault() e.stopPropagation() } function highlight(e) { dropArea.classList.add('highlight') } function unhighlight(e) { dropArea.classList.remove('active') } function handleDrop(e) { var dt = e.dataTransfer var files = dt.files handleFiles(files) } let uploadProgress = [] let progressBar = document.getElementById('progress-bar') function initializeProgress(numFiles) { progressBar.value = 0 uploadProgress = [] for (let i = numFiles; i > 0; i--) { uploadProgress.push(0) } } function updateProgress(fileNumber, percent) { uploadProgress[fileNumber] = percent let total = uploadProgress.reduce((tot, curr) => tot + curr, 0) / uploadProgress.length console.debug('update', fileNumber, percent, total) progressBar.value = total } function handleFiles(files) { files = [...files] initializeProgress(files.length) files.forEach(uploadFile) files.forEach(previewFile) } function previewFile(file) { let reader = new FileReader() reader.readAsDataURL(file) reader.onloadend = function() { let img = document.createElement('img') img.src = reader.result var mainDiv = document.createElement("div") mainDiv.className = "box" mainDiv.appendChild(img) var textbx = document.createElement("textarea") textbx.placeholder ="Caption..." mainDiv.appendChild(textbx) var btn = document.createElement("button") var tx = document.createTextNode("X"); btn.onclick = function() { $(this).closest(".box").remove() } btn.appendChild(tx); mainDiv.appendChild(btn) document.getElementById('gallery').appendChild(mainDiv) } } function uploadFile(file, i) { var xhr = new XMLHttpRequest() var formData = new FormData() xhr.open('POST', true) xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest') // Update progress (can be used to show progress indicator) xhr.upload.addEventListener("progress", function(e) { updateProgress(i, (e.loaded * 100.0 / e.total) || 100) }) xhr.addEventListener('readystatechange', function(e) { if (xhr.readyState == 4 && xhr.status == 200) { updateProgress(i, 100) // <- Add this } else if (xhr.readyState == 4 && xhr.status != 200) { // Error. Inform the user } }) formData.append('upload_preset', 'ujpu6gyk') formData.append('file', file) xhr.send(formData) }
 .add-photo { width: 18%; background-color: #00a100; color: #fff; padding: 11px 13px; border: 3px solid #00a100; -webkit-transition: 0.3s ease; transition: 0.3s ease; cursor: pointer; text-align: center; font-size: 13px; font-weight: 550; border-radius: 1px; margin-left: 41%; } * { box-sizing: border-box; } #dialogoverlay { display: none; opacity: 0.5; /*so that user can see through it*/ position: fixed; top: 0px; left: 0px; background: black; z-index: 10; height: 100%; width: 100%; } #dialogbox { display: none; position: fixed; background: #ffffff; border-radius: 1px; border: 0.5px solid #ccc; z-index: 10; left: 25%; top: 20%; width: 50%; height: 400px; -webkit-animation: fadeEffect 0.3s; animation: fadeEffect 0.3s; } #close-popup { float: right; background-color: red; color: #474747; font-size: 15px; } .header { position: absolute; width: 100.2%; background-color: white; height: 11%; top: 5.4%; left: 50%; transform: translate(-50%, -50%); } .content-centre { width: 99%; height: 77%; margin-left: 3px; margin-top: 46px; } #content-leftside { width: 65%; height: 100%; float: left; } .tab { overflow: hidden; } .tab button { width: 33.3%; height: 14%; background-color: #acacac; float: left; color: white; outline: none; cursor: pointer; padding: 6px; transition: 0.3s; border-right: 1px solid #fff; } .tab button:hover { background-color: #474747; } .tab button.active { background-color: #474747; } .tabcontent { display: none; padding: 6px 12px; } #content-rightside { width: 35%; height: 100%; float: right; background-color: #ffffff; border-left: 1px solid #dddddd; } #right-topbar { width: 100%; height: 9%; background-color: #474747; color: #fff; padding: 5px; text-align: center; transition: 0.3s; } .footer { position: absolute; width: 100.2%; background-color: #474747; height: 11%; bottom: -5.6%; left: 50%; /* top: calc(50% - 50px); */ transform: translate(-50%, -50%); } /*------------------- UPLOAD AREA -----------------------*/ #drop-area { border: 2px dashed #ccc; border-radius: 8px; width: 98%; margin: 24px auto; padding: 15px; } #progress-bar { display: none; } #gallery { margin-top: 5%; } #gallery img { width: 55px; height: 50px; margin-bottom: 10px; margin-left: 10px } .button { display: inline-block; padding: 10px; background: #00a100; color: #fff; cursor: pointer; border-radius: 5px; } #fileElem { display: none; } #upload-button { font-size: 40px; color: #00a100;
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="add-photo" onclick="newAlert.performCustomAlert()">ADD MY PHOTO</button> <div class="popup-upload"> <div id="dialogoverlay"></div> <!--------------- SELECT MEDIA BOX ----------------> <div id="dialogbox"> <!--------------- HEADER OF THE BOX ----------------> <div class="header"> <!--------------- CLOSE POPUP ----------------> <button id="close-popup" onclick="newAlert.ok()"><i class="fa fa-times" style="margin-top: 8px; margin-right: 7px;"></i></button> <div class="select-media"> <i class="fa fa-camera" id="select-camera"></i> <h2 id="select-media">SELECT YOUR MEDIA</h2> </div> </div> <!--------------- CONTENT OF THE BOX ----------------> <div class="content-centre"> <!--------------- LEFT CONTENT ----------------> <div id="content-leftside"> <div class="tab"> <button class="tablinks" id="defaultOpen" onclick="openTab(event, 'Desktop')"><span class="fa fa-desktop"></span>&nbsp; Desktop</button> <button class="tablinks" onclick="openTab(event, 'Facebook')"><span class="fa fa-facebook"></span>&nbsp; Facebook</button> <button class="tablinks" onclick="openTab(event, 'Instagram')"><span class="fa fa-instagram"></span>&nbsp; Instagram</button> </div> <div id="Desktop" class="tabcontent"> <div id="drop-area"> <form class="my-form"> <span class="fa fa-cloud-upload" id="upload-button"></span> <p id="drag-text">Drag & Drop Your <br> Photos or Videos <br> To Upload</p> <input type="file" id="fileElem" multiple accept="image/*" onchange="handleFiles(this.files)"> <label class="button" for="fileElem">or Select Files</label> </form> </div> </div> <div id="Facebook" class="tabcontent"> <h3>Facebook</h3> </div> <div id="Instagram" class="tabcontent"> <h3>Instagram</h3> </div> </div> <!--------------- RIGHT CONTENT ----------------> <div id="content-rightside"> <!--------------- RIGHT TOPBAR ----------------> <div id="right-topbar"> <h1>Selected Media</h1> </div> <progress id="progress-bar" max=100 value=0></progress> <div id="gallery" /></div> </div> </div> <div class="footer"> </div> </div> </div> </div>

just replace previewFile function with this.

  function previewFile(file) {
    let reader = new FileReader()
    reader.readAsDataURL(file);
    reader.onloadend = function() {
     var gallleryDiv=document.getElementById('gallery');
     var wrapperDiv = document.createElement("div");
     let img = document.createElement('img');
     img.src = reader.result;
     wrapperDiv.className = "wrapperDiv";
     wrapperDiv.appendChild(img)
     var textbx = document.createElement("textarea");
     wrapperDiv.appendChild(textbx);
     var btn = document.createElement("button");
     var tx = document.createTextNode("X");
     btn.onclick = function() {$(this).closest(".wrapperDiv").remove()}
     btn.appendChild(tx);
     wrapperDiv.appendChild(btn);
     gallleryDiv.appendChild(wrapperDiv);
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM