skip to Main Content

I am working on a shopify store, there is a ‘remove from cart’ option on the cart page, when they click on it a popup shows up to confirm if they want to remove it from the cart.
The issue I am having is that the popup will only work on the first item, the others will just take you back to the top of the page.

Here’s the code I am using.

The remove text

<td style="text-align: center">
            <a href="#" id="cart_popup">X</a>
</td>

The Popup

<!-- The Modal -->
    <div id="myModal" class="modal">

      <!-- Modal content -->
      <div class="modal-content">
        <p class="modal-index-title">Hey!</p>
        <p class="modal-title">Are you sure you want to remove this?</p>
        <div class="modal-confirm">
          <span class="close">No!</span>
          <p><a href="#" onclick="remove_item({{ item.variant.id }}); return false;">Yes</a></p>
        </div>
      </div>

    </div>

The script

  // Get the modal
  var modal = document.getElementById('myModal');

  // Get the button that opens the modal
  var btn = document.getElementById("cart_popup");

  // Get the <span> element that closes the modal
  var span = document.getElementsByClassName("close")[0];

  // When the user clicks on the button, open the modal 
  btn.onclick = function() {
      modal.style.display = "block";
  }

  // When the user clicks on <span> (x), close the modal
  span.onclick = function() {
      modal.style.display = "none";
  }

  // When the user clicks anywhere outside of the modal, close it
  window.onclick = function(event) {
      if (event.target == modal) {
          modal.style.display = "none";
      }
  }

2

Answers


  1. IDs are supposed to be unique for a DOM element so your JS code will just grab the first instance of the cart_popup element and apply the onClick there.

    If you want to make it apply across all your remove cart buttons, add a CSSclass to it and then apply the btn.onclick function to buttons having that class.

    EDIT:

    Example:

    var classname = document.getElementsByClassName("classname");
    
    var showModal = function() {
        modal.style.display = "block";
    };
    
    for (var i = 0; i < classname.length; i++) {
        classname[i].addEventListener('click', showModal, false);
    }
    
    Login or Signup to reply.
  2. You might have several elements with the same id attribute. Only the first triggers your btn.onclick function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search