Posts Tagged ‘class 5’

Class 5 – Document Object Model Cheat Sheet

Sunday, March 28th, 2010

Here is an attempt at a cheat sheet for working with the Document Object Model.   This diagram shows the most commonly used objects and their properties and methods.  It is by no means an exhaustive list of every feature of the DOM.

Curated List of Dom Objects

Curated List of Dom Objects

Class 2 – Web Dev Discussion List

Wednesday, October 28th, 2009

You should have received notification that you are subscribed to the Web Dev Intensive email discussion list.  That email should have information on how to send email to the list, as well as how to subscribe or unsubscribe from the list, so please don’t delete it.

Emails sent to this list at

Picture 3

will be received by everyone in the class, as well as former students from past classes.  So it might be useful if you have questions, problems, or anything else you want to share with the class.  Use it however you want.

If you have not yet received notification of the list, send a test email to the list address above.  If for whatever reason, you have not been subscribed to the list yet, I will be notified automatically and will add you to the list.

Class 5 – What is the Javascript Document Object Model?

Friday, October 23rd, 2009

In your studies of Javascript, you will most likely come across the Document Object Model (DOM for short) at some point. The DOM is simply the internal representation the browser has of the contents of a web page.  We have already discussed some aspects of the DOM without calling it such.

The layout engine

Whenever you write XHTML and CSS code, the web browser does some internal processing to determine out how the page is supposed to look.  The part of the browser responsible for this task is known as the layout engine.  The different browsers often have slight different layout engines which means the browsers sometimes display the contents of any given page slightly differently.

The internal representation that the browser makes of the page, the DOM, is made accessible to any Javascript code on the page as a series of built-in Javascript variables.   For example, “window” is a built-in variable that holds information about the entire browser window.   “document” is another built-in variable that contains all the information about the content in the <body> section of the page.

Developers can write Javascript code to interact with the DOM to either detect or to change how the page is internally represented.

Object-oriented DOM variables

These built-in variables that hold the browser’s internal DOM information are object-oriented, which for our purposes means that these variables do not necessarily hold just text or numbers.  They often are wrappers that contain other properties, functions, or other objects “inside” of them.  For example, the “window” object has a “title” property inside of it, which is simply a variable that holds the text inside the <title> tag in the XHTML.

When one property, function, or object is inside of another, we use dot notation to indicate the hierarchical relationship.  So window.title indicates that title is a sub-property of the window object.  The code window.close() tells the browser to run the function called close() that is inside of the window object, which happens to close the window automatically.  Similarly, window.alert(“hello”) tells the browser to run the alert() function of the window object and pass it the parameter, “hello”.

The DOM on a need-to-know basis

There are lots of built-in variables, objects, and functions in the DOM, and it can easily become overwhelming.  However, in practice, we only use a few of these.  Don’t try to memorize them all.  By following the conventions taught in this class, it is not necessary that you delve too far into the details.

There are some things you will want to know:

  • window is the highest level DOM object.  All other DOM objects are sub-objects of window.  In fact, your own variables and functions that you define in your code are also automatically created as sub-properties of window.
  • document is a sub-object of window.  So to get access in Javascript to information concerning the stuff inside the <body> tag, you use the window.document object.  Fortunately, for convenience, you can refer to the document object as simply document.  It’s not necessary to specify the full window.document variable name. The “window.” part is implicit in all variable names, so you don’t need to write it.
  • You can get the DOM representation of any element in the <body> tag by using the getElementById() function of the document object.  For example, var el = document.getElementById(‘foo’); will find the XHTML element that has the id attribute set to “foo” and store it in memory in an object named “el”.    The variable “el” now holds an element object, which is a standard type of object used to hold all the information about individual XHTML elements.  Element objects have a variety of properties and functions that are especially useful when dealing with individual XHTML elements.
  • The className property of the element object holds the name of the class that is specified in the XHTML.  For example, to detect the class of an XHTML element that looks like this <p id=”p1″ class=”foo”>…</p>, you would first get an element object that holds information about this element by using var el = document.getElementById(‘p1′); Then you would access this element’s className property by referring to it as el.className.  For example, if you said, alert(el.className);, the word “foo” would pop up in an alert window.
  • The style property of the element object contains information about the CSS used to control the design of that element in the browser.  For example, to get the font-size property of an element such as <p id=”p1″>, you could (in theory), access that information through the DOM by referring to the element’s style.fontSize property in Javasacript.  First you would get a reference to the element object by using var el = document.getElementById(‘p1′);, then you would access this element’s font-size property, for example, with alert(el.style.fontSize);
  • Image elements have a src property which represents the source file used to display the image.  For example, if you have an image tag in your XHTML like this, <img id=”img1″ src=”images/monkey.jpg” />, you can manipulate the src attribute in Javascript by doing something like, var el = document.getElementById(‘img1′); img1.src = “images/cat.jpg”;

