Posted: April 24th, 2009 | Author: amos | Filed under: javascript, xhtml | Tags: class 10 | No Comments »
To play audio or video files on a web page consistently across all the browsers, you will want to use a Flash media player. Adobe Flash is the most widely supported application on the web for playing audio and video files. As we mentioned early in the course, Flash is also commonly used to do animation on the web.
There are a variety of Flash media players available online, some free, some not. One of the most common, and easiest to use, is the freely available JW FLV Media Player. The nice thing about the JW FLV Media Player, and other players of its ilk, is that you can relatively easily skin it to make it fit the design of your site.
The bare bones approach
Note: While the following is the simplest way to put a Flash application on your page, and it is worth understanding, it is not the recommended approach. Skip below for the recommended approach.
To place any Flash application on your web page using simple XHTML, you will need to use either the <object> tag, or the <embed> tags in XHTML. Historically, the <object> tag was used for Internet Explorer, and the embed tag was used for the other browsers. However, these days, <embed> is not considered to be valid XHTML, and it is no longer recommended for use. However, most modern browsers continue to support it.
The FLV Media Player apploication we will be using to play media files can be put on a page using the following embed code:
<embed
src="mediaplayer.swf"
pluginspage="http://www.macromedia.com/go/getflashplayer"
type="application/x-shockwave-flash"
quality="high"
wmode="transparent"
flashvars="file=http%3A%2F%2Fwww.mos.org%2Fmedia%2Faudio%2F081121MOS_CSTPodcastTMGrapheneDDEelsX.mp3%3Ffile_extension%3D.mp3&autostart=false&repeat=false&showdigits=true&showfsbutton=false"
width="100%"
height="20"
/>
The “src” attribute tells the embed tag where to locate the flash media player file. Obviously, you need to make sure you have a copy of mediaplayer.swf in your own directories in order for this to work.
We then pass a parameter to this media player that indicates which media file it should play. The path to this media file goes inside the “flashvars” attribute. Notice that in this example, in the “flashvars” attribute, we are telling the media player to load a media file from another server. We could just as easily load a media file on our own server using a relative path instead of an absolute path. Also notice that the path to the media file is urlencoded.
To see this example in action on our server, click here.
The recommended approach
This example is the same as the first example above, but it uses the Javascript SWFObject.js library to put the Flash player on the page instead of using the <embed> tag. The SWFObject.js library is just a bit of code that creates the embed tag in Javascript and then places it on the page without you having to write it in XHTML. You’re probably wondering why you would want to use it…
This page gives a good overview of the two methods, the problems with the XHTML version, and the reasons for using the Javascript version rather than the XHTML version.
The code requires that you have downloaded the swfobject.js script, and have put it in a subfolder called “scripts” on your server. Once you have the file uploaded, you can included it into your XHTML file in the head of the document:
<head>
...the usual stuff in the head
<script type="text/javascript" src="scripts/swfobject.js"></script>
</head>
Once that’s taken care of, you put the JW FLV Media Player onto your page using this example code:
<script type="text/javascript">
var so = new SWFObject('mediaplayer.swf','mpl','100%','20','9');
so.addParam('flashvars','file=http%3A%2F%2Fwww.mos.org%2Fmedia%2Faudio%2F081121MOS_CSTPodcastTMGrapheneDDEelsX.mp3&autostart=true');
so.write('flashplayer');
</script>
Notice that the parameters are basically the same as we saw in the <embed> example: the location of the Flash application file, the width and height of the application, and the location of the media file that we want the media player to play. The difference, of course, is that these parameters are specified in Javascript.
PS: In case you didn’t notice, these parameters are obviously arguments being sent to the constructor function of an object in Javascript, similar to how we used constructor functions in object-oriented PHP.
Posted: March 14th, 2009 | Author: amos | Filed under: javascript, jquery | Tags: class 6 | No Comments »
JQuery’s syntax can be confusing, especially since you only started learning regular Javascript about a week ago. Don’t worry, it’s going to be ok
Let’s first deconstruct some of the more common JQuery commands that you’ll come across, so you can start to recognize the common elements in all JQuery scripts.
Wating for the page to load
First, and most importantly among JQuery commands, is $(document).ready(). This is the command we use to wait until the page is loaded before doing any manipulation of elements on the page.
Remember that objects are specific instances of classes (e.g., a specific Ford Mustang would be an instance – i.e., an object – of a general Car class). Objects have both properties and methods.
By default the web browser automatically creates an object that it calls “document” that has a variety of properties and methods related to the contents of the current web page. This document object is the highest level object in the Document Object Model (DOM), which is the internal representation the browser has of the contents of any page.
The ready() method is an extra method that JQuery adds on to the browser’s existing “document” object. It offers a relatively simple way to run some code only once the page has finished loading. This method takes one parameter, which is the function to run when the page is ready.
To extend the “document” object so that it has this extra ready() method (as well as many other extra JQuery properties and methods), we wrap it in the $() function. So we write “$(document)” whereas in regular Javascript, we would use just “document”. This “$()” indicates that we want to use the extended JQuery version of this object, with the extra methods and properties. You can use this same technique for any element in the DOM that you want to extend with JQuery’s extra properties and functions.
So in the end, $(document).ready(some_function) is the way we call this extended document object’s ready() function. We pass it, as a parameter, the function we want called when the page is ready.
some_function can either be the name of the function to call, or the definition of the function itself. So you could have code that looks like this:
function doSomething() {
//some code that you want to run when the page loads
}
$(document).ready(doSomething); //call the doSomething() function when the page is ready
…or, we could use an alternative syntax, which takes advantage of Javascript’s ability to write anonymous functions, meaning functions with no name that are only used once:
$(document).ready(function() {
//some code that you want to run when the page loads
});
These two code snippets are functionally identical as far as the browser is concerned. The latter syntax, using an anonymous function as a parameter, is more common in this context among experienced developers, since it is more compact.
Creating an event handler
The next most common thing you will want to do in JQuery code is create an event handler. This means creating a block of Javascript code that responds to a browser event, be it a click, mouseover, mouseout, keypress, keyup, or any other type of event. JQuery makes this process standardized, and quite simple.
A typical JQuery click event handler will look something like this:
$("a.class1").click(function(event) {
//some code that you want to run when the user clicks any element that matches the "a.class1" CSS-style selector
});
Let’s dissect this code. Let’s first look at the first part, $(“a.class1″). Once again, we see the ubiquitous “$()” JQuery function. This time, it is wrapped around a CSS-style selector, “a.class1″. As you know, if this were CSS code, that selector would match any <a> tag with class=”class1″. And it works exactly the same way here, because the developers of JQuery decided that this type of selector is easy to use. Putting a CSS-style selector as a String literal like this between the parentheses (as a parameter) of the $() function tells JQuery to return an array (i.e., a list) of all DOM elements that match this selector.
For all the elements that match this selector, we attach a “click” event handler. An “event handler” is just code that does something in response to an event: in this case the event would be a user clicking on any of the matching <a> elements. To attach the event handler to these elements, we call the click() method of the matching DOM elements. This click() method is is one of those method that JQuery adds as an extension to the default DOM element methods.
Any time you use the $() function to get a single element, or a list of elements, you can be sure that the objects that are returned by that function have the additional extended methods and properties that JQuery provides. So now you know that click() is an extended method of any DOM element returned by the $() function, and it takes one parameter: the function to run when a user clicks one of the matching elements.
Like the $(document).ready() method, we can think of this method as looking something like this:
$(some_css_selector).click(some_function)
The some_css_selector indicated in this code would be a CSS-style selector, such as “a.class1″. And just as with the $(document).ready() function, some_function can be either the name of an existing function, or an anonymous function definition, as illustrated in the following two equivalent ways of doing this task. First the long-winded way of doing it:
function doSomething(event) {
//some code that you want to run when the user clicks any element that matches the "a.class1" CSS-style selector
}
$("a.class1").click(doSomething);
You may notice that our function’s signature, “function doSomething(event)”, takes a parameter that we call “event”. This paramater automatically gets passed by JQuery to any function that called as an event handler. And so the “event” variable in that function holds the a special JQuery Event object that has properties and methods related to the browser event that triggered this event handler to be called. In this case, the “event” object has properties and methods related to the “click” event that caused the function to get called. For example, the event.type property would hold the type of event, be it “click”, “mouseover”, or something else. And event.preventDefault() is a method of the JQuery Event object that prevents links or forms from actually taking the user to another page.
The directly equivalent, but more compact, way of writing this same event handler using an anonymous function definition would be:
$("a.class1").click(function(event) {
//some code that you want to run when the user clicks any element that matches the "a.class1" CSS-style selector
});
Which method you choose is up to you, but you will probably see both being used by other developers. The two are equivalent as far as the browser is concerned.
The this
Within any function that gets called as a the result of an event handler, we have a special variable called “this”. This variable automatically holds the DOM element that triggered the event.
For example:
$("a.class1").click(function(event) {
//some code that you want to run when the user clicks any element that matches the "a.class1" CSS-style selector
$(this).addClass("selected");
});
The “this”, in this example, holds the regular Javascript DOM element that triggered the “click” event, which was handled by the anonymous function that is passed as a parameter to the click() method.
If we want to use JQuery to modify this DOM element, we have to first extend it by wrapping it in $(). So we write $(this) in order to be able to use the special JQuery methods and properties, like addClass() that JQuery adds to regular DOM elements. The addClass() method is a simple method that takes a single parameter, the name of a CSS class to add to the element. In this case, we are using it to add the class, “selected”, to the element that was clicked.
Putting it all together
So taking a real-world example…. the way you would use JQuery to handle an event is by combining the above methods. First you would wait for the page to finish loading, using the $(document).ready() method. And as the sole parameter to this ready() method, you would pass a function that defined an event handler.
For example:
$(document).ready(function() {
//some code that you want to run when the page loads
$("a.class1").click(function(event) {
//some code that you want to run when the user clicks any element that matches the "a.class1" CSS-style selector
$(this).addClass("selected");
});
});
See how we have nested the “click” event handler within the anonymous function that gets called when the page is “ready”. This makes sure that the event handler is only set after the page has loaded, thereby assuring that the DOM elements of the page that we want to modify are already loaded and available to be modified.
Posted: March 14th, 2009 | Author: amos | Filed under: assignments, javascript, jquery | Tags: class 6 | No Comments »
Your assignment in class today is to convert this diagram into a fully functioning XHTML/CSS/Javascript/JQuery page.

Mock e-commerce store wireframe
You hopefully realize that this assignment is identical to the class 5 assignment, except that this time, you will be writing Javascript code that takes advantage of the jQuery framework, rather than writing native Javascript as you did in the previous assignment.
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.
Where to start
I highly encourage you to make sure you understand all the discussion points from the class 5 page and the the class 6 page of this site. In case you wish to refer to some more “official” documentation, here are some external links to relevant pages from the JQuery site that you may find useful (you may also find them difficult to comprehend, so take them with a grain of salt):
A hint
To approach this problem, it might be helpful to go over the high-level flow of control of the page. Here are the steps involved in a typical scenario:
- Your code waits for the page to load, using JQuery’s $(document).ready() method. (Maybe it would be smart to refer to the example of the ready() function on the class 6 page of this site)
- Once the page loads, your code sets mouseover and mouseout event handlers around all the thumbnails using the mouseover() and mouseout() methods available to all extended JQuery elements…. something like this (the ids and classes used in the CSS-style selectors in your code will probably be different): $(“img.product_thumb”).mouseover() and $(“div.product_info”).mouseout()
- These event handlers call functions that use JQuery’s show() and hide() methods of all extended elements to show and hide the corresponding images and divs. For example $(“img#thumb1″).show() and $(“div#info1″).hide()
Posted: March 14th, 2009 | Author: amos | Filed under: javascript | Tags: class 5 | No Comments »
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.
Posted: March 13th, 2009 | Author: amos | Filed under: javascript, jquery | Tags: class 6 | No Comments »
To sum up our previous discussions and examples, the most common uses of Javascript fall into these general categories:
- responding to user-generated “events” (e.g. “mouseover”, “mouseout”, “click”, “submit”, “keypress”, “keyup” events)
- responding to other types of browser events (e.g. “load”, “error” “resize” events)
- doing mathematical calculations
- changing the style of elements on the screen (either individual CSS styles, or swapping entire CSS classes)
- making elements appear/disappear from the page (e.g. by toggling the CSS “display” property between “block” and “none”)
- image swaps (i.e. changing an image element’s “src” attribute for mouseover effects, or for slideshow effects)
- detecting what a user has entered in a form
- determining whether a given expression is true or false, and running some Javascript depending on the result (e.g. if/else statements)
Javascript is Horribly Inconsistent
You should be aware that there are significant inconsistencies in how the major web browsers handle Javascript. There are also inconsistencies and bugs within each browser’s support of Javascript. Until only a few years ago, Javascript developers often had to write several sets of code: one for each of the browsers they wanted to support. Although this still happens, it is not as common, due to the popularity of a few Javascript “Frameworks”, which simplify coding practices.
Javascript Frameworks
Thankfully, a few altruistic developers have created these Javascript libraries (scripts written in Javascript) whose sole purpose is to smooth out these inconsistencies in the browsers’ support of Javascript so that regular developers no longer have to worry about them. This is achieved by creating a layer of abstraction between the code the Javascript developer writes, and the actual code that is eventually run in the browser.

Javascript framework as an abstraction layer
You, the developer, write code using the intuitive-looking functions and objects provided by the Javascript framework. The Javascript framework then converts your nice clean Javascript code into the horrible mess that the browser’s Javascript engine actually understands.
Thus, the frameworks hide the complexity of the buggy browser implementations from the average developer. The frameworks include functions and objects that your code can call instead of calling the buggy built-in Javascript functions and objects. You write one set of code using those functions and objects, and it runs as you would expect it to regardless of which browser you’re using.
Behind the scenes, rest assured that the framework is determining which browser you are using and running idiosyncratic code that is known to work for that browser, but you don’t need to (or want to) know that.
In addition to smoothing out the inconsistencies and differences in each browser’s Javascript implementation, the frameworks also offer some shortcut ways of doing common programming tasks. These shortcuts expedite development and make developers’ lives at least a little bit more enjoyable.
Prototype and JQuery
Four independent (and competing) frameworks that serve this purpose are Prototype, JQuery, YUI, and MooTools. Each provides much of the same functionality as far as we are concerned, although they achieve it in slightly different ways. In this class, we will be using JQuery, although everything we will be doing with it can also be done in any of the other frameworks (and in fact, anything we do with any Javascript library can be done – with much difficulty – in plain Javascript, since the libraries are themselves written in plain Javascript).
Posted: March 6th, 2009 | Author: amos | Filed under: javascript | Tags: class 5 | No Comments »
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.
Posted: March 6th, 2009 | Author: amos | Filed under: javascript | Tags: class 5 | No Comments »
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.
Posted: March 6th, 2009 | Author: amos | Filed under: javascript | Tags: class 5 | No Comments »
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).
Posted: February 28th, 2009 | Author: amos | Filed under: css, javascript, xhtml | Tags: class 4 | No Comments »
This code can be put in the <head> element of your page, and will only be interpreted by the IE6 browser. So you can use it to load special stylesheets or javascripts that will override the other styles or scripts you have set.
<!--[if lte IE 6]>
<link href="/css/ie_hacks.css" media="screen" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/js/frontend/iepngfix_tilebg.js"></script>
<![endif]-->
To see more information about these “conditional comments”, check out this page on the quirksmode.org website.