How to execute an insert only once via javascript / jQuery

0

I have a situation where I need to insert a div once in a block via jQuery, is there any function already defined that guarantees that this block will be inserted only once? Without me having to check with if

if (!jQuery('.product').parents('.product-info').has('.quickreview').length {
    jQuery('.product').parents('.product-info').prepend("<div class="quickreview"></div>");
}
    
asked by anonymous 17.08.2018 / 18:42

3 answers

2

I would use a logic for this, would create a bool to see if it is already created, if it passes the if once it becomes false and will not enter it anymore

This way:

var needToCreate = true;

if (!jQuery('.product').parents('.product-info').has('.quickreview').length && needToCreate) {
    jQuery('.product').parents('.product-info').prepend("<div class="quickreview"></div>");
    needToCreate = false;
}
    
17.08.2018 / 18:58
1

See if using the one method helps you:

$("#btn1").one("click", function(){                   // executa apenas uma vez
  $("#local1").prepend("<p>Qualquer coisa - uma vez</p>");
})

$("#btn2").on("click", function(){                   // executa varias vezes
  $("#local2").prepend("<p>Qualquer coisa - mais de uma vez</p>");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><buttonid="btn1">inserir</button>  
<div id="local1"></div>
<hr>
<button id="btn2">inserir</button>  
<div id="local2"></div>
    
17.08.2018 / 20:19
0

If you want to understand when the DOM is changed you should use MutationObserver . This allows you to define a callback that executes whenever there is a change in a given element and its descendants.

document.getElementById("inserir").addEventListener("click", function() {
  document.getElementById("conteudo").innerHTML = "<div class='product'>Produto</div>";
});

//no pai do que pretende escutar as alterações
const targetNode = document.getElementById('conteudo'); 
const config = { childList: true, subtree: true};

const observer = new MutationObserver(function(mutationsList) {
  for (let mutation of mutationsList) { //para cada uma das alterações no DOM
    if (mutation.type == 'childList') { //se afeta os filhos
      const removedIds = [...mutation.removedNodes].map(x => x.id); //apanhar os id's
      if (!removedIds.includes("teste")){ //se o id existe é porque foi inserido
        console.log("teste já inserido");
      }
    }
  }
}); 

observer.observe(targetNode, config);
<div id="conteudo">
  <div id="teste">Div teste aqui</div>
</div>
<button id="inserir">Uma única vez</div>
    
20.08.2018 / 15:01