简体   繁体   中英

Click event doesn't fire on first click but does everytime after

I am making my add to cart button update a span counter of items in the cart which works every time after you click the button once but does not work on the first click

I have tried using .on method which gives the same outcome and have tried using document.ready which also doesn't effect it.

$(document).ready(function() {
  $('#addToCart').on('click', function() {
    jQuery.getJSON('/cart.js', function(cart) {
      $("span.count").html(cart.item_count);
    });
  }); 
});

I expect the addToCart button to update the span.count on every click. The actual result is that it works after the first click.

$(document).ready(function() { 
  $('#addToCart').on('click', function() { 
    alert("Hello"); 
  }); 
});

Please try it now Hope this ll helpful for you

Button clicked every time, there is no issue with button click

 $(document).ready(function() { $('#addToCart').on('click', function() { alert('button clicked'); jQuery.getJSON('/cart.js', function(cart) { $("span.count").html(cart.item_count); }); }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/shopify-cartjs/0.4.1/cart.min.js"></script> <button id="addToCart" type="button">Add to cart</button> <span>Cart Items: </span> <span class="count">0</span> 

You can try the solution provided below if it works:

$(document).ready(function() {
    $(document).on('click', '#addToCart', function() {  
        alert('button clicked');
        jQuery.getJSON('/cart.js', function(cart) { 
            $("span.count").html(cart.item_count);
        });
    }); 
});

I want to suggest you another way to update cart without using Ajaxify cart API. You should try once. I'm talking about cart.js

You just need to include below CDN in your theme header.

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/shopify-cartjs/0.4.1/cart.min.js"></script>

After that you need to add tag "data-cart-render" in your html. It will automatically render cart item count inside the html tag. Example:

<span data-cart-render="item_count"></span>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM