jQuery sandwich counter example: document ready function / on click events /
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Trigger Clicked</title>
<!-- Added link to the jQuery Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<h1>Click to Eat Sandwich</h1>
<h3 id="pbj">Peanut Butter Jelly</h3>
<h3 id="grilledcheese">Grilled Cheese</h3>
<h3 id="roastbeef">Roast Beef</h3>
<div id="image-div"></div>
<script type="text/javascript">
// This document.ready isn't necessary in this example... but is needed in cases where the HTML is complex.
// This code makes sure that the JavaScript doesn't get run until the HTML is finished loading
// It's useful to become familiar with now.
$(document).ready(function() {
// VARIABLES
// ====================================================================
// Here we create variables for tracking the number of sandwiches eaten
var pbjCounter = 0;
var grilledCheeseCounter = 0;
var roastBeefCounter = 0;
// FUNCTIONS
// ====================================================================
// Here we create various "on click" events which capture clicks
// Inside each click event is the code to create an alert, update the counter, and show the updated count.
$("#pbj").on("click", function() {
alert("Mmm... Peanut Butter Jelly Time.");
pbjCounter++;
alert("You've eaten " + pbjCounter + " PB&J sandwiches");
// BONUS
$("#image-div").html("<img id='PBJ' src='http://allthingsd.com/files/2012/08/peanut_butter_jelly430x300.jpeg'/>");
});
$("#grilledcheese").on("click", function() {
alert("Nom nom nom. Gooey Gooey Grilled Cheese!");
grilledCheeseCounter++;
alert("You've eaten " + grilledCheeseCounter + " grilled cheese sandwiches");
// BONUS
$("#image-div").html("<img id='Grilled Cheese' src='http://cdn.funcheap.com/wp-content/uploads/2014/04/The-Perfect-Grilled-Cheese-Sandwich-800-158111.jpg' />");
});
$("#roastbeef").on("click", function() {
alert("No qualms about animal rights here. I'm all about that roast beef.");
roastBeefCounter++;
alert("You've eaten " + roastBeefCounter + " roast beef sandwiches");
// BONUS
$("#image-div").html("<img id='Roast Beef' src='https://www.cscassets.com/recipes/wide_cknew/wide_25336.jpg' />");
});
});
</script>
</body>
</html>