Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
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
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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);
}
})
about 4 years ago · Juan Pablo Isaza Relatório

0

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda