Home Forums Plugins WooCommerce Cart All in One fly to cart

fly to cart

  • Author
    Posts
  • #160399

    AC
    Participant

    Hi again, I, wonder if there is an easy way to add animation (preferably fly to cart), like the one you have in your floating cart. I know i can make sidebar open after product is added, but i don’t want it like that. I would like to animate it somehowe.
    I asked it in Chat GPT and got this one

    const buttons = document.querySelectorAll(‘.add_to_cart_button’);
    const cartIcon = document.querySelector(‘.cart’);

    buttons.forEach(button => {
    button.addEventListener(‘click’, () => {
    // Get the position of the button
    const buttonRect = button.getBoundingClientRect();
    const buttonX = buttonRect.left + buttonRect.width / 2;
    const buttonY = buttonRect.top + buttonRect.height / 2;

    // Get the product ID
    const productId = button.dataset.productId;

    // Trigger the cart functionality
    jQuery.ajax({
    type: ‘POST’,
    url: wc_add_to_cart_params.ajax_url,
    data: {
    action: ‘woocommerce_add_to_cart’,
    product_id: productId,
    quantity: 1
    },
    success: function(response) {
    if (response.error & response.error.type === ‘added_already’) {
    // Product is already in cart, do nothing
    } else {
    // Product added to cart, trigger fly-to-cart animation
    const productEl = document.createElement(‘div’);
    productEl.classList.add(‘product-fly’);
    productEl.innerText = ‘+1’;
    document.body.appendChild(productEl);

    const productRect = productEl.getBoundingClientRect();
    const productX = productRect.left + productRect.width / 2;
    const productY = productRect.top + productRect.height / 2;

    const dx = cartIcon.offsetLeft + cartIcon.offsetWidth / 2 – productX;
    const dy = cartIcon.offsetTop + cartIcon.offsetHeight / 2 – productY;
    const distance = Math.sqrt(dx * dx + dy * dy);
    const angle = Math.atan2(dy, dx);

    productEl.style.transform = translate(${dx}px, ${dy}px) rotate(${angle}rad);

    setTimeout(() => {
    productEl.style.transform = ‘none’;
    productEl.style.opacity = ‘0’;
    cartIcon.classList.add(‘added’);
    setTimeout(() => {
    document.body.removeChild(productEl);
    cartIcon.classList.remove(‘added’);
    }, 1000);
    }, 100);
    }
    }
    });
    });
    });

You must be logged in to see replies to this topic. Click here to login or register