Skip to content

Instantly share code, notes, and snippets.

@acidtone
Last active October 13, 2021 14:48
Show Gist options
  • Save acidtone/37a879d3777bc123483d582248eded90 to your computer and use it in GitHub Desktop.
Save acidtone/37a879d3777bc123483d582248eded90 to your computer and use it in GitHub Desktop.
JS Activity: Eat and drink click handlers

JS Activity: Eat and Drink click handlers

In this activity, you will complete the following app so that clicking each button will deduct the proper amount from the Account Balance.

See this simple click handler for example code.

Instructions

  1. Download or fork/clone this Gist into your workspace. Alternatively, you can fork this Codepen.
  2. Using document.querySelector create Element variables for each button displayed on the page.
  3. Define a separate function for each of the actions listed in eat-drink.js, moving the relevant code into each respective function:
    • Drink beer -> drinkBeer()
    • Eat burger -> eatBurger()
    • Drink pop -> drinkPop()
  4. Using Element.addEventListener(), add a click listener to each button so that the proper function is invoked when the button is clicked.
  5. Finally, refactor the code so that each console.log() instead displays the proper balance to outputBalance.

Attributions

// Set prices
const beerCost = 6.25;
const burgerCost = 4.75;
const popCost = 3.00;
// Define and output account balance
let accountBalance = 15.75;
const outputBalance = document.querySelector('.balance');
outputBalance.textContent = accountBalance.toFixed(2);
// Drink beer
accountBalance = accountBalance - beerCost;
console.log(accountBalance);
// Eat burger
accountBalance = accountBalance - burgerCost;
console.log(accountBalance);
// Drink pop
accountBalance = accountBalance - popCost;
console.log(accountBalance);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Eat and Drink</title>
<script src="eat-drink.js" defer></script>
<style>
body {
font-size: 32px;
text-align: center;
}
.wrapper {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
place-items: center;
}
button {
font-size: 2rem;
margin: 2em;
padding: 1rem;
}
p {
grid-column: span 3;
}
</style>
</head>
<body>
<p>Balance: $<span class="balance"></span></p>
<div class="wrapper">
<button class="drink-beer">Drink Beer</button>
<button class="eat-burger">Eat Burger</button>
<button class="drink-pop">Drink Pop</button>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment