Advertisement
Guest User

Untitled

a guest
Mar 11th, 2017
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.77 KB | None | 0 0
  1. /*
  2. * jQuery myCart - v1.1 - 2017-02-21
  3. * http://asraf-uddin-ahmed.github.io/
  4. * Copyright (c) 2017 Asraf Uddin Ahmed; Licensed None
  5. */
  6.  
  7. (function ($) {
  8.  
  9. "use strict";
  10.  
  11. var OptionManager = (function () {
  12. var objToReturn = {};
  13.  
  14. var defaultOptions = {
  15. currencySymbol: '$',
  16. classCartIcon: 'my-cart-icon',
  17. classCartBadge: 'my-cart-badge',
  18. classProductQuantity: 'my-product-quantity',
  19. classProductRemove: 'my-product-remove',
  20. classCheckoutCart: 'my-cart-checkout',
  21. affixCartIcon: true,
  22. showCheckoutModal: true,
  23. cartItems: [],
  24. clickOnAddToCart: function($addTocart) { },
  25. afterAddOnCart: function(products, totalPrice, totalQuantity) { },
  26. clickOnCartIcon: function($cartIcon, products, totalPrice, totalQuantity) { },
  27. checkoutCart: function(products, totalPrice, totalQuantity) { },
  28. getDiscountPrice: function(products, totalPrice, totalQuantity) { return null; }
  29. };
  30.  
  31.  
  32. var getOptions = function (customOptions) {
  33. var options = $.extend({}, defaultOptions);
  34. if (typeof customOptions === 'object') {
  35. $.extend(options, customOptions);
  36. }
  37. return options;
  38. }
  39.  
  40. objToReturn.getOptions = getOptions;
  41. return objToReturn;
  42. }());
  43.  
  44.  
  45. var ProductManager = (function(){
  46. var objToReturn = {};
  47.  
  48. /*
  49. PRIVATE
  50. */
  51. localStorage.products = localStorage.products ? localStorage.products : "";
  52. var getIndexOfProduct = function(id){
  53. var productIndex = -1;
  54. var products = getAllProducts();
  55. $.each(products, function(index, value){
  56. if(value.id == id){
  57. productIndex = index;
  58. return;
  59. }
  60. });
  61. return productIndex;
  62. }
  63. var setAllProducts = function(products){
  64. localStorage.products = JSON.stringify(products);
  65. }
  66. var addProduct = function(id, name, summary, price, quantity, image) {
  67. var products = getAllProducts();
  68. products.push({
  69. id: id,
  70. name: name,
  71. summary: summary,
  72. price: price,
  73. quantity: quantity,
  74. image: image
  75. });
  76. setAllProducts(products);
  77. }
  78.  
  79. /*
  80. PUBLIC
  81. */
  82. var getAllProducts = function(){
  83. try {
  84. var products = JSON.parse(localStorage.products);
  85. return products;
  86. } catch (e) {
  87. return [];
  88. }
  89. }
  90. var updatePoduct = function(id, quantity) {
  91. var productIndex = getIndexOfProduct(id);
  92. if(productIndex < 0){
  93. return false;
  94. }
  95. var products = getAllProducts();
  96. products[productIndex].quantity = typeof quantity === "undefined" ? products[productIndex].quantity * 1 + 1 : quantity;
  97. setAllProducts(products);
  98. return true;
  99. }
  100. var setProduct = function(id, name, summary, price, quantity, image) {
  101. if(typeof id === "undefined"){
  102. console.error("id required")
  103. return false;
  104. }
  105. if(typeof name === "undefined"){
  106. console.error("name required")
  107. return false;
  108. }
  109. if(typeof image === "undefined"){
  110. console.error("image required")
  111. return false;
  112. }
  113. if(!$.isNumeric(price)){
  114. console.error("price is not a number")
  115. return false;
  116. }
  117. if(!$.isNumeric(quantity)) {
  118. console.error("quantity is not a number");
  119. return false;
  120. }
  121. summary = typeof summary === "undefined" ? "" : summary;
  122.  
  123. if(!updatePoduct(id)){
  124. addProduct(id, name, summary, price, quantity, image);
  125. }
  126. }
  127. var clearProduct = function(){
  128. setAllProducts([]);
  129. }
  130. var removeProduct = function(id){
  131. var products = getAllProducts();
  132. products = $.grep(products, function(value, index) {
  133. return value.id != id;
  134. });
  135. setAllProducts(products);
  136. }
  137. var getTotalQuantity = function(){
  138. var total = 0;
  139. var products = getAllProducts();
  140. $.each(products, function(index, value){
  141. total += value.quantity * 1;
  142. });
  143. return total;
  144. }
  145. var getTotalPrice = function(){
  146. var products = getAllProducts();
  147. var total = 0;
  148. $.each(products, function(index, value){
  149. total += value.quantity * value.price;
  150. });
  151. return total;
  152. }
  153.  
  154. objToReturn.getAllProducts = getAllProducts;
  155. objToReturn.updatePoduct = updatePoduct;
  156. objToReturn.setProduct = setProduct;
  157. objToReturn.clearProduct = clearProduct;
  158. objToReturn.removeProduct = removeProduct;
  159. objToReturn.getTotalQuantity = getTotalQuantity;
  160. objToReturn.getTotalPrice = getTotalPrice;
  161. return objToReturn;
  162. }());
  163.  
  164.  
  165. var loadMyCartEvent = function(userOptions){
  166.  
  167. var options = OptionManager.getOptions(userOptions);
  168. var $cartIcon = $("." + options.classCartIcon);
  169. var $cartBadge = $("." + options.classCartBadge);
  170. var classProductQuantity = options.classProductQuantity;
  171. var classProductRemove = options.classProductRemove;
  172. var classCheckoutCart = options.classCheckoutCart;
  173.  
  174. var idCartModal = 'my-cart-modal';
  175. var idCartTable = 'my-cart-table';
  176. var idGrandTotal = 'my-cart-grand-total';
  177. var idEmptyCartMessage = 'my-cart-empty-message';
  178. var idDiscountPrice = 'my-cart-discount-price';
  179. var classProductTotal = 'my-product-total';
  180. var classAffixMyCartIcon = 'my-cart-icon-affix';
  181.  
  182.  
  183. if(userOptions.cartItems && userOptions.cartItems.constructor === Array) {
  184. ProductManager.clearProduct();
  185. $.each(options.cartItems, function() {
  186. ProductManager.setProduct(this.id, this.name, this.summary, this.price, this.quantity, this.image);
  187. });
  188. }
  189.  
  190. $cartBadge.text(ProductManager.getTotalQuantity());
  191.  
  192. if(!$("#" + idCartModal).length) {
  193. $('body').append(
  194. '<div class="modal fade" id="' + idCartModal + '" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">' +
  195. '<div class="modal-dialog" role="document">' +
  196. '<div class="modal-content">' +
  197. '<div class="modal-header">' +
  198. '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
  199. '<h4 class="modal-title" id="myModalLabel"><span class="glyphicon glyphicon-shopping-cart"></span> My Cart</h4>' +
  200. '</div>' +
  201. '<div class="modal-body">' +
  202. '<table class="table table-hover table-responsive" id="' + idCartTable + '"></table>' +
  203. '</div>' +
  204. '<div class="modal-footer">' +
  205. '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>' +
  206. '<button type="button" class="btn btn-primary ' + classCheckoutCart + '">Checkout</button>' +
  207. '</div>' +
  208. '</div>' +
  209. '</div>' +
  210. '</div>'
  211. );
  212. }
  213.  
  214. var drawTable = function(){
  215. var $cartTable = $("#" + idCartTable);
  216. $cartTable.empty();
  217.  
  218. var products = ProductManager.getAllProducts();
  219. $.each(products, function(){
  220. var total = this.quantity * this.price;
  221. $cartTable.append(
  222. '<tr title="' + this.summary + '" data-id="' + this.id + '" data-price="' + this.price + '">' +
  223. '<td class="text-center" style="width: 30px;"><img width="30px" height="30px" src="' + this.image + '"/></td>' +
  224. '<td>' + this.name + '</td>' +
  225. '<td title="Unit Price">' + options.currencySymbol + this.price + '</td>' +
  226. '<td title="Quantity"><input type="number" min="1" style="width: 70px;" class="' + classProductQuantity + '" value="' + this.quantity + '"/></td>' +
  227. '<td title="Total" class="' + classProductTotal + '">' + options.currencySymbol + total + '</td>' +
  228. '<td title="Remove from Cart" class="text-center" style="width: 30px;"><a href="javascript:void(0);" class="btn btn-xs btn-danger ' + classProductRemove + '">X</a></td>' +
  229. '</tr>'
  230. );
  231. });
  232.  
  233. $cartTable.append(products.length ?
  234. '<tr>' +
  235. '<td></td>' +
  236. '<td><strong>Total</strong></td>' +
  237. '<td></td>' +
  238. '<td></td>' +
  239. '<td><strong id="' + idGrandTotal + '"></strong></td>' +
  240. '<td></td>' +
  241. '</tr>'
  242. : '<div class="alert alert-danger" role="alert" id="' + idEmptyCartMessage + '">Your cart is empty</div>'
  243. );
  244.  
  245. var discountPrice = options.getDiscountPrice(products, ProductManager.getTotalPrice(), ProductManager.getTotalQuantity());
  246. if(products.length && discountPrice !== null) {
  247. $cartTable.append(
  248. '<tr style="color: red">' +
  249. '<td></td>' +
  250. '<td><strong>Total (including discount)</strong></td>' +
  251. '<td></td>' +
  252. '<td></td>' +
  253. '<td><strong id="' + idDiscountPrice + '"></strong></td>' +
  254. '<td></td>' +
  255. '</tr>'
  256. );
  257. }
  258.  
  259. showGrandTotal();
  260. showDiscountPrice();
  261. }
  262. var showModal = function(){
  263. drawTable();
  264. $("#" + idCartModal).modal('show');
  265. }
  266. var updateCart = function(){
  267. $.each($("." + classProductQuantity), function(){
  268. var id = $(this).closest("tr").data("id");
  269. ProductManager.updatePoduct(id, $(this).val());
  270. });
  271. }
  272. var showGrandTotal = function(){
  273. $("#" + idGrandTotal).text(options.currencySymbol + ProductManager.getTotalPrice());
  274. }
  275. var showDiscountPrice = function(){
  276. $("#" + idDiscountPrice).text(options.currencySymbol + options.getDiscountPrice(ProductManager.getAllProducts(), ProductManager.getTotalPrice(), ProductManager.getTotalQuantity()));
  277. }
  278.  
  279. /*
  280. EVENT
  281. */
  282. if(options.affixCartIcon) {
  283. var cartIconBottom = $cartIcon.offset().top * 1 + $cartIcon.css("height").match(/\d+/) * 1;
  284. var cartIconPosition = $cartIcon.css('position');
  285. $(window).scroll(function () {
  286. $(window).scrollTop() >= cartIconBottom ? $cartIcon.addClass(classAffixMyCartIcon) : $cartIcon.removeClass(classAffixMyCartIcon);
  287. });
  288. }
  289.  
  290. $cartIcon.click(function(){
  291. options.showCheckoutModal ? showModal() : options.clickOnCartIcon($cartIcon, ProductManager.getAllProducts(), ProductManager.getTotalPrice(), ProductManager.getTotalQuantity());
  292. });
  293.  
  294. $(document).on("input", "." + classProductQuantity, function () {
  295. var price = $(this).closest("tr").data("price");
  296. var id = $(this).closest("tr").data("id");
  297. var quantity = $(this).val();
  298.  
  299. $(this).parent("td").next("." + classProductTotal).text("$" + price * quantity);
  300. ProductManager.updatePoduct(id, quantity);
  301.  
  302. $cartBadge.text(ProductManager.getTotalQuantity());
  303. showGrandTotal();
  304. showDiscountPrice();
  305. });
  306.  
  307. $(document).on('keypress', "." + classProductQuantity, function(evt){
  308. if(evt.keyCode == 38 || evt.keyCode == 40){
  309. return ;
  310. }
  311. evt.preventDefault();
  312. });
  313.  
  314. $(document).on('click', "." + classProductRemove, function(){
  315. var $tr = $(this).closest("tr");
  316. var id = $tr.data("id");
  317. $tr.hide(500, function(){
  318. ProductManager.removeProduct(id);
  319. drawTable();
  320. $cartBadge.text(ProductManager.getTotalQuantity());
  321. });
  322. });
  323.  
  324. $("." + classCheckoutCart).click(function(){
  325. var products = ProductManager.getAllProducts();
  326. if(!products.length) {
  327. $("#" + idEmptyCartMessage).fadeTo('fast', 0.5).fadeTo('fast', 1.0);
  328. return ;
  329. }
  330. updateCart();
  331. options.checkoutCart(ProductManager.getAllProducts(), ProductManager.getTotalPrice(), ProductManager.getTotalQuantity());
  332. ProductManager.clearProduct();
  333. $cartBadge.text(ProductManager.getTotalQuantity());
  334. $("#" + idCartModal).modal("hide");
  335. });
  336.  
  337. }
  338.  
  339.  
  340. var MyCart = function (target, userOptions) {
  341. /*
  342. PRIVATE
  343. */
  344. var $target = $(target);
  345. var options = OptionManager.getOptions(userOptions);
  346. var $cartIcon = $("." + options.classCartIcon);
  347. var $cartBadge = $("." + options.classCartBadge);
  348.  
  349. /*
  350. EVENT
  351. */
  352. $target.click(function(){
  353. options.clickOnAddToCart($target);
  354.  
  355. var id = $target.data('id');
  356. var name = $target.data('name');
  357. var summary = $target.data('summary');
  358. var price = $target.data('price');
  359. var quantity = $target.data('quantity');
  360. var image = $target.data('image');
  361. ProductManager.setProduct(id, name, summary, price, quantity, image);
  362. $cartBadge.text(ProductManager.getTotalQuantity());
  363.  
  364. options.afterAddOnCart(ProductManager.getAllProducts(), ProductManager.getTotalPrice(), ProductManager.getTotalQuantity());
  365. });
  366.  
  367. }
  368.  
  369.  
  370. $.fn.myCart = function (userOptions) {
  371. loadMyCartEvent(userOptions);
  372. return $.each(this, function () {
  373. new MyCart(this, userOptions);
  374. });
  375. }
  376.  
  377.  
  378. })(jQuery);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement