9/2/2017 - 2:00 PM

jQuery sandwich counter example: document ready function / on click events /

jQuery sandwich counter example: document ready function / on click events /

<!DOCTYPE html>
<html lang="en">

	<meta charset="UTF-8">
	<title>Trigger Clicked</title>

	<!-- Added link to the jQuery Library -->
	<script src=""></script>



	<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() {

    // ====================================================================

      // 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.");
        alert("You've eaten " + pbjCounter + " PB&J sandwiches");

        // BONUS
        $("#image-div").html("<img id='PBJ' src=''/>");

      $("#grilledcheese").on("click", function() {
        alert("Nom nom nom. Gooey Gooey Grilled Cheese!");
        alert("You've eaten " + grilledCheeseCounter + " grilled cheese sandwiches");
        // BONUS
        $("#image-div").html("<img id='Grilled Cheese' src='' />");

      $("#roastbeef").on("click", function() {
        alert("No qualms about animal rights here. I'm all about that roast beef.");
        alert("You've eaten " + roastBeefCounter + " roast beef sandwiches");

        // BONUS
        $("#image-div").html("<img id='Roast Beef' src='' />");