5

Diving into Web Development

In this chapter, we’ll learn about a development environment built into every web browser that students can jump right into and use to begin executing code within moments. This tool requires no development environment setup and no need to install new software, and will deeply engage students with software code using a single keystroke. Just like when learning a foreign language, the quickest way to learn code is to immerse ourselves in it.

Developing in the Web Browser

We’ll jump right into web development. To get the most from this chapter, it’s best to follow along with the steps provided. These are the same steps your students will follow in class over several lessons. As you move through the steps, think about how you might tailor the content to your students’ specific needs.

For simplicity, this book uses the Google Chrome browser running on the Windows operating system. But every web browser now has web development tools that are very similar to one another, and the steps outlined here should be available in other browsers and operating systems. The only potential roadblock you might encounter is your organization’s computer policies. If you’re using a school computer, access to the web development tools might be disabled as a group policy, but personal computers will allow you to access them. Work with your organization’s technical support department to access these valuable tools if they’re blocked within your organization.

Open your web browser and navigate to any web page. This book uses Wikipedia, but any site should work. Press F12. A new window opens, which looks similar to Figure 5-1. In this screenshot, the tools are docked to the browser for illustrative purposes, but making them free-floating is often a more convenient option.

Figure 5-1: Web development tools

Figure 5-1 shows four main areas. At the top of the figure is the browser window , which is the web page we’re analyzing. Below the browser window are the elements of the page , the markup language from which the page is rendered—a type of source code. The elements currently selected have various properties . At the bottom of the figure is the console , which displays information useful to the web developer.

Before going any further, take a few moments to have students reflect on what they think about this interface. Ask them how they feel when confronted with this screen. Do they feel frustrated? Intimidated? Excited? How would they learn about this software on their own? Would they click around and play with it? Is there built-in help? If so, how does that feature compare to search engine results about it? Have students examine their thinking at this time and document it in a few sentences so they can empathize with the users who will one day be confronted with software the students might create.

In a sense, you’ve just thrown your students into a pool’s deep end. As mentioned earlier, these complex panels are known as web development tools, and they’re the same tools software engineers use when writing and debugging web applications. With these tools, your students are accessing the client-side code that makes up the web page. Work with them to analyze it, step through it, and even manipulate it.

These powerful tools are built into every web browser, and as intimidating as they appear, whatever your students do will be completely safe. Students will only be experimenting with the code on their local computers. They’ll have the freedom to click around, explore different menu options, and try to break features as much as they like. Just as board games provide a magic circle for experimenting with ideas, web development tools provide a safe space for experimenting with code. Give your students some time to just explore and play with this browser feature on their own before moving on to more directed content. So many wow factors exist in these tools. Allowing students the excitement of self-discovery and time to share with their peers can improve their engagement going forward. It’s also exciting for the teacher to see their students leaning forward into the content on their own.

Document Object Model Inspector

Once your students have explored the interface and learned about it on their own, provide a more formal lesson on how to use the web development tools. Specifically, they will learn about the Document Object Model (DOM) for web pages, which is the hierarchy of elements with which they may interact. To facilitate this, we will introduce them to the DOM Inspector within the web development tools, which will allow them to navigate and manipulate these elements.

We’ll begin by launching the DOM Inspector. If necessary, undock this suite of tools and move the window over to one side of the desktop and the browser to the other side so you can see both windows at once. In the elements panel, move your mouse over the hypertext markup language (HTML), which describes the web page’s structure. HTML is composed of tags that define a web document’s elements. Each element on a page has an opening and closing tag. For example, in the markup <p>This is a paragraph.</p> , the <p> is the opening paragraph tag, the </p> is the closing tag, and This is a ­paragraph. is the inner HTML content of the element. Many different tags define elements in a web page, including <video></video>, <blockquote></blockquote>, and <table></table, to name a few.

Parts of the web page will become highlighted as you move the mouse up and down the HTML. What you’re seeing is which HTML elements refer to which objects on the web page. For example, hovering the mouse over an h1 tag will usually highlight the title of the page. Alternatively, if you right-click a specific part of the page in the browser window, a pop-up menu will appear. Select Inspect or Inspect Element from the menu and the web development tools will highlight the part of the source code referring to that part of the page.

The DOM consists of many nested nodes organized hierarchically in a tree structure. In the elements panel, you can click the arrows to the left of nodes to expand them and see their contents or collapse them for a simpler view. Figure 5-2 provides a high-level view of this document hierarchy.

Figure 5-2: DOM hierarchy

All web pages use this organizational structure. Starting with the root <html> node, the document branches into the <head> node where the document properties like title, search terms, and programming code reside. The document also branches into the <body> node where the web page content like text, images, and videos resides. Show your students the tree structure in Figure 5-2. Then show them the sample markup in Listing 5-1 to see how the tree looks in an actual script.

<html>
  <head>
    <title>Hello, World Website</title>
  </head>
  <body>
    <p>Hello, World!</p>
  </body>
</html>

Listing 5-1: Basic HTML structure

In this very elementary example, the script is indented deeper for each level the tree descends. Have your students explore how elements are nested in various websites to find and become familiar with these basic DOM elements. Understanding the DOM as a tree structure can provide your students with a map for navigating the HTML and will be especially useful when they’re writing code that manipulates it.

But the real wow factor is the DOM Inspector. Try inspecting the headline of the Wikipedia article and then double-click the text in the elements panel. It should become editable (if not, try right-clicking the text and selecting Edit or Edit as HTML from the options). Make some changes to the text and then look at your browser to see your handiwork. In Figure 5-3, the Wikipedia article’s h1 tag is edited to a mnemonic for remembering biological taxonomies. You can see the edit in the elements panel and the result in the browser window.

This is a playful hack—a clever technical trick that should impress your students. You haven’t edited the actual website on the server, only its presentation in your client browser. If you want to see the web page as it still appears to everyone else on the web, simply refresh the page to wipe away your changes.

Figure 5-3: DOM manipulation

Now look at the properties panel where the current tab should read Styles. This panel displays the Cascading Style Sheet (CSS) definitions for whatever you’ve selected in the elements panel. CSS describes how elements in the DOM should appear, using attributes such as font-family, font-size, color, alignment, and so forth.

As with the elements panel, you can edit these CSS definitions and see how the edits affect the page’s appearance. For example, when you scroll through the many definitions in the Styles tab, you’ll likely find one labeled background-color followed by a value like #000000, black, or rgb(0,0,0). Change that value to something else, such as red, blue, or even lemonchiffon. The DOM Inspector will give you suggestions, as shown in Figure 5-4.

Figure 5-4: Suggested valid color values in the Styles tab

If there is no background-color attribute, you can scroll down to travel up the node hierarchy until you find the html, body definition. Like the color suggestions, the DOM Inspector will also give you attribute suggestions so you can add a new background definition. Tinker with the styles on a few pages to become familiar with some of the many available styling options.

The elements panel displays the web page’s DOM: the document’s content in HTML. The CSS on the Styles tab defines how that content is laid out and appears. The content and styling are separated or decoupled. Decoupling the style from the content makes the content easier for developers to maintain and easier for machines, such as search engine web crawlers, to read. Once you and your students feel comfortable with the DOM’s content and design aspects, you can move on to programming code to begin manipulating the DOM in more dynamic ways.

The Console

Although playing with the DOM Inspector is fun for learning about and manipulating websites, you’re only minimally engaging with programming concepts and computational thinking. HTML and CSS aren’t programming languages. They’re markup languages, syntax that defines and structures data that the browser reads and translates into a website. But we need to understand the structure and rules of this medium before we can start manipulating it with programming code.

Let’s look at the web development tools in the console. This area of the tool is where the browser will report errors and information about the web page. It might report errors in the website code or inform the developer that a feature referenced in the web page script is being phased out, or deprecated, in a future release.

The console also provides instant access to a simple coding environment. Here we can run simple lines of code with inputs and see their outputs. Web developers use this feature to check the values of variables or other states as they run in the page.

In your console, enter the highly cryptic code in Listing 5-2 and press enter to execute it.

> for(i=0;++i<101;console.log(i%5?f||i:f+'Buzz'))f=i%3?'':'Fizz'

Listing 5-2: A JavaScript one-liner for the FizzBuzz game

This is very dense code, but if you entered it correctly, the console should output the numbers 1 through 100, replacing each number divisible by three with “Fizz,” numbers divisible by five with “Buzz,” and numbers divisible by three and five with “FizzBuzz.” This models the classic classroom game FizzBuzz in which students sit in a circle and count upward, replacing numbers divisible by three and five with the words “Fizz” and “Buzz” respectively.

Programming FizzBuzz from scratch is also a common interview question. The example in Listing 5-2 uses multiple syntax tricks to condense the program into a single line to impress interviewers, and we use it for ease of execution in the web console, but the code is unreadable as a result. Other programmers who encounter this code would have a hard time deciphering what it does. Listing 5-3 shows what this code might look like in a more readable format.

for(i = 0; i < 101; ++i) {
  var out = i + ' ';
  if (i%3 == 0) out += 'Fizz';
  if (i%5 == 0) out += 'Buzz';
  console.log(out);
}

Listing 5-3: FizzBuzz in a more human-friendly format

To execute the code in Listing 5-3, first type it into a text editor, like Notepad or TextEdit, and then copy and paste it into the console. By doing so, you can save your code snippets to a text file where you can modify and extend them later. Using this technique, you can also execute the code samples provided in Chapter 4, such as the Snakes and Ladders example.

With the console, students can instantly begin experimenting with a core programming language in web development. JavaScript is a safe language, which means working with JavaScript in the web development tools is entirely done on the client side. Client-side code executes in the browser, not the server hosting the JavaScript code. Running in the client browser, JavaScript can’t execute any malicious operations. It can’t write or erase files, or otherwise harm the client.

