Review
Using what we learned about CSS last week, see if you can make a box-drawing of any of the following figures:
A (block) smiley face, or a Jack O' Lantern face
A (square) kite with little square flags along its tail
A small (block) animal like a dog or cat
Here are some properties you'll probably need to use / look up how to use:
widthandheightaccept pixel or % values to decide the width or height of an element.display: inline-block;will make an element appear as a block but allow other elements to be in the same horizontal space.float: right;flushes an element to the right side of the container.margin,margin-left,margin-topetc. will add space on the outside of the bounding box.text-align: center;centers all contents in the container (like a div), including other inline-block elements.
Adding JS Scripts to HTML Docs
So first off, let's take a quick divergence to learn how to incorporate JavaScript... Scripts into our HTML documents.
If you guessed that we'd be using the head tag to include our scripts, you'd be correct!
(If you're curious, there's a great discussion on how best to load scripts in webpages located here)
The script tag, <script src="script.js" type="text/javascript"></script>,
is used to include a JS Script file that will be loaded and executed on the included webpage (where the src attribute includes the path-to and name-of the script to include,
and the type="text/javascript" attribute is used to indicate that it's a JavaScript file).
So, just like with including CSS documents in our webpages, we can employ the following steps:
Use your favorite text editor to open a new document.
Save that document as a JavaScript file (.js) in the same directory as your HTML document (again, this is not strictly necessary; you can still include scripts in other directories, but we'll assume that ours is in the same directory as the HTML file for simplicity).
Include the proper script inclusion in the HTML's head:
<script src="script.js" type="text/javascript"></script>(where "script.js" is the name of the script you saved in Step 2).
So let's try it! Save the following as your HTML file followed by saving "script.js" as your JS file, and then load the HTML document in your browser:
<html>
<head>
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<p>Just alertin' stuffs!</p>
</body>
</html>
// script.js
alert("Howdy hey! Scripterino here!");
And there you have it! When you load the page, you should see the alert pop up... you now have running JavaScript on your page!
Disclaimer: there are some efficiency concerns with how to add scripts using the async and defer script attributes that won't be discussed here,
but which are important concepts for loading larger scripts.
NB, you can use CodePen's HTML and JavaScript panels in union to perform a similar operation for testing, but when actually publishing a webpage, you'll need to use the above steps.
The DOM
So now that we've got a JS file in our HTML doc... what do we do in it?
Well let's wait no further! Shall we talk about how to employ JS to empower our websites?
The Document Object Model (DOM) provides a JavaScript interface that allows for dynamic manipulation, styling, and the addition of behaviors to page elements.
The DOM treats the HTML document as a tree in which each page element's tag is a parent of its immediate contents.
Draw the DOM tree corresponding to the following, simple document:
<html>
<body>
<div>
<p>DOM!</p>
<p>Tree!</p>
</div>
<div>
<p>Example!</p>
</div>
</body>
</html>
For greater detail and another DOM tutorial, consult the MDN Guide.
Although the DOM exposes the HTML to a variety of programming languages, you should be aware that every browser provides JavaScript access to the DOM through a
special, global object called document.
The browser's global document object treats the HTML as a JavaScript object in which page elements are properties that can be manipulated.
Let's look at a few ways we can use the document object to add dynamic behavior to our websites.
Document Selection
Just like with CSS selectors, we'll need some way of talking about "which elements we want to manipulate / read from" during our script.
The document object possesses several selection methods, which will return page elements in the form of manipulable JavaScript objects.
The document.querySelector(selector) method returns a DOM element corresponding to the given selector parameterized by a
string selector that corresponds to the CSS selector syntax plus more (see MDN documentation).
If no elements match the given selector, null is returned, and if multiple elements match the given selector, the first is returned.
Sometimes, we may want to select *multiple* tags at once, and then perform some operation on each of those elements. To do so, we use a modified version of the document's querySelector method:
The document.querySelectorAll(selector) method returns a NodeList (an array-like object with indexes corresponding to matched elements)
consisting of *all* elements matched by the given selector.
Note: the querySelector and querySelectorAll methods can also be called on previously selected DOM objects to search for the
given selector in only descendants of the calling object in the DOM tree!
Individual elements in a NodeList (returned by the querySelectorAll method) can be iterated over through a variety of means:
Traditional for-loops and for-of loops
A NodeList's
forEach(function)method, which is parameterized by a function that is called with each element in the NodeList as an argument. The syntax for this is:document.querySelectorAll(selector).forEach(function (element) { // Behavior to be done with each element matched by // the given querySelectorAll });
This forEach will look a bit alien at first, but we'll learn more about its syntax later in the course.
For now, let's look at some examples!
See the Pen Selector Examples by Andrew Forney (@forns) on CodePen.
Document Access & Manipulation
So now that we've selected some elements, let's look at how to retrieve and set their properties.
Each selected DOM object has properties that can be accessed through the typical object property access syntax, and dynamically changed
in the same way (through assignment object.property = newValue;)
The innerHTML property of a DOM object refers to the contents of that element's tags.
The className property of a DOM object refers to a space-separated list of classes to which the element belongs.
The style.cssText property of a DOM object refers to element-specific styling that can be assigned via a tag's style attribute.
Let's examine how we can use these simple properties with selectors now!
See the Pen DOM Manipulation Examples by Andrew Forney (@forns) on CodePen.
Creating Document Elements
Suppose we want to make new elements and use JavaScript to dynamically add them to the page!
The DOM's got you covered!
The document.createElement(tag) method creates a new document element with the given tag, but is not rendered on the page until it is
added to the DOM tree (see below).
The element.appendChild(toAdd) method appends the element toAdd to the end of the existing element in the DOM.
See the Pen DOM Creation Example by Andrew Forney (@forns) on CodePen.
So now that we know a lot about the document object, let's look at how we can reach the pinnacle of user interaction: collecting input and event handling!
User Input
Thus far we've dealt with pretty primitive methods for getting input from the user.
We started by assuming that they input directly into variable values (lol) then used prompt to collect input...
But both of these are tactics are from the stone-age of interaction design... time to evolve!
Interaction design is the study of creating user-friendly and effective interfaces by which users may input data or otherwise interact with an application.
In web design, there exist a number of input elements that can be used to facilitate good interaction with a user.
We'll start today's discussion by looking at a few of these elements, and later in the class, we'll see how to link them to some behaviors.
The most basic interactive element of a web page is the input tag, <input type="text" />,
used to collect small text, numerical, password, and other inputs from the user.
To collect larger amounts of text (like paragraphs) from the user, the textarea tag, <textarea> placeholder text </textarea>,
creates a larger input box for users to enter text.
Usually used to submit or otherwise confirm entries into inputs, the button tag, <button> buttonName </button>,
creates a clickable element that can be tied to some behavior.
Let's take a look at these basic input elements in action (well, they won't actually do anything yet, but hey... one thing at a time):
<html>
<body>
<p>Tell me your name pal!</p>
<input type="text" />
<p>Tell me a little bit about you buddy!</p>
<textarea></textarea>
<br/>
<button>Submit!</button>
</body>
</html>
These are just a couple of input examples; there exist quite a few others, from checkboxes, to dropdown menus, to radio buttons... we may or may not have time to look at those later!
So how do we get our inputs to... well... do anything? We provide event handlers!
Event Handling
Ever "posted" or "liked" a status on Facebook? Clicked the upvote arrow on Reddit?
I'm sure you've been on sites where you've clicked on something and neat stuff happened... or you typed in an input box and it did some calculations... or what have you...
Chances are good that those sites have used event handlers to react to your input and respond appropriately.
Event handlers / listeners define behavior that is executed whenever a user interacts with a particular page element.
Events, therefore, are the types of user input that trigger the event handlers. Events can be things like mouse clicks or keyboard input.
The DOM again gives us some tools to respond to different events.
Let's take a look at a couple!
The element.addEventListener(event, handler) method specifies some behavior (the handler argument, a function) to be executed
whenever the given event is detected. (see documentation here)
Detectable events include case-sensitive strings like: "click", "keydown". A list of events that are currently handle-able
can be found here: MDN Events Documentation
The anatomy of an event handler will look something like this:
document
.querySelector(selector)
.addEventListener(eventName, function (event) {
// What to do when event is detected
});
Create a small webpage with two features: (1) a ticklish button that giggles when clicked, and (2) our hypotenuse calculator from two input elements in which the user enters the base and height of the triangle on which to compute the hypotenuse.
See the Pen DOM Event Handling by Andrew Forney (@forns) on CodePen.
What a useful example!
Next week, we'll look at more advanced event handlers!
Write a script that assigns a click event handler to a button with id="move-btn" such that clicking the button will move an
element with id="shove-me" to the right by +10px with each push of the button. [Hint: consider making a global variable that tracks the current amount of indent, which you
can then add to with every click of the button and set the style of the "shove-me" element using this variable].