Brad Playdon
Brad Playdon

Reputation: 21

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.

Upvotes: 1

Views: 630

Answers (4)

Mohit Tiwari
Mohit Tiwari

Reputation: 165

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>

Upvotes: 0

Anshul
Anshul

Reputation: 395

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);
        });
    }); 
});

Upvotes: 1

Jayoti Parkash
Jayoti Parkash

Reputation: 878

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>

Upvotes: 0

Gurdeep Singh
Gurdeep Singh

Reputation: 41

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

Please try it now Hope this ll helpful for you

Upvotes: 0

Related Questions