简体   繁体   中英

How to create a function for a button that is dynamically added to the website? Vanilla Javascript

Hi so I'm creating this Image Upload feature but I'm stuck with the logic of creating a function for the dynamically added call to action buttons . So I have this drag and drop upload image, and when you drop the image in the drop-area it'll automatically display a preview of the image and that preview image has a button below in it, a Remove Button

const previewImage = function(file) {
  let reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {        
    let div = document.createElement('div');
    div.className = 'preview-image-result';
    div.innerHTML = `
      <img src="${reader.result}">
      <div class="d-flex justify-content-center">
        <span class="remove-image-button" onclick="removeImage()">Remove Image</span>
      </div>
    `;
  }
  document.getElementById('preview-image-container').prepend(div);
}

I tried to add a onclick=removeImage() in the <span> but it returns error and says (index):1 Uncaught ReferenceError: removeImage is not defined I assume that since the <span>Remove Image</span> is dynamically added to the site it is not detecting the removeImage() method I created. Anyone can help me on what method to use in this kind of workflow or am I missing something? using Vanilla Javascript

const removeImage = function() {
 // remove image
}

An event listener on the document will do:

document.addEventListener("click", function(event){
  if(event.target.classList.contains("remove-image-button"){
    event.target.closest(".preview-image-result").remove();
  }
})

So if any click on the document occurs and the clicked element has the remove-image-button class, its preview-image-result parent will be removed.

Adding an event listener to the document and checking for specific condition of the clicked element is also called event delegation .

I see, thanks for pointing it out on the comments. The removeImage() is placed inside of the jQuery(document).ready(function () { }) I change the placement of the removeImage() outside of the jQuery(document).ready(function () {}) and It works!

const removeImage = function() {
  // remove image
}

jQuery(document).ready(function () {
const previewImage = function(file) {
  let reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {        
    let div = document.createElement('div');
    div.className = 'preview-image-result';
    div.innerHTML = `
      <img src="${reader.result}">
      <div class="d-flex justify-content-center">
        <span class="remove-image-button" onclick="removeImage()">Remove Image</span>
      </div>
    `;
  }
  document.getElementById('preview-image-container').prepend(div);
}
})

I can't tell if the dynamic part of OP code actually works so in the example below the img has been added dynamically. The event handler removeImg(e) has been bound to an ancestor element <section> . Through event delegation, any button of any amount can be controlled as long as it's within the <section> . The event handler has been designed only to react to any click on .btn and nothing else.

 const sec = document.querySelector('section'); const previewImage = () => { let img = ` <figure class="d-flex justify-content-center"> <img src="https://i.ibb.co/hZj77BZ/lena01.jpg" width='150'><figcaption><button class="btn">Remove Image</button></figcaption></figure> `; sec.insertAdjacentHTML('afterBegin', img); } previewImage(); const removeImg = e => { const btn = e.target; if (btn.matches('.btn')) { let imgFrame = btn.closest('figure'); imgFrame.remove(); } }; sec.onclick = removeImg;
 <section></section>

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