JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<section id="items">
<h1>Items for Sale</h1>
</section>
<section id="basket">
<h1>Basket</h1>
</section>
</body>
JavaScript
var shop = {};
shop.items = [];
shop.Item = function(id, item, description, price) {
this.id = id;
this.item = item;
this.description = description;
this.price = price;
};
shop.items.push(new shop.Item("1", "Coat", "Warm", "20"));
shop.items.push(new shop.Item("2", "Hat", "Warm", "20"));
shop.items.push(new shop.Item("3", "Cap", "Warm", "20"));
shop.items.push(new shop.Item("4", "Robe", "Warm", "20"));
shop.print = function() {
var itemCon = document.getElementById('items'),
html = "";
for(var i = 0; i < this.items.length; i++) {
html += '<div id="item">';
for(prop in this.items[i]) {
if(prop != "id") {
html += '<p><span class="title">' + prop + '</span>: ' + this.items[i][prop] + '</p>';
};
};
html += '<button class="addButton" data-id="' + this.items[i].id + '">Add to Basket</button>'
html += '</div>';
};
itemCon.innerHTML += html;
};
var basket = {};
basket.items = [];
basket.Item = function(item, description, price) {
this.item = item;
this.description = description;
this.price = price;
};
basket.clickHandler = function(){
var targets = document.getElementsByClassName("addButton");
for(var i = 0; i < targets.length; i++) {
var target = targets[i];
target.onclick = function() {
var shopId = target.getAttribute("data-id");
var item = shop.items[shopId];
basket.add(item);
};
};
};
basket.add = function(item) {
basket.items.push(item);
basket.print();
};
basket.costCalculate = function() {
var cost = 0,
html = "Total: " + cost;
for(var i = 0; i < this.items.length; i++) {
cost += items[i].price;
};
return html;
};
basket.print = function() {
var output;
for(var i = 0; i < this.items.length; i++) {
for(prop in this.items[i]) {
if(prop != "id") {
console.log(prop + ": " +...