Untitled

 avatar
unknown
javascript
5 months ago
2.0 kB
3
Indexable
<script>
jQuery(document).ready(function($) {
    // Function to update the custom cart count
    function updateCartCount(cartCount) {
        const cartCountElement = document.querySelector('.custom-cart-count');

        // Check if cartCount is defined and is a number
        if (cartCount !== undefined && !isNaN(cartCount)) {
            cartCountElement.innerHTML = cartCount; // Update the count in the icon

            // Hide the cart count if it's 0
            if (cartCount === 0) {
                cartCountElement.style.display = 'none'; // Hide the counter
            } else {
                cartCountElement.style.display = 'inline'; // Show the counter
            }
        } else {
            cartCountElement.innerHTML = 0; // Default to 0 if undefined or NaN
            cartCountElement.style.display = 'none'; // Hide the counter if NaN
        }
    }

    // Get the initial cart count from PHP
    const initialCartCount = <?php echo WC()->cart->get_cart_contents_count(); ?>;
    console.log('Initial Cart Count from PHP:', initialCartCount); // Debugging output
    updateCartCount(initialCartCount); // Update cart count on page load

    // Event listener for the custom cart icon to link to the cart page
    const customCartIcon = document.querySelector('.custom-cart-icon');
    customCartIcon.addEventListener('click', function() {
        console.log('Custom cart icon clicked'); // Debugging output
        window.location.href = '/kurv/';  // Change to your cart URL
    });

    // WooCommerce event listener for cart updates
    $('body').on('added_to_cart removed_from_cart updated_cart_totals wc_fragments_refreshed wc_fragments_refresh', function(event) {
        console.log('Event triggered:', event.type); // Log the event type
        const updatedCartCount = <?php echo WC()->cart->get_cart_contents_count(); ?>; // Get the updated cart count from PHP
        updateCartCount(updatedCartCount); // Update the cart count dynamically
    });
});
</script>
Editor is loading...
Leave a Comment