Saturday, April 30, 2011

JavaScript Event Handlers


When your users visit your website, they do things like click on things, hover over things etc. These are examples of what JavaScript calls events. Using JavaScript, you can respond to an event using Event Handlers. You can attach an event handler to the HTML element for which you want to respond to when a specific event occurs. For example, you could attach JavaScript'sonMouseover event handler to a button and specify some JavaScript to run whenever this event occurs against that button.
The HTML 4 specification defines 18 event handlers as listed below:
Event HandlerEvent that it handles
onBlurUser has left the focus of the object. For example, they clicked away from a text field that was previously selected.
onChangeUser has changed the object, then attempts to leave that field (i.e. clicks elsewhere).
onClickUser clicked on the object.
onDblClickUser clicked twice on the object.
onFocusUser brought the focus to the object (i.e. clicked on it/tabbed to it)
onKeydownA key was pressed over an element.
onKeyupA key was released over an element.
onKeypressA key was pressed over an element then released.
onLoadThe object has loaded.
onMousedownThe cursor moved over the object and mouse/pointing device was pressed down.
onMouseupThe mouse/pointing device was released after being pressed down.
onMouseoverThe cursor moved over the object (i.e. user hovers the mouse over the object).
onMousemoveThe cursor moved while hovering over an object.
onMouseoutThe cursor moved off the object
onResetUser has reset a form.
onSelectUser selected some or all of the contents of the object. For example, the user selected some text within a text field.
onSubmitUser submitted a form.
onUnloadUser left the window (i.e. user closes the browser window).

JavaScript Date and Time Functions


JavaScript provides the following date and time functions. Note that UTC stands for Universal Coordinated Time which refers to the time as set by the World Time Standard. Previously referred to as Greenwich Mean Time or GMT.
FunctionDescriptionReturned Values
getDate()
getUTCDate()
Day of the month1-31
getDay()
getUTCDay()
Day of the week (integer)0-6
getFullYear()
getUTCFullYear()
Year (full four digit)1900+
getHours()
getUTCHours()
Hour of the day (integer)0-23
getMilliseconds()
getUTCMilliseconds()
Milliseconds (since last second)0-999
getMinutes()
getUTCMinutes()
Minutes (since last hour)0-59
getMonth()
getUTCMonth()
Month0-11
getSeconds()
getUTCSeconds()
Seconds (since last minute)0-59
getTime()Number of milliseconds since 1 January 1970 
getTimezoneOffset()Difference between local time and GMT in minutes0-1439
getYear()Year0-99 for years between 1900-1999
Four digit for 2000+
parse()Returns the number of milliseconds since midnight 1 January 1970 for a given date and time string passed to it. 
setDate()
setUTCDate()
Sets the day, given a number between 1-31Date in milliseconds
setFullYear()
setUTCFullYear()
Sets the year, given a four digit numberDate in milliseconds
setHours()
setUTCHours()
Sets the hour, given a number between 0-23Date in milliseconds
setMilliseconds()
setUTCMilliseconds()
Sets the milliseconds, given a numberDate in milliseconds
setMinutes()
setUTCMinutes()
Sets the minutes, given a number between 0-59Date in milliseconds
setMonth()
setUTCMonth()
Sets the month, given a number between 0-11Date in milliseconds
setSeconds()
setUTCSeconds()
Sets the seconds,l given a number between 0-59Date in milliseconds
setTime()Sets the date, given the number of milliseconds since 1 January 1970Date in milliseconds
setYear()Sets the year, given either a two digit or four digit numberDate in milliseconds
toGMTString()
toUTCString()
GMT date and time as a stringday dd mmm yyyy hh:mm:ss GMT
toLocaleString()Local date and time as a stringDepends on operating system, locale, and browser
toString()Local date and time as a stringDepends on operating system, locale, and browser
UTC()Returns the number of milliseconds since 1 January 1970 for a given date in year, month, day (and optionally, hours, minutes, seconds, and milliseconds)Date in milliseconds
valueOf()Number of milliseconds since 1 January 1970Date in milliseconds