Being a primarily client-side programming language, JavaScript has many functions that relate to the DOM and allow you to reference nodes in the DOM’s tree structure. When students know that the document root node branches off into the head and body nodes, they can reference these nodes in JavaScript by using document.head and document.body. From either of these nodes, they can reference nodes and properties further down the chain. For example, try executing the code in Listing 5-3. The innerHTML portion references the content between the two <body> tags:

> document.body.innerHTML = 'Hello, World!';

Listing 5-3: A line of code that replaces a web page

When you press enter after entering this line of code to execute it, the entire web page you’re viewing vanishes. In its place, students will simply see the words “Hello, World!” You might get some surprised reactions when your students see what they too can do.

With JavaScript code, you can modify the content of the page programmatically. Listing 5-4 provides another example. The document.body.style portion allows you to modify the body node’s CSS properties. This line of code changes the body background color to blue if you execute it in the console:

> document.body.style.backgroundColor = 'blue';

Listing 5-4: A line of code that changes the body background color

Notice the capitalization that Listing 5-3 and Listing 5-4 use. Specifically, note that innerHTML and backgroundColor are defined in camel-case capitalization: the first letter of each word is capitalized so the variable name has humps like a camel’s back. JavaScript is a case-sensitive language, so it will treat a variable named camelCase and a variable named CamelCase as two different variables. Capitalization is important, so if your code isn’t working, check to make sure you have this right.

As your students enter code into the console, they’ll see lists of suggestions for nodes and functions they can access at each point in the chain. This feature is known as intelligent code completion and is available in many coding environments. These suggestions help you quickly write syntactically correct code. If you type document.body.on in the console, code completion will provide you with a list of event listeners. These listeners are functions that trigger when the user interacts with the page in specific ways pertaining to the node, such as those in Figure 5-7.

Figure 5-7: Intelligent code completion

With the line of code in Listing 5-5, you can set an event listener on the body so an alert message pops up when the user clicks anywhere on the page.

> document.body.onclick = function() { alert('THAT TICKLES!'); }

Listing 5-5: Set an alert message to pop up when the user clicks the page.

If you sequentially execute the code in Listings 5-3, 5-4, and 5-5, you should be able to erase almost any website and replace it with a blue page that displays Hello, World! and pops up an alert showing THAT TICKLES! whenever the user clicks it. This is a good place to draw your students’ attention back to the elements panel in the web development tools. There they’ll find that the changes they’ve made programmatically are reflected in the HTML, the Styles tab, and the Event Listeners tab. The tools reflect the current state of the page. If students right-click the page and select View Source or View Page Source, they’ll see the markup and code of the page’s initial state before it was modified. It’s best to make students aware of this so they know that what they see in the web development tools is often not the web page’s initial source code.

Once your students understand how to execute code in the console, let them explore on their own. What would they like to see happen on a web page? It’s tricky to execute sophisticated code in the console, so remind them to keep the scope simple. Some examples they can find online might include How do I change a web page’s background to a random color on click? How do I make text blink on and off when the user hovers over it? How do I make the page automatically scroll? Your students will quickly find that almost any question they can think of has already been asked by one of the other seven billion humans on the planet and answered by many of those helpful humans.

Summary

In this chapter, we threw our students into a mind-boggling deluge of information available in any web browser and had them dive into engaging with what they find there. The web development tools have a definitive wow factor that gets students sitting up in their chairs and engaging with the content. After you introduce your students to these powerful tools, hopefully many of them will rush home to excitedly show their friends and family what they’ve discovered. They’ll have the power to do so because this identical environment is available on their home and library computers, and this is how it should be.

But often, programming classes take a more roundabout approach. In a 2002 essay titled “A Mathematician’s Lament,” math teacher Paul Lockhart speculates on a world in which we teach music the way we teach math to make students competitive in an “increasingly sound-filled world.” He describes the arduous, meaningless exercises children in this dystopia go through at all grade levels: students memorizing algorithms and getting graded on the correctness of their musical notation, and stressed-out parents hiring tutors for their children who are bored with it and spend their music sessions staring out the window humming tunes to themselves instead of learning music. When the students get to college, they’re finally allowed to play and listen to actual music, and appreciate what all those years of busywork were leading up to, but only if they major in music.

A programming class that spends the first hour getting students to output a single "Hello, World!" in code is a soul-crushingly tedious way to teach coding. The more rapidly we can get students hacking and immediately rewarding them with outputs from the code they input, the more engaged they’ll become and the faster they’ll rise to the challenges of this new environment.

Only when students have had an opportunity to thoroughly enjoy coding as a playground of instant rewards can we begin to guide their newfound skills into more formal computational artifacts. JavaScript allows students to implement variables and the various control structures we learned about in the previous chapter into algorithms and functions. But students will need an environment where they can save their work, return to it, and iteratively enhance it if they want to take full advantage of these programming elements.

In the next chapter, we’ll learn about some readily available development environments where your students can graduate from temporary modifications to existing websites and start crafting web applications of their own to share with their peers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.40.177