JavaScript Essential Training

LinkedIn Learning : Morten Rand-Hendriksen

Code Samples

Code Sample 1

This is the code example for 04_01 in the exercise files. The HTML file shown below is our starting point.

The HTML Document - Start

	<!DOCTYPE html>
	<html lang="en">
	  <head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>String output</title>
		<script type="module" src="Backpack.js"></script>
		<script type="module" src="script.js"></script>
	  </head>
	  <body>
		<main>
		  <article>
			<h1>Everyday Backpack</h1>
			<ul>
			  <li>Volume:</li>
			  <li>Color:</li>
			  <li>Age:</li>
			  <li>Number of pockets:</li>
			  <li>Left strap length:</li>
			  <li>Right strap length:</li>
			  <li>Lid status:</li>
			</ul>
		  </article>
		</main>
	  </body>
	</html>

The HTML in the body is removed because we want the JavaScript file to add this content using a template literal. This will allow us to add in some JavaScript expressions so that we can get the values of each property directly from a backpack object and display these along with the property names.

The HTML Document - Finish

	<!DOCTYPE html>
	<html lang="en">
	  <head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>String output</title>
		<script type="module" src="Backpack.js"></script>
		<script type="module" src="script.js"></script>
	  </head>
	  <body>
	  </body>
	</html>

The only difference between these two HTML files is that in the second version, there is no HTML in the body.

The JavaScript file

	/**
	 * Use template literals to output HTML
	 * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
	 *
	 */
	// import { doc } from "prettier";
	import Backpack from "./Backpack.js";

	const everydayPack = new Backpack(
	  "Everyday Backpack",
	  30,
	  "grey",
	  15,
	  26,
	  26,
	  false,
	  "December 5, 2018 15:00:00 PST"
	);

	const content = `
	  <main>
	  <article>
		<h1>${everydayPack.name}</h1>
		<ul>
		  <li>Volume: ${everydayPack.volume}</li>
		  <li>Color: ${everydayPack.color}</li>
		  <li>Age: ${everydayPack.backpackAge()}</li>
		  <li>Number of pockets: ${everydayPack.pocketNum}</li>
		  <li>Left strap length: ${everydayPack.strapLength.left}</li>
		  <li>Right strap length: ${everydayPack.strapLength.right}</li>
		  <li>Lid status: ${everydayPack.lidOpen}</li>
		</ul>
	  </article>
	  </main>
	`;

	document.body.innerHTML = content;

Just a note on this, the line importing doc from prettier was enabled in the code from the exercise files, but it was giving me an error so I disabled it and this seems to have fixed the problem without causing any additional problems as far as I can tell.