JavaScript Reserved Words


You should avoid using these reserved words and keywords as function or variable names as JavaScript has reserved these words for its own use.
JavaScript Reserved Words
breakcontinuedoforimportnewthisvoid
casedefaultelsefunctioninreturntypeofwhile
commentdeleteexportiflabelswitchvarwith


Java Keywords (Reserved by JavaScript)
abstractimplementsprotected
booleaninstanceOfpublic
byteintshort
charinterfacestatic
doublelongsynchronized
falsenativethrows
finalnulltransient
floatpackagetrue
gotoprivate


JavaScript Summary - XXII


Pat yourself on the back - you've made it to the end of this tutorial!
This tutorial has demonstrated what JavaScript is and how it works. We started with the basics - like how to turn JavaScript on and off in your browser. We then quickly moved on to the basic syntax of JavaScript. We learned that you can include JavaScript within your HTML page, or you can place it in an external file - the choice is yours.
We learned about some of the key concepts of JavaScript and that these concepts are pretty standard across most programming/scripting languages - concepts such as operatorsvariables and functions. We learned that intrinsic events enable you run a script in response to a user's action.
We covered some more of the standard programming concepts such as if statements, switch statements and loops.
We learned how to catch an error and present a friendly message back to the user (so as to not scare them off).
Among the advanced topics were cookies, which enable us to "remember" a user by writing and reading a file on their hard drive. We learned how to present the date and time in a nice format, then finished off with arrays - another standard programming concept.

What Next?

If you think JavaScript is your thing, try checking out some of the code snippets here on Quackit such as Image Rollovers orDropdown Menu. There are also JavaScript references such as Reserved Words or Date and Time Functions.

InnerHTML In JavaScript - XXI


The innerHTML property can be used to modify your document's HTML on the fly.
When you use innerHTML, you can change the page's content without refreshing the page. This can make your website feel quicker and more responsive to user input.
The innerHTML property is used along with getElementById within your JavaScript code to refer to an HTML element and change its contents.
The innerHTML property is not actually part of the official DOM specification. Despite this, it is supported in all major browsers, and has had widespread use across the web for many years. DOM, which stands for Document Object Model, is the hierarchy that you can use to access and manipulate HTML objects from within your JavaScript.

The innerHTML Syntax

The syntax for using innerHTML goes like this:

Two Dimensional Arrays - XX


Visualizing Two Dimensional Arrays

Whereas, one dimensional arrays can be visualized as a stack of elements, two dimensional arrays can be visualized as a multicolumn table or grid.
For example, we could create a two dimensional array that holds three columns of data; a question, an answer, and a topic.
Two Dimensional Array
0ArraysWhat is an array?An ordered stack of data
1ArraysHow to create arrays?Assign variable name to array object, then assign values to the array.
2ArraysWhat are two dimensional arrays?An ordered grid of data

Creating Two Dimensional Arrays

JavaScript Arrays - XIX


What is an array?

Arrays are a fundamental part of most programming languages and scripting languages. Arrays are simply an ordered stack of data items with the same data type. Using arrays, you can store multiple values under a single name. Instead of using a separate variable for each item, you can use one array to hold all of them.
For example, say you have three Frequently Asked Questions that you want to store and write to the screen. You could store these in a simple variable like this:
faqQuestion1 = "What is an array?"
faqQuestion2 = "How to create arrays in JavaScript?"
faqQuestion3 = "What are two dimensional arrays?"
This will work fine. But one problem with this approach is that you have to write out each variable name whenever you need to work with it. Also, you can't do stuff like loop through all your variables. That's where arrays come into play. You could put all your questions into one array.

JavaScript Date and Time - XVIII


