Вопрос

Question: How can I show the number of items in a user's cart using the minicart.js script?

Backstory: I'm developing a static HTML website that is selling a small number of products using standard PayPal buttons and minicart.js

I'd like to have an area in the header of my website that displays the number of items currently in the "cart", but I can't figure out how to do so. There is no example detailing this functionality on the minicart.js website.

I'm sure it can be done, but I'm at a loss. Any help would be greatly appreciated. Thanks!

Это было полезно?

Решение 2

I managed to figure out a way to achieve what I'm looking for by finding the necessary variable set through minicart.js and then manipulating it via jQuery.

minicart.js gives me the following variable which outputs the current cart total:

paypal.minicart.cart.total();

I then took that variable and applied some jQuery that converted this variable into a separate variable called "cartTotal" which is checked and updated every time a user interaction happens on the page (ie - a click or a keypress). I found that a brief delay was needed in order for everything to work properly. Interestingly, the keypress check needs a longer delay than the mouse click.

My final (for now) working code is as follows:

$( document ).ready(function() {
     var cartTotal = paypal.minicart.cart.total();
        $('input#cart').val('$' + cartTotal);

    $( "body" ).click(function() {
            setTimeout(function() { // Setting slight delay on function to accomodate for button push of removing items from cart
             var cartTotal = paypal.minicart.cart.total();
            $('input#cart').val('$' + cartTotal);
        }, 100);
    });


    $( "body" ).keypress(function() {
       setTimeout(function() { // Setting longer delay on function to accomodate for key push of removing items from cart
             var cartTotal = paypal.minicart.cart.total();
            $('input#cart').val('$' + cartTotal);
        }, 900);
    });

Другие советы

You can get like this:

paypal.minicart.cart.items().length

It works for me

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top