Version 1
Version 1

Creating a Shopping Cart

You can use DataViewsJS to create a shopping cart layout.

To create a shopping cart layout, you need to design a series of pages that are programmatically linked, so data can be transferred, as the user moves from one page to another. You can use the calculation engine feature provided by DataViewsJS to create an effective and appealing shopping cart design.

Use the following steps to create a shopping cart design for a book store.

Sample Code

  1. Add the following references to the project.
<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/normalize.css@8.0.1/normalize.css" />
    <link href="css/bootstrap-snippet.min.css" rel="stylesheet" />
    <link href="css/gc.dataviews.core.min.css" rel="stylesheet" />
    <link href="css/gc.dataviews.grid.min.css" rel="stylesheet" />

    <script id="locale-loader" src="/dataviewsjs/demos/static/js/localeloader.js" type="text/javascript"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js" type="text/javascript"></script>
    <script src="scripts/gc.dataviews.common.min.js"></script>
    <script src="scripts/gc.dataviews.core.min.js"></script>
    <script src="scripts/gc.dataviews.grid.min.js"></script>
  </head>
</html>
  1. Add a style tag within the head tag to apply styling to the interface.
</head>
<style>
        .container {
            height: 900px;
            overflow: auto;
        }

        #grid {
            border: 0;
            float: left;
            height: 810px;
            width: 800px;
        }

        .gc-grid,
        .gc-cell {
            border: 0;
            text-overflow: clip;
        }

            .gc-grid .gc-cell-content,
            .gc-cell .gc-cell-content {
                white-space: normal;
            }

        .gc-cell-border {
            border: 0;
        }

        .gc-column-header-cell {
            background-color: transparent;
            color: inherit;
            font-weight: normal;
        }

        .c4,
        .c5 {
            text-align: center;
            justify-content: center;
        }

        /*product presentation:*/
        .product-item {
            display: inline-block;
            width: 400px;
        }

        .product-item-image {
            display: inline-block;
            text-align: center;
            vertical-align: middle;
            width: 120px;
        }

        .product-item-image-resize {
            border: solid 1px #e0e0e0;
            border-radius: 4px;
            height: 120px;
            padding: 0;
        }

        .product-item-details {
            display: inline-block;
            vertical-align: middle;
            width: 280px;
        }

        .product-price,
        .product-quantity {
            display: inline-block;
            text-align: center;
            vertical-align: middle;
            width: 100px;
        }

        .product-total {
            background: #f1f1f1;
            border: solid 1px #e0e0e0;
            border-radius: 4px;
            color: #777;
            display: inline-block;
            float: right;
            font-family: 'Roboto', sans-serif;
            font-weight: 300;
            margin-right: 1em;
            margin-top: 1em;
            padding: 1em;
            width: 25%;
        }

            .product-total .total-info {
                font-size: 16px;
                font-weight: bold;
            }

            .product-total .green {
                color: green;
            }

        @media only screen and (max-width: 768px) {
            .container {
                height: 420px;
            }

            #grid {
                float: none;
                width: 100%;
            }

            .product-total {
                float: none;
                width: 90%;
            }
        }
    </style>
    </head>
  1. Add the div tag within the body tag to include the DOM element as the container in the page.
<body class="theme-default">
  <template id="rowTmpl" style="display: none">
    <div class="gc-cell">
      <div class="product-item">
        <div data-column="productImage" class="product-item-image"></div>
        <div class="product-item-details">
          <div data-column="productTitle"></div>
        </div>
      </div>
      <div data-column="productPrice" class="product-price"></div>
      <div data-column="productSubtotal" class="product-subtotal"></div>
      <div class="product-quantity">
        <div data-column="productQuantity" class="product-quantity-number"></div>
      </div>
    </div>
  </template>
  <div class="container">
    <div id="grid"></div>
    <div id="total" class="product-total"></div>
  </div>
</body>
  1. Add the column definition.
