LogoLogo
Documentação de Temas
Documentação de Temas
  • 🚀COMECE POR AQUI
    • Temas Tray
    • Entenda o Tema
    • Meu primeiro tema
  • 💻Tray CLI
    • Instalação
    • Comandos
      • Erros Retornados
    • API para integrações Tray CLI
  • 🧱Construindo seu Template
    • Twig
      • O que é o Twig
      • Como ele é utilizado nos temas
      • Possibilidades de uso
      • Documentação para consulta
    • Visão Geral
      • Estrutura do Tema
      • Arquivo de configuração
      • Extensões de arquivos
      • Codificação de Arquivos
      • Avisos e Recomendações
      • Flags
    • Editor do Tema
      • Antigo
        • Como criar um Editor
        • Settings.html
      • Novo
        • Estrutura
          • Seções
          • Ícones
          • Componentes
            • Text
            • Textarea
            • Email
            • Number
            • Color
            • Checkbox
            • Radio
            • Select
            • Toggle
            • Upload
            • Tab
            • Alert
          • Exemplo de utilização
        • Thumb preview do tema
        • Imagens padrões
        • Como desabilitar e reabilitar?
      • Settings.json
    • Desenvolver
      • Atributo Google Analytics 4
      • Como adicionar o botão comprar na listagem dos produtos
      • Como criar um carrossel de produtos
      • Como inserir um vídeo na home da loja
      • Como manipular as variações de produtos
      • Como saber se o usuário está logado
      • Descontinuação do carrinho.php
      • Exibindo as formas de pagamento de um produto
      • Informação de preço com tempo de cache menor
      • Order Bump - Produtos Relacionados
      • Páginas Institucionais
      • Página de recuperação de senha
      • Página Live Shop
      • Recursos extras
      • Personalização das paginas de carrinho e checkout
    • Core Web Vitals
      • Desempenho
        • Lazyload
        • Primeira dobra
        • Fontes
        • Definição largura e altura
        • Sprite formas de pagamentos
      • Boas Práticas
        • Origem cruzada
      • Acessibilidade
        • Atributo Lang
        • Nome discernível
        • Atributo ALT
        • Contraste
        • IDs únicos
        • ARIA Labelled By
        • Tabindex
    • Otimizar e Medir
      • Carregamento na home
      • Layout AMP
      • Utilizando PWA na loja
    • Referências
      • Objetos
        • banner
        • breadcrumb
        • category
        • categories
        • filters
        • filter_options
        • links
        • pages
        • paginate
        • paymentMethods
        • product
        • productTabs
        • products
        • productFeatured
        • seals
        • search
        • settings
        • store
        • tags
        • tray
        • themePath
        • utils
      • Funções
        • asset()
        • Brands()
        • Categories()
        • Image()
        • Products()
        • Translation()
      • Data Attributes
        • Banners
        • Cart
        • Compare
        • Filter
        • Logged User
        • Search (Suggestion)
      • Componentes
        • Adicionar ao carrinho sem sair da página
        • Banner Desconto Progressivo
        • Banner extra com contagem de cliques
        • Banner Régua
        • Banner Rotativo
        • Botão "Voltar para o topo"
        • Botões Quantidade
        • Carrinho Lateral
        • Exibir a segunda imagem ao passar o mouse
        • Filtro Inteligente
        • Link flutuante para Whatsapp
        • Menu de Categorias
        • Menu de Categorias em 3 Níveis
        • Menu de Categorias com ver mais categorias
        • Menu de Categorias com Imagens
        • Menu de Categorias com Imagens - Hover
        • Menu de Categorias com produto
        • Menu de Marcas
        • Modal de Ofertas
        • Notícias com imagem na home
        • Novo Filtro Inteligente
        • Paginação
        • Porcentagem Desconto
        • Popup de Newsletter
        • Star Ranking
        • Selos da Loja
        • Selos do produto
        • Showcase ( List / Grid )
        • Topo Flutuante
        • Tray Login
        • Whatsapp flutuante
    • APIs Disponíveis
      • Busca
      • Carrinho de Compra
      • Categorias
      • Produtos
      • Variações de Produto
  • ✔️Homologação
    • Loja de Temas Tray
    • Requerimentos
      • Exclusividade
      • Identidade única
      • Estrutura necessária
      • Funcionalidades
      • Nova Busca e Filtro inteligente
      • Selos de produtos
      • Google Lighthouse
      • Consistência e funcionalidade
      • Compatibilidade com navegadores
      • Assets
      • Otimização para buscadores (SEO)
      • Acessibilidade
      • Configurações
      • Sistema de cores
      • Imagens responsivas
      • Nomes dos temas
      • Versionamento e notas de lançamento
      • Lojas demonstrativas
      • Documentação e suporte
    • Checklist obrigatório
    • Templates
    • Homologando o tema
    • Atualizando o tema
    • FAQ
  • 📣NOVIDADES
    • Tray CLI
    • Checklist
    • Tema Draft
    • Novo Editor
Powered by GitBook
On this page

Was this helpful?

  1. Construindo seu Template
  2. Referências
  3. Componentes

Carrinho Lateral

Snippet para criar o carrinho lateral, ou flutuante como alguns conhecem.

{#
 # Snippets do Carrinho Lateral
 # elements/snippets/cart.html
#}

<div class="cart-sidebar">
    <div class="header-cart">
        <div class="box-prev">
            <svg class="icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 492 492">
                <path d="M198.608,246.104L382.664,62.04c5.068-5.056,7.856-11.816,7.856-19.024c0-7.212-2.788-13.968-7.856-19.032l-16.128-16.12
                    C361.476,2.792,354.712,0,347.504,0s-13.964,2.792-19.028,7.864L109.328,227.008c-5.084,5.08-7.868,11.868-7.848,19.084
                    c-0.02,7.248,2.76,14.028,7.848,19.112l218.944,218.932c5.064,5.072,11.82,7.864,19.032,7.864c7.208,0,13.964-2.792,19.032-7.864
                    l16.124-16.12c10.492-10.492,10.492-27.572,0-38.06L198.608,246.104z"/>
            </svg>
        </div>
        <div class="text">Carrinho de compras</div>
    </div>
    <div class="content-cart empty">
        <div class="list">
            <div class="error">
                <div class="text">Carrinho Vazio</div>
            </div>
        </div>
    </div>
    <div class="footer-cart">
        <div class="text-info">
            <div class="total">
                <span>Subtotal:</span> 
                <span class="value"></span>
            </div>
        </div>
        <div class="line">
            <a href="{{ links.cart }}" rel="nofollow" class="link-cart">Finalizar compra</a>
            <div class="box-prev">Continuar Comprando</div>
        </div>
    </div>
</div>

<div class="shadow-cart"></div>
.cart-sidebar, .shadow-cart {
    position: fixed;
    height: 100%;
    top: 0;
    opacity: 0;
    transition: .3s ease-in-out;
}

.shadow-cart {
    width: 100%;
    background-color: #171717;
    left: 0;
    z-index: 11;
    visibility: hidden;
}

.cart-sidebar.active ~ .shadow-cart {
    opacity: .9;
    visibility: visible;
}

.cart-sidebar {
    right: 0;
    background: #ffffff;
    color: #0d0d0d;
    z-index: 12;
    width: 430px;
    max-width: 100%;
    padding: 0 20px;
    transform: translateX(100%);
    display: flex;
    flex-direction: column;
}    

.cart-sidebar.active {
    transform: translateX(0);
    opacity: 1;
}

.cart-sidebar .header-cart {
    background: #0c0c0c;
    margin: 0 -20px;
    color: #ffffff;
    display: flex;
    align-items: center;
}

.cart-sidebar .header-cart .box-prev {
    padding: 10px;
    margin-right: 14px;
    cursor: pointer;
    background-color: #2d2d2d;
}

.cart-sidebar .header-cart .box-prev .icon {
    width: 16px;
    height: 16px;
    fill: #fff;
    display: block;
}

.cart-sidebar .content-cart {
    overflow: auto;
    padding-top: 20px;
    display: flex;
    flex-grow: 1;
    flex-direction: column;
    justify-content: space-between;
}

.cart-sidebar .item {
    margin-bottom: 20px;
}

.cart-sidebar .box-cart {
    display: flex;
    align-items: center;
}

.cart-sidebar .box-cart .box-image {
    width: 84px;
    height: 84px;
    border: 1px solid #f6f6f8;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
}

.cart-sidebar .box-cart .box-image img {
    display: block;
    max-height: 100%;
    max-width: 100%;
    margin: auto;
}

.cart-sidebar .box-cart .info-product {
    width: calc(100% - 80px);
    margin-left: 10px;
    padding-right: 20px;
    position: relative;
}

.cart-sidebar .box-cart .line-top {
    display: flex;
    justify-content: space-between;
}  

.cart-sidebar .box-cart .info-product a {
    display: block;
    margin-bottom: 8px;
}

.cart-sidebar .box-cart .info-product .remove {
    width: 12px;
    height: 12px;
    position: absolute;
    cursor: pointer;
    top: 0;
    right: 0;
}

.cart-sidebar .box-cart .info-product .price {
    font-weight: 700;
}

.cart-sidebar .box-cart .info-product .qnt {
    font-size: .75rem;
}

.cart-sidebar .footer-cart {
    height: 200px;
    margin-top: 15px;
}

.cart-sidebar .content-cart.empty + .footer-cart {
    display: none;
}

.cart-sidebar .footer-cart .text-info {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    border-bottom: 1px solid #e4e4e4;
    text-align: right;
}

.cart-sidebar .text-info .value {
    font-weight: 700;
    display: block;
}

.cart-sidebar .footer-cart .line {
    margin: 20px 0;
}

.cart-sidebar .footer-cart .link-cart {
    color: #fff;
    text-align: center;
    background: #646464;
    width: 100%;
    display: block;
    border-radius: 30px;
    line-height: 55px;
}

.cart-sidebar .footer-cart .box-prev {
    text-align: center;
    margin-top: 15px;
    cursor: pointer;
}
function toReal(value, str_cifrao) {
    return str_cifrao + ' ' + value.formatMoney(2, ',', '.');
}

var cart = {

    session: function () {
        return jQuery("html").attr("data-session");
    },

    removeProduct: function (element){

        var id = parseInt(jQuery(element).attr('data-id'));
        var variant = '/' + jQuery(element).attr('data-variant');
        var together = jQuery(element).attr('data-together') !== '' ? '/' + jQuery(element).attr('data-together') : '';
        var addText = jQuery(element).attr('data-add') == "" ? '' : jQuery(element).attr('data-add');
                
        jQuery.ajax({
            method: "DELETE",
            url: "/web_api/carts/" + cart.session() + "/" + id + variant + together + "?" + jQuery.param({ "additional_information": addText })
        }).done(function(response) {
            cart.listProduct();
        }).fail(function(error) {
            cart.listProduct();
        })
    },

    listProduct: function () {
        jQuery.ajax({
            method: "GET",
            url: "/web_api/cart/" + cart.session(),
            success: function (response) {
                cart.forProduct(response);
            },
            error: function (error) {
                cart.forProduct([]);
            }
        });
    },

    total: function(price){
        jQuery('.cart-sidebar .total .value').text(toReal(parseFloat(price), 'R$'));
    },

    forProduct: function (listProducts) {

        var listDom = jQuery('.cart-sidebar .content-cart .list');
        listDom.find('*').remove();
        listDom.parent().removeClass('empty');

        var qnt = 0;
        var total = 0.0;
        var listId = [];

        if (listProducts.length) {

            listProducts.forEach(function (product) {

                product = product.Cart;
                var addMsg = product.additional_information;
                prices = product;
                var productImage = product.product_image.thumbs[90].https.length ? product.product_image.thumbs[90].https : ''; 
                listDom.append(cart.templateProduct(product.product_id, product.variant_id, product.product_name, productImage, product.quantity, product.price, product.product_url.https,addMsg,product.bought_together_id));
                qnt += parseInt(product.quantity);
                total += (parseFloat(product.price) * parseInt(product.quantity));
                listId.push(parseInt(product.product_id));

            });

            cart.total(total);

        } else {

            listDom.append('<div class="error"><div clas="text">Carrinho Vazio</div></div>');
            listDom.parent().addClass('empty');

        }
    },

    startCart: function () {

        jQuery('.cart-toggle').on('click', function(e){
            e.preventDefault();
            cart.showCart();
        });

        jQuery('.shadow-cart, .cart-sidebar .box-prev').on('click', function(e){
            jQuery('.cart-sidebar').removeClass('active');
        });

    },

    showCart: function(){
        cart.listProduct();
        jQuery('.cart-sidebar').addClass('active');
    },

    templateProduct: function (id, variant, name, image, qnt, price, url, addMsg, together) {

        var template = '\
            <div class="item">\
                <div class="box-cart flex align-center">\
                    <div class="box-image">\
                        <a href="{url}" class="image">\
                            <img src="{image}" alt="{name}">\
                        </a>\
                    </div>\
                    <div class="info-product">\
                        <div class="line-top flex justify-between">\
                            <a href="{url}" class="name t-color">{name}</a>\
                            <div class="remove" data-id="{id}" data-together="{together}" data-variant="{variant}" data-add="{addMsg}" onclick="cart.removeProduct(this)">\
                                <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 438.529 438.529">\
                                    <path d="M417.689,75.654c-1.711-1.709-3.901-2.568-6.563-2.568h-88.224L302.917,25.41c-2.854-7.044-7.994-13.04-15.413-17.989C280.078,2.473,272.556,0,264.945,0h-91.363c-7.611,0-15.131,2.473-22.554,7.421c-7.424,4.949-12.563,10.944-15.419,17.989l-19.985,47.676h-88.22c-2.667,0-4.853,0.859-6.567,2.568c-1.709,1.713-2.568,3.903-2.568,6.567v18.274c0,2.664,0.855,4.854,2.568,6.564c1.714,1.712,3.904,2.568,6.567,2.568h27.406v271.8c0,15.803,4.473,29.266,13.418,40.398c8.947,11.139,19.701,16.703,32.264,16.703h237.542c12.566,0,23.319-5.756,32.265-17.268c8.945-11.52,13.415-25.174,13.415-40.971V109.627h27.411c2.662,0,4.853-0.856,6.563-2.568c1.708-1.709,2.57-3.9,2.57-6.564V82.221C420.26,79.557,419.397,77.367,417.689,75.654z M169.301,39.678c1.331-1.712,2.95-2.762,4.853-3.14h90.504c1.903,0.381,3.525,1.43,4.854,3.14l13.709,33.404H155.311L169.301,39.678z M347.173,380.291c0,4.186-0.664,8.042-1.999,11.561c-1.334,3.518-2.717,6.088-4.141,7.706c-1.431,1.622-2.423,2.427-2.998,2.427H100.493c-0.571,0-1.565-0.805-2.996-2.427c-1.429-1.618-2.81-4.188-4.143-7.706c-1.331-3.519-1.997-7.379-1.997-11.561V109.627h255.815V380.291z"/>\
                                    <path d="M137.04,347.172h18.271c2.667,0,4.858-0.855,6.567-2.567c1.709-1.718,2.568-3.901,2.568-6.57V173.581c0-2.663-0.859-4.853-2.568-6.567c-1.714-1.709-3.899-2.565-6.567-2.565H137.04c-2.667,0-4.854,0.855-6.567,2.565c-1.711,1.714-2.568,3.904-2.568,6.567v164.454c0,2.669,0.854,4.853,2.568,6.57C132.186,346.316,134.373,347.172,137.04,347.172z"/>\
                                    <path d="M210.129,347.172h18.271c2.666,0,4.856-0.855,6.564-2.567c1.718-1.718,2.569-3.901,2.569-6.57V173.581c0-2.663-0.852-4.853-2.569-6.567c-1.708-1.709-3.898-2.565-6.564-2.565h-18.271c-2.664,0-4.854,0.855-6.567,2.565c-1.714,1.714-2.568,3.904-2.568,6.567v164.454c0,2.669,0.854,4.853,2.568,6.57C205.274,346.316,207.465,347.172,210.129,347.172z"/>\
                                    <path d="M283.22,347.172h18.268c2.669,0,4.859-0.855,6.57-2.567c1.711-1.718,2.562-3.901,2.562-6.57V173.581c0-2.663-0.852-4.853-2.562-6.567c-1.711-1.709-3.901-2.565-6.57-2.565H283.22c-2.67,0-4.853,0.855-6.571,2.565c-1.711,1.714-2.566,3.904-2.566,6.567v164.454c0,2.669,0.855,4.853,2.566,6.57C278.367,346.316,280.55,347.172,283.22,347.172z" />\
                                </svg>\
                            </div>\
                        </div>\
                        <div class="line-down">\
                            <div class="qnt">Quantidade: {length}</div>\
                            <div class="price">{price}</div>\
                        </div>\
                    </div>\
                </div>\
            </div>\
        ';

        price = toReal(parseFloat(price), 'R$');

        template = template.replace(/{url}/g,url);
        template = template.replace(/{image}/g,image);
        template = template.replace(/{name}/g,name);
        template = template.replace(/{id}/g,id);
        template = template.replace(/{variant}/g,variant);
        template = template.replace(/{length}/g,qnt);
        template = template.replace(/{addMsg}/g,addMsg);
        template = template.replace(/{price}/g,price);
        template = template.replace(/{together}/g,together);

        return template;

    }

}

jQuery(function(){

    cart.startCart();

}); 

Como usar

Copie o código HTML e crie um arquivo separado, exemplo: elements/snippets/cart.html

Faça a chamada desse arquivo onde desejar:

{% element 'snippets/cart' %} 

Insira o bloco de código CSS em sua folha de estilo .css

Insira o bloco de código Javascript em seu arquivo .js

PreviousBotões QuantidadeNextExibir a segunda imagem ao passar o mouse

Last updated 1 year ago

Was this helpful?

OBS: o exemplo acima serve de base para criar o carrinho lateral mas não explica como adicionar o produto ao carrinho. Para isso acesse:

🧱
https://partners.tray.com.br/v/themes/construindo-seu-template/referencias/componentes/adicionar-ao-carrinho-sem-sair-da-pagina