JSFiddle - React, Tailwind, and code Playground

by iamjpg

HTML

<button id="cart_button">
  Add £5 To Cart
</button>

<div id="price"></div>

JavaScript

// Define function which will be our Object
function cart(name) {

	// Define a name for cart. Default to 'Bob' if undefined.
	this.name = name || 'Bob';
  
  // addToCart method on object.
  this.addToCart = function(price) {
  	
    // If there is no total, set the total to zero.
    if (!this.total) {
      this.total = 0;
    }
    
    // Increment total by passed in price parameter
    this.total += price;
    
    // Return the string containing the total value.
    return this.name + '\'s cart total is £' + this.total;
  }
}

// Construct cart object
var cart = new cart('Mario');

// Set event listener on the button.
document.getElementById('cart_button').onclick = function() {
	
  // On each click, update the cart price incrementing by 5.
  document.getElementById('price').innerHTML = cart.addToCart(5);
}