See also

Class 5 – Assignment #2

Saturday, October 17th, 2009

Your coding assignment is to convert the following wireframe diagram into a fully functioning page, using XHTML & CSS for the layout and Javascript for the interactive behaviors.

Note: this is a wireframe, not a design comp.  So do not try to use make your pages pixel-perfect based on this diagram.  Use the diagram as a rough guide, and just make sure the Ad Banner and Skyscraper Ads you use are the size that is written into the wireframe.  All other design elements, including dimensions, colors, fonts, and borders are up to you.

E-Commerce Assignment wireframe

When someone mouses over any of the product thumbnails, the thumbnail should disappear, and a div containing information about that product should appear.  The information div should show up as exactly the same height and width in exactly the same place where the thumbnail was on the page.

When the user then mouses out of the product info div, the info div should disappear, and the product thumbnail image for that product should reappear.

So the trick to this assignment will be to first create the layout with all the basic page elements using XHTML & CSS.  Be sure to create an “img” tag and a “div” tag for each product.  The img tag should be visible when the page first loads, and the div tag should be invisible by setting its “display” property to be “none” in the CSS.

Create the mouseover and mouseout Javascript event handlers so that when you mouse over an image the image disappears and the div shows up.  And when you mouse out of the div, the div should disappear and the image should re-appear.

Tips / Spoilers

Note: don’t read this if you want to figure out the solution yourself.

Solution #1: Here is an example of how I would set up the product thumbnails in terms of both XHTLML and Javascript.  You can use this exact code for the thumbnails on your own pages, but be sure you understand how it is working.

Solution #2: It just so happens that you don’t even need to use Javascript to complete this assignment.  Here is an example that has no Javascript and relies instead upon the CSS :hover pseudo-class to do the same thing.

Solution #3: Here is a slight variation on the CSS-only solution outlined in Solution #2.  This version makes the product thumbnail become partially transparent when it is moused-over, instead of disappearing entirely.

Class 5 – In-class Assignment #1

Saturday, October 17th, 2009

Your assignment in class today is to develop a sort of text-capturing script.  The page is going to be divided into two identical  panels.  In the left panel, you will have one text input, one password input, and one textarea input.  When a user begins to enter text into any of the fields in the left panel, the corresponding field in the right panel will start to be automatically filled-in with the same text that they entered in the left.

To do this assignment, you will have to look into Javascript “keyup” events.

Here is the information architecture wireframe for this in-class assignment:

Text-capturing wireframe

Text-capturing wireframe

The best way to approach this assignment is to first lay out the page in XHTML and CSS before doing any Javascript coding.  Then start thinking about the how the logic of this type of interaction might be structured.  Break it down into discrete individual steps.

Here are the basic steps that need to be handled in order for something like this works

  1. set event handlers to detect the “keyup” event whenever a user types anything into any of the form elements on the left side of the page
  2. if a keyup event is triggered, call a function
  3. in that function, first get the values of all form elements on the left side of the page and store them each in their own variable
  4. Take the values stored in those variables and insert them into the corresponding form elements on the right side of the page

I expect you’ll have questions for me about exactly to do this, so please try to figure it out based on the examples so far, and ask for help when you get stuck.

Hint

Dealing with keypress, keyup, or any other type of supported Javascript event is not so different from the examples we went over for mouseover, mouseout, and click events.  You create an XHTML attribute called “onkeypress” or “onkeyup” in each element you want to detect these events for, and set its value to be a call to a Javascript function…

<input type="text" name="first_name" id="first_name" onkeyup="doSomething();">

To get an XHTML element into memory in Javascript, you access it based on its “id” attribute.  So, for example, to get an element with the id=”first_name” into memory, we would do the following in Javascript:

var firstNameElement = document.getElementById("first_name");

To get the value of a text input, password input, or textarea element, you can use the .value property of the element in Javascript.  So, for example, to get the value of the element retrieved above, we could do something like:

var firstNameValue = firstNameElement.value;

To set the value of a text input, password input, or textarea element, you can do the reverse.  For example:

firstNameElement.value = "some new value here";

where “some new value here” can be left as a string literal, as in what we just saw, or replaced by a variable that holds a string in memory, such as:

var newName = "Amos";
firstNameElement.value = newName;

Class 5 – Basic Javascript Examples

Wednesday, July 15th, 2009

Some basic documentation

To begin understanding Javascript, and programming in general, I recommend you begin reading some of the documentation I have written about Javascript.  In particular:

The tutorials and reference pages about Javascript on w3schools.com are also very good.

Example files

With that information in mind, here are links to each of the Javascript examples I will be covering in our first day of learning Javascript.

How to include Javascript on your web page

Understanding variables

Understanding functions

Conditional statements and loops

Detecting user interaction with event handlers

The Basics of dynamic HTML

Detecting the value of form elements

Misc

Class 5 – How to Cancel the Default Behavior of Links and Forms

Saturday, March 14th, 2009

Clicking a link and submitting a form will, by default, take you to another page.  In some cases, you may want to override that behavior.

Canceling form submissions

To cancel the submission of a form, while still allowing the user to click a submit button, the form tag’s “onsubmit” attribute must be set to return false.  This causes the browser to cancel the form submission after the user attempts to submit.

<form onsubmit="return false;">

See an example live on the server

Let’s say, in a hypothetical situation, you wanted to call a function in Javascript first when the user clicks submit, and then cancel the form, you could add the function call (or any other Javascript code) before the “return false;” statement.

For example, assuming you had a function named doSomething(), you could call it when the user tries to submit the form, and then cancel the form as follows:

<form onsubmit="doSomething(); return false;">

See an example live on the server

 

Canceling a link click

Let’s say you want to allow a user to click a link, but you don’t want that link to take the user to another page.  You place “return false” to the onclick attribute:

<a href="http://wd.onepotcooking.com onclick="return false;">click me!</a>

See an example live on the server

The above code will not take the user away from the current page.  They can click all they want, but they will not go anywhere.

If, in a hypothetical situation, you wanted to call a function named doSomething() first when the user clicked a link, and then cancel that link, you would do it as follows:

<a href="http://wd.onepotcooking.com" onclick="doSomething(); return false;">click me</a>

See an example live on the server

In sum…

To sum these examples up, by telling the code to “return false;” when a user clicks a link or submits a form, we tell the browser to prevent that element from performing its default behavior.  We do this by placing that code in the onclick and onsubmit attributes of links and forms, respectively.

 

Class 5 – Javascript Functions

Friday, March 6th, 2009

Whereas variables store a piece of data in memory, functions store a series of commands in memory to be run at a later time.  Think of a function as a block of code that performs a  specific task.

Defining a function

For example, let’s say we have a function that does one thing – it pops up a message with the word, “hello.”

function sayHello() {
  alert("hello");
}

Let’s take this function line-by-line:

function sayHello() {

This line of code declares that the following block of code will be a function by using the keyword “function” (similar to how a variable is declared with the “var” keyword).  Then it defines the name of the function as “sayHello”.

  alert("hello");

This line of code calls the browser’s built-in “alert” function, which will automagically pop up an alert box with the word “hello” in it when it is run.

}

This last line of code just has a closing bracket, “}”.  This tells the browser, which is reading this code, that this is the end of the function.  Everything between the opening bracket, “{“, and the closing bracket, “}”, is a block of code (i.e., a set of commands) that is stored in memory and is only executed when we call the function named “sayHello.”

Calling the function

It’s all well and good to define a function, as we have done above.  But the browser does not actually perform the actions defined in the function.  It simply stores them in memory for use later.

In order to actually run the commands stored in the function, we have to “call” the function.  This usually happens somewhere else in the code, outside of the function block.

To call the function we defined above, we would use the following code:

sayHello();

This would run the commands in the function, which would result in the word “hello” appearing in a pop-up alert box.

Passing parameters to functions

Let’s say we wanted to make the message that pops up in the alert box customizable.  For example, we want the message to have someone’s name in it, such as “hello, Martha” or “hello, Juan”, or “hello, Fausta.”

We want to be able to use this same function to say hello to all these people.  How do we do it?

We could just write a separate function for each person, like this:

function sayHelloToMartha() {
  alert("hello, Martha");
}
function sayHelloToJuan() {
  alert("hello, Juan");
}
function sayHelloToFausta() {
  alert("hello, Fausta");
}

and whenever we want to pop up a message for Martha we call her function in our code:

sayHelloToMartha();

and when we want to pop up a message for Juan, we call his function:

sayHelloToJuan();

…and so on.

However, this can become very inefficient if there are lots of variations on the same basic function.  There is an easier way using parameters.

We can design a version of our original function that takes one “parameter” or input.  When we call the function, we tell the function the name of the person to whom to say hello, and it outputs a message customized to that person.

Here is what our function will look like:

function sayHello(person) {
  alert("hello," + person);
}

This single function can say hello to just about anybody we tell it to.  Let’s take it line by line:

function sayHello(person) {

This declares that we are defining a function named “sayHello” and that it accepts one parameter, which we call “person”.

Note: Anytime you see words in between the parentheses of a function definition, they indicate parameters that the function accepts as input when it is called.

  alert("hello," + person);

Here we are again using the browser’s built-in “alert” function in order to pop up a message in an alert box.  However, the message we are popping up is no longer just a simple “hello”.  The message we are popping up (i.e. the stuff between the parentheses of the alert function call) is now:

"hello," + person

This takes the word “hello,” and glues it to the name we will use as a parameter when we called the function. The word “hello”, in this case, is a string literal, which we saw in the discussion on variables.  You can tell this because it is text surrounded by quotes.  The term “person” is a variable name, which you can tell because it is text not surrounded by quotes.

So the word “hello” is concatenated with, or glued onto, whatever word is stored in the variable named “person”.

If we call the function and pass it the word “Martha” as a parameter, the function takes the word, “Martha”, stores it in a variable named “person”, and concatenates this variable with the word “hello”.  Then it pops up an alert message with the combined message, which contains the words, “hello, Martha”.

Calling the function with the word “Martha” as a parameter looks like this:

sayHello("Martha");

If we pass it the word “Simon”, it will say “hello, Simon”:

sayHello("Simon");

If we pass it the word, “Susan”, it will pop up “hello, Susan”:

sayHello("Susan");

etc.

More about parameters and variable scope

Functions are not limited to just accepting one parameter as input.  Functions can take as many parameters as you want them to when you design them.

function doSomething(parameter1, parameter2) { ... }

In any function definition, the stuff between the parentheses is a comma-delimited list of parameters.  Parameters are values that the function will accept when it is called.  They are variables that automatically hold the values that were passed to the function when it was called.

When we call a function, we supply it with a list of arguments.  These can be variables or literals. In the following example function call we’re using two literals, but these arguments could just as easily be variables: the two are interchangeable as far as the code is concerned, and it really depends on what you’re trying to achieve which one you use.

doSomething("hello", 100);

When we call the function this way, the argument “hello” is stored in the function’s first parameter variable, “parameter1″.  The second argument, 100, is stored in the function’s second parameter variable, “parameter2″.

Within the function block (anywhere between the brackets “{” and “}”) , the variable “parameter1″ holds the value “hello”, and “parameter2″ holds the value 100.  These parameter variables only exist within that function, and are said to have a local scope to that function.  Referring to the variable named “parameter1″ outside of the function is meaningless.

So the term “arguments” refers to values that are supplied to a function when that function is called somewhere in your code.  Parameters are the flip-side of arguments – the term “parameters” refers to the values that the function accepts and stores in variables when it is called.  Whatever you supply as arguments to a function are then stored temporarily in that function’s parameters.

Return values

Some functions have return values.  This means that when the function is called, it takes some kind of input, performs a specific function on that input, and then returns the results of that process to the code that called it.

This is probably best illustrated with an example:

function addOne(someNumber) {
  var newNumber = someNumber + 1;
  return newNumber;
}

This function defines a block of code that takes some number and adds one to it.  Then it returns the new number.

So if we call this number, and give it the number 10 as an argument, we will get the number 11 back.  This is how we’d call the function and supply it with the argument, 10.

addOne(10);

But in order to see that this works, we would have to do something we the number we get back, like, for example, popping it up in an alert message.  So let’s first store the returned value in a variable, and then pop up the contents of that variable in an alert pop-up.

var result = addOne(10);
alert(result);

So we can see that the return value of the function was 11.  If we supplied the function with the parameter 3, the return value would be 4, and so on.

Function names

Like variable names, function names must not have any spaces or special characters in them, although they can use the underscore (“_”) character.  They also generally use the CamelCase convention.

Class 5 – Javascript Variables

Friday, March 6th, 2009

In Javascript, as in most high-level programming languages, we have access to some of the computer’s memory.  At any point in our code, we can store things in memory that we want to use later on.

It may not be clear at the moment why we would want to use memory, but it will come into play in everything we do for the rest of this course.  The same principles we will go over here will apply to PHP coding, as well any programming languages you learn in the future.  So although these examples may seem abstract at first, it is imperative that you follow the concepts and understand how they are being used.

Variables are symbols that represent data

The simplest way of storing data is with what is termed a variable.  If you remember basic algebra, you may recall that you encountered formulas where some of the values were replaced with variables.  In algebra, a variable is a symbol that represents a number.  For example, a simple formula for a straight line looks something like this:

y = x + 1

If you imagine that x is replaced with the number 3, then your formula would become:

y = 3 + 1

…which means that:

y = 4

In this example, the letter “x” is a variable.  It is a placeholder for some data stored in memory.  In this example, you “remember” that x has the value 3, so everywhere you see the letter “x”, you know that it should be replaced by the number 3.  But you could just as easily use the same formula for other values of x.  For example, if x=5, then following the formula, y=5+1, which means y=6.

Variables in programming languages come in a variety of data types

In most programming languages, unlike algebra, not all variables hold numbers.  Some can hold text or more complicated types of data.  For example, imagine we had a formula that assembles a sentence:

y = "Hello " + name

If you imagine that “name” is a variable that holds someone’s name, such as “Amos”, then you can see that:

y = "Hello " + "Amos"

…which, if you use the plus sign to concatenate the two bits of text, means that:

y = "Hello Amos"

So here we have a formula that deals with variables that store text, not numbers.  In programming parlance, variables, like this, that hold text are called “strings“.

Defining variables in Javascript

In Javascript, you can define variables as follows:

var x = 3;
var y = x + 1;

In this case, we have declared (assigned a name to) a variable “x” and defined it as having the value 3, which tells the computer to store the number 3 in the piece of memory associated with the symbol “x”.  We have also declared the variable “y” and assigned it the value of x+1, which in this case tells the computer to first evaluate the expression x+1, realize that it is equal to 4 (since x=3), and then store the number 4 in the piece of memory associated with the symbol “y”.

Note that all variables must be declared, and that variable declarations must be preceded with the keyword “var”.  Also note that Javascript commands must end in a semi-colon.

The second time we referred to “x”, in the second line of code, it is not preceded by the keyword “var” – this is because “x” has already been declared once in the first line of code, and we do not have to re-declare it when we use it subsequent times.

Variables vs. Literals

In the second line of code in the example above, we have the following:

var y = x + 1;

There are two variables in this line: “x” and “y”.  There is also the number 1.  Whenever we use a raw value, rather than a variable, it is known as a “literal“.  So 1, in this case, is a literal.

The same concept applies to variables that hold other types of data, such as strings:

var name = "Amos";
y = "Hello " + name;

In the second line of code in this example, “Hello” is a literal, whereas “name” is a variable.  In Javascript, literals that are numbers do not need quotes around them.  But all literals that are strings must be surrounded by quotes.  It doesn’t matter whether you use single or double quotes, so long as you start with the same kind of quote that you end with.

Variable Names in Javascript

In Javascript, variable names must not have any spaces or special characters in them, but they can use the underscore “_” character.  A common convention is to use CamelCase for variables that have more than one word.  For example, if I wanted to create a variable that held someone’s first name in it, I might name it using CamelCase in the variable declaration:

var firstName;

Notice that the first word is not capitalized, but the first letter of the second word is. Some people capitalize the first letter of all words, but in Javascript, it is common to see the first word all lowercase.  The reason this convention is called CamelCase is because the capitalized letters look almost like humps on a camel’s back:

var thisIsALongVariableNameThatLooksSimilarToCamelHumps;

Variable types in Javascript

Unlike many other programming languages, variables in Javascript are “loosely typed”.  This means you do not have to explicitly state what type of data the variable will hold when you declare it.

For example, a variable that previously held an integer can be later used to hold a string:

var i = 100; //declare the variable and assign it the literal 100
i = i + 1; //increase the value stored in the variable by 1 (i.e. "i" is now 101)
i = "this is not a number anymore!"; //reassign the variable a string value

In many other languages, this would produce an error.  In Javascript, it’s fine, which may be confusing to people who have previous experience programming more strictly-typed languages like C, C++, or Java.

Class 5 – How to place Javascript code on a page

Friday, March 6th, 2009

Javascript is the last of the client-side technologies we will be covering in this class.  After XHTMl and CSS, it is the third most prevalent technology on the web today.

Javascript has nothing to do with Java.  Javascript is actually based on a language called ECMAScript, so if you must use the wrong name, call it ECMAScript.  But whatever you do, never mistakenly use the term “Java” when you mean to say “Javascript”… it’s a sign of web dev ignorance to do so.

Similarly to CSS, Javascript should always be written in an external file whenever possible.  And like CSS, Javascript can be put in your XHTML code in three different places:
1) nested within the <head> tag
2) nested within the <body> tag
3) as an attribute of almost any XHTML element

Here are examples of each of these placements:

Nested within the <head> tag

...
<head>
  ...
  <script type="text/javascript" src="scripts/something.js"></script>
  ...
</head>
...

Click to view a page using this example code

Nested within the <body> tag

...
<body>
  ...
  <script type="text/javascript" src="scripts/something.js"></script>
  ...
</body>
...

Click to view a page using this example code

As an attribute of an XHTML element

...
  <a href="#" onclick="alert('Hello again!');">Click me please</a>
...

Click to view a page using this example code

Internal vs. External Scripts

Just as with CSS, as far as the web browser is concerned, an external script file is equivalent to an internal script.  So in the examples above, you could replace any of the external <script> tags with an internal script and get the same results in the browser.

Here is the example of a script nested within the <head> element, as shown above, but this time using an internal script.  The important thing to notice is that the syntax of the <script> tag is basically the same, but the src attribute is removed and Javascript code is placed between the start and end <script> tags:

...
<head>
  ...
  <script type="text/javascript">
    alert('Hello World!');
  </script>
  ...
</head>
...

Click to view a page using this example code

For the same reasons as with CSS, you are encouraged to use external Javscripts whenever possible.  This affords you a clear separation of markup (XHTML) from presentation (CSS) from behavior (Javascript).