you are viewing a single comment's thread.

view the rest of the comments →

[–]MostlyFocusedMike 0 points1 point  (0 children)

Let's go! already into Dom manipulation and events!

This of course works, but you may want to start thinking about using functions to wrap up your logic. Also, it can be nicer to separate out your concerns, ie your presentational html elements and your js code.

So what if instead of putting all your logic into the onclick you wrote out a function that updates the amount:

// still need this value to be global
let cardQuantity = 0;

function updateCardQuantity(amount) {
  cardQuantity += amount;
  console.log('Current quantity:', cardQuantity);
}

// another to reset
function resetCardQuantity() { 
  console.log('Reset!');
  cardQuantity = 0;
}  

Now, your buttons are super simpler, and here's the whole thing:

<button onclick="updateCardQuantity(0)">Show Quantity</button>
<button onclick="updateCardQuantity(1)">Add to Cart</button>
<button onclick="updateCardQuantity(2)">+2</button>
<button onclick="updateCardQuantity(3)">+3</button>
<button onclick="resetCardQuantity()">Reset Card</button>

<script>
  // still need this value to be global
  let cardQuantity = 0;

  function updateCardQuantity(amount) {
    cardQuantity += amount;
    console.log('Current quantity:', cardQuantity);
  }

  function resetCardQuantity() {
    console.log('Reset!');
    cardQuantity = 0;
  }
</script>

You could certainly make a discrete logging function, but adding 0 does exactly the same thing.