ST80
ST80

Reputation: 3903

Jquery Modal popup gets rerendered over and over

I'm creating a Modal popup window dynamically by using jquery. SO far so good, but once I open it and close it, each time it gets opened again it renders twice and I don't know why. Here is my code:

jQuery(document).ready(function($) {
  $(document).click(e => {
    if (!$(e.target).is(".modal-content, #closeBtn")) {
       $(".modal").remove();
    }
  });

 $(".add_to_cart_button").on("click", e => {
    if ($(".modal").length) {
      $(".modal").remove();
    }
    // get current productItem
    let currentItem = e.currentTarget;

    // get product Title
    let productTitle = $(currentItem)
      .parent()
      .parent()
      .parent()
      .next()
      .find("h2")
      .text();

   // Pass Title to modal
   addedToCart(productTitle);
 });

 // Modal popup
 function addedToCart(productTitle) {
   if ($(".modal").length) {
     $("body")
       .find(".modal")
       .remove();
   }
   // Listen to event
   $("body").on("added_to_cart", function(e, data) {
     // Generate dynamic popup
     let modalHtml = '<div id="productModal" class="modal">';
     modalHtml += '<div class="modal-content">';
     modalHtml += '<div class="modal-header">';
     modalHtml += '<span class="closeBtn" id="closeBtn">&times;</span> 
     </div>';
     modalHtml += '<div class="modal-body">';
     modalHtml +=
      "<p><b>" + productTitle + "</b> er blevet tilføjet til kurven!</p>";
     modalHtml += "</div>";
     modalHtml += "</div>";
     modalHtml += "</div>";

     // Append modal to body and show
     $("body").append(modalHtml);
     $(".modal").show();

     // Close modal and remove from DOM
     $(".closeBtn").on("click", () => {
       $(".modal").remove();
     });

   });
  }
});

Can someone tell me what I'm doing wrong? It seems not to care if I remove it, and to exaggerate, I remove it everywhere I can but with no luck, it keeps rerender everytime I open it.

Upvotes: 0

Views: 39

Answers (1)

cli-ish
cli-ish

Reputation: 776

You bind the added_to_cart event on each click on the cart button.

you need to unbind it if you use it there or you should only define it once.

Upvotes: 1

Related Questions