JavaScript provides you with the ability to access the date and time of your users' local computer, which can be quite useful at times. Displaying the current date and time in a nice user friendly way using JavaScript is not quite as simple as you might like. You need to massage the data a little.

Displaying the Current Date

Typing this code...
var currentDate = new Date()
  var day = currentDate.getDate()
  var month = currentDate.getMonth()
  var year = currentDate.getFullYear()
  document.write("<b>" + day + "/" + month + "/" + year + "</b>")

JavaScript Cookies - XVII


Cookies are small text files that sit on your hard disk. Cookies are created when you visit websites that use cookies to store information that they need (or prefer). Websites often use cookies to personalise the user experience - such as remembering your name (assuming you supplied it previously) or remembering the items in your shopping cart from previous visits.
Despite the many misconceptions about cookies being malicious, they are quite harmless. Cookies can't give your personal details to other websites, or transmit a virus or anything like that. A cookie can only be read by the server that created it. Websites normally use cookies to make its users' lives easier, not harder.

Creating Cookies in JavaScript

JavaScript Void(0) - XVI


Sometimes, you may need to call some JavaSript from within a link. Normally, when you click a link, the browser loads a new page (or refreshes the same page).
This might not always be desirable. For example, you might only want to dynamically update a form field when the user clicks a link.
To prevent the load from refreshing, you could use the JavaScript void() function and pass a parameter of 0 (zero).

Example of void(0):

We have a link that should only do something (i.e. display a message) upon two clicks (i.e. a double click). If you click once, nothing should happen. We can specify the double click code by using JavaScript's "ondblclick" method. To prevent the page reloading upon a single click, we can use "JavaScript:void(0);" within the anchor link.
Code:

JavaScript Escape Characters - XV


When working with strings, you'll notice there are some characters that always seem to break your program. These include apostrophes, ampersands, double quotes etc.
When working with these characters, you need to use what is known as an "escape character". An escape character enables you to output characters you wouldn't normally be able to, usually because the browser will interpret it differently to what you intended.
In JavaScript, the backslash (\) is an escape character.
As an example, let's say I want to display the following text: They call it an "escape" character. Let's try that without an escape character:

Without an escape character:

JavaScript Try... Catch - XIV


The more JavaScript you code the more errors you'll encounter. This is a fact of life in any programming environment. Nobody's perfect and, once your scripts become more complex, you'll find there are sometimes scenarios that result in an error that you didn't think of.
JavaScript errors on web pages can scare your visitors away. How many times have you encountered a web page with errors, only to click the "back" button?
OK, so you can't always prevent errors from occuring, but you can do something about them. The JavaScript "Try... Catch" statement helps you handle errors in a "nice" way.
To use the Try... Catch statement, you take any code you think could potentially result in an error, and wrap it within the "try" statement. You then code what you want to happen in the event of an error and wrap that in a "catch" statement.

Code without a Try... Catch statement:

JavaScript While Loop - XIII


In JavaScript and most other languages, "loops" enable your program to continuously execute a block of code for a given number of times, or while a given condition is true.
The JavaScript While loop executes code while a condition is true.
For example, you could make your program display a the value of a counter while the count is less than or equal to say, 10.

Example While statement:

JavaScript Switch Statement - XII


In the previous lesson about JavaScript If statements, we learned that we can use an If Else If statement to test for multiple conditions, then output a different result for each condition.
For example, if the variable "myColor" was equal to "Blue", we could output one message. If it is "Red" we could output another etc
Another way of doing this is to use the JavaScript Switch statement. An advantage of using the switch statement is that it uses less code, which is better if you have a lot of conditions that you need to check for.

Example Switch statement:

JavaScript If Statements - XI

When you write code, you will often need to use conditional statements.

A conditional statement refers to a piece of code that does one thing based on one condition, and another based on another condition. In fact, you could have as many conditions as you like.

JavaScript If statements are an example of conditional statements. With If statements, you can tell the browser to execute a piece of code only if a given condition is true.