var data = [
  {
    url: 'images/51j6OH4qYhL_SS100_.jpg',
    link: '//www.amazon.com/gp/product/1628600837/ref=ox_sc_act_title_1?ie=UTF8&psc=1&smid=ATVPDKIKX0DER',
    title:
      'Becoming a Supple Leopard 2nd Edition: The Ultimate Guide to Resolving Pain, Preventing Injury, and Optimizing Athletic Performance',
    price: 59.95,
    quantity: 1,
  },
  {
    url: 'images/41ophY78M2L_SS100_.jpg',
    link: '//www.amazon.com/gp/product/0062190377/ref=ox_sc_act_title_2?ie=UTF8&psc=1&smid=ATVPDKIKX0DER',
    title: 'Seveneves: A Novel',
    price: 35.0,
    quantity: 1,
  },
  {
    url: 'images/6195J3AhbdL_SL500_SY135_.jpg',
    link:
      '//www.amazon.com/The-Whole30-30-Day-Health-Freedom/dp/0544609719/ref=pd_cart_recs_2_2_p?ie=UTF8&refRID=0C2KPAAFEMW69ZXA0XBN',
    title: 'The whole 30: The 30 Days Guild to Total Healthy and Food Freedom',
    price: 30.0,
    quantity: 1,
  },
];
var locale = { total: 'Total', items: 'items', totalSavings: 'Total savings' };
var cols = [
  {
    id: 'productImage',
    caption: '',
    dataField: 'productImageUrl,productLink,productTitle',
    presenter: '<img class="product-item-image-resize" src="\{{=it.productImageUrl}}" alt="\{{=it.productTitle}}">',
  },
  {
    id: 'productTitle',
    caption: 'Title',
    dataField: 'title',
  },
  {
    id: 'productPrice',
    caption: 'Price',
    dataField: 'price',
    format: '$#,##0.00',
  },
  {
    id: 'productQuantity',
    caption: 'Quantity',
    dataField: 'quantity',
    presenter:
      '<input min="0" value="\{{=it.productQuantity}}" type="number" style="width:100%;" oninput="refreshQuantity(this)" />',
  },
  {
    id: 'productDelete',
    action: [
      {
        name: 'delete',
        presenter:
          '<div data-action = "delete" style = "background-color:red;color:white;width:80px;height:100%;position:relative"><span style = "position:absolute;left:30%;top:40%">Delete</span></div>',
        handler: deleteRow,
      },
    ],
    width: 80,
    swipeDirection: 'left',
  },
  {
    id: 'productSubtotal',
    caption: 'Subtotal',
    dataField: '=[productPrice] * [productQuantity]',
    visible: false,
  },
  {
    id: 'productImageUrl',
    visible: false,
    dataField: 'url',
  },
  {
    id: 'productLink',
    visible: false,
    dataField: 'link',
  },
  {
    id: 'discountThreshold',
    visible: false,
    dataField: 'discountThreshold',
  },
];
  1. Initialize the grid and specify the function to handle the calculation of items available in the shopping cart.
var layout = new GC.DataViews.GridLayout({
  rowHeight: 127,
  showRowHeader: false,
  allowColumnReorder: false,
  allowColumnResize: false,
  allowSwipe: true,
  colHeaderHeight: 24,
  rowTemplate: '#rowTmpl',
});
var dataView = new GC.DataViews.DataView(document.getElementById('grid'), data, cols, layout);
refreshTotalPrice(); // focus data.view by default

document.getElementById('grid').focus();

function refreshTotalPrice() {
  var formulaStringTotal = 'if(sum([productSubtotal]) > 199.99, sum([productSubtotal]) * 0.6, sum([productSubtotal]))';
  var formulaStringPrice = 'sum([productSubtotal])';
  var formulaStringQuantity = 'sum([productQuantity])';
  var total = dataView.data.evaluate(formulaStringTotal);
  var price = dataView.data.evaluate(formulaStringPrice);
  var saving = price - total;
  var quantity = dataView.data.evaluate(formulaStringQuantity);
  var totalPriceSpan = document.getElementById('total');
  var savingPercentage = price === 0 ? 0 : ((saving / price) * 100).toFixed(0);
  totalPriceSpan.innerHTML = '\n<div>\n    <span style="font-size: 16px; font-weight: bold">\n      <span>'
    .concat(locale.total, ' (')
    .concat(quantity, ' ')
    .concat(locale.items, '): </span>\n      <span style="color:green">$')
    .concat(total.toFixed(2), '</span>\n    </span>\n</div>\n<div>\n    <span>')
    .concat(locale.totalSavings, ': </span>\n    <span style="color:green">$')
    .concat(saving.toFixed(2), '</span>\n    ')
    .concat(price === 0 ? '' : '<span>('.concat(savingPercentage, '%)</span>'), '\n</div>');
}

function deleteRow(args) {
  var answer = confirm('Are you sure to delete row?');

  if (answer) {
    dataView.data.removeDataItems(args.hitInfo.row);
    dataView.invalidate();
    refreshTotalPrice();
  }

  args.closeActionColumnPanel();
}

window.refreshQuantity = function refreshQuantity(input) {
  var row = $(input).closest('.gc-row');
  var rowIndex = row[0].id.substr(''.concat(dataView.uid, '-r').length);
  var rowData = data[rowIndex];

  if (rowData) {
    rowData.quantity = input.value ? parseInt(input.value, 10) : 0;
    dataView.data.reCalculate();
    refreshTotalPrice();
  }
};