Why does my code not reload the iframe after I run an onClick function to reload?

Viewed 98

I am trying to make an onclick function that will refresh an iframe's data to parse its HTML and include some of that HTML in a sidebar. When I click on the "add to cart" button the first time I have to refresh the page to get the HTML in the sidebar to load. I also have to press the "add to cart" button twice after clicking the button to empty the cart in the sidebar before the HTML appears again if I refresh the page and empty the cart from the sidebar. This is the website I'm working on here.

This is the HTML / JavaScript that I'm using:

<div id="sidebarcartdiv"></div>

<script>
  var data;
  var url = "index.php?route=checkout/cart";
  var iframe = document.createElement("iframe");
  iframe.id = "cartiframe";

  iframe.onload = function () {
    data = iframe.contentWindow.document.body.innerHTML;

    const parser = new DOMParser();
    var parsedDocument = parser.parseFromString(data, "text/html");

    if (parsedDocument.getElementsByClassName("table-responsive")[0] != null) {
      document.getElementById("sidebarcartdiv").innerHTML =
        parsedDocument.getElementsByClassName("table-responsive")[0].innerHTML;
    } else {
      document.getElementById("sidebarcartdiv").innerHTML =
        "Your cart is empty";
    }
  };

  iframe.src = url;
  iframe.style.display = "none";
  document.body.appendChild(iframe);

  document.addEventListener("click", (event) => {
    if (
      event.target
        .closest("button")
        .getAttribute("onClick")
        .includes("cart.add")
    ) {
      document.getElementById("cartiframe").contentWindow.location.reload();
    }
    if (
      event.target
        .closest("button")
        .getAttribute("onClick")
        .includes("cart.remove")
    ) {
      document.getElementById("sidebarcartdiv").innerHTML =
        "Your cart is empty";
    }
  });
</script>

0 Answers
Related