Get started with the JavaScript language, Part 2: Events, cookies, timing, and more

JavaScript has become increasingly popular and is arguably one of the most widely used languages on the Internet. It can be used cross-platform and cross-browser, and it does not discriminate against back-end languages. Many great libraries are available to help with development, but sometimes, these libraries are so removed from the original language that beginning developers lack an understanding of the language fundamentals. This article, part 2 in a series, continues the fundamentals of JavaScript with events, try...catch statements, cookie use, and timing functions.

Share:

Kris Hadlock (kris@krishadlock.com), Web Developer/Designer, Studio Sedition

Photo of Kris HadlockKris Hadlock has been a contract web developer and designer since 1996. He has worked on projects for companies such as SPIN Magazine, IKEA, United Airlines, JP Morgan Chase, GoDaddy Software, and Fire Mountain Gems. He is the author of Ajax for Web Application Developers (Sams) and The ActionScript Migration Guide (New Riders) as well as a featured columnist and writer for numerous websites and design magazines, including Peachpit.com, InformIT.com, and Practical Web Design magazine. Kris is also the founder of www.studiosedition.com, a web design and software development studio specializing in fusion of form and function.



02 August 2011

Also available in Chinese Russian Japanese

The first "Get started with the JavaScript language" article covered many of the absolute fundamentals in the JavaScript language, from creating script tags to using comments, including JavaScript files in your HTML documents, defining variables, using operators, defining arrays, using conditional statements, defining functions, and using loops. This article picks up where the previous article left off by explaining additional basic JavaScript language concepts to give beginners a foundational understanding of the language. The fundamentals covered in this article provide you with a better understanding of the libraries you use, how to make a decision on whether you need to use a library at all, and possibly even give you the courage to write your own library. Code examples are provided throughout to show how it's all done.

Develop skills on this topic

This content is part of a progressive knowledge path for advancing your skills. See A comprehensive guide to JavaScript.

Events

Events are the catalyst for adding any type of interactivity to a web page with the JavaScript language. Every HTML element has associated events that you can use to trigger JavaScript code. For example, an input field has many possible events: You can associate the focus event to trigger JavaScript code when someone clicks in or tabs to an input field, or you can associate a blur event to trigger JavaScript code when someone clicks outside or tabs out of a focused input field. After you've associated your event, the possibilities are endless. For example, the blur event can trigger JavaScript code that checks whether the input field has valid data and, if not, a message can be displayed inline and as automatic feedback. The following code provides an example of how the focus and blur events can be used to display default text in an input field:

<input type="text" name="email" value="Enter your email address" 
   onfocus="this.value = '';" onblur="if(this.value == '') 
   this.value = 'Enter your email address';" />

Here you have an input field with a default value; therefore, the input field shows the text "Enter your email address" when viewed in a web browser. To make this default text disappear when someone clicks in or tabs to the field, you use the focus event and set the value of the field to an empty string. If someone clicks outside or tabs out of the input field, you use the blur event to show the default text again; otherwise, you leave their custom text.

Every HTML element has events associated with it. Table 1 lists a few of the most common HTML elements and their associated events.

Table 1. Common elements and their associated events
ElementEvents
bodyonload, onunload
inputonfocus, onblur, onchange, onkeydown, onkeypress, onkeyup
formonsubmit
imgonmouseover, onmouseout, onclick

Try...catch and throw

Try...catch statements provide you with a way to test code for errors without sending the error to the browser or presenting a custom error. If a JavaScript error is not within a try...catch statement, none of the proceeding JavaScript code is executed, and the browser is left to its own form of handling and displaying the error. You use the try portion of the statement to execute JavaScript code; the catch portion handles errors that may have occurred in the try portion. You could use this construction when executing code that may not work in certain browsers. If this code were within a try...catch statement, it would simply not execute if it returned an error and the catch portion would handle the error. This error could be an actual error message, or it may do nothing based on whether the user needs to know that it occurred.

Handling errors with try...catch

The catch portion of the statement also includes a default parameter for the error object. The error object returns pertinent information about the error that occurred in the try portion of the statement. The error object has two properties: message and line. The message provides text that states the exact error that occurred; the line provides the exact line of code where the error occurred. Listing 1 shows an example of a try...catch statement that uses the error object to alert the message and the line. Of course, this information would only be useful in a debugging situation, but these properties can become useful when attempting to provide feedback to a user about an error that occurred without relying on the browser to handle it.

Listing 1. Using the error object in a try...catch statement to debug an error
try
{
   // Attempt to execute code that produces an error here
}
catch(err)
{
   var txt = err.message +'\n';
   txt += err.line;
   alert(txt);
}

Creating error exceptions with the throw statement

The try...catch construction provides great error-handling capabilities, but you can take it a step farther by using the throw statement. The throw statement lets you create error exceptions based on certain conditions, which provides the perfect opportunity to create more user-friendly error messages that are accurate and in plain English. Listing 2 shows a simple example of how you can use the throw statement to create an error exception based on a condition in the try portion of the try...catch statement.

Listing 2. Using the throw statement to create an error exception
<script type="text/javascript">
var x=prompt("What type of music is Led Zeppelin?","");
try
{ 
   if(x != 'rock and roll')
   {
   throw "Err1";
   }
}
catch(er)
{
   if(er=="Err1")
   {
   alert("Sorry, you're wrong.");
   }
}
</script>

Notice that try, catch, and throw are all written in lowercase letters: Using uppercase letters generates a JavaScript error.


JavaScript lets you create several types of pop-up boxes. The most common types—and the boxes discussed here—are alert boxes, confirm boxes, and prompt boxes.

Alert box

Not commonly used for their original purpose, alert boxes are a quick and easy way to display page errors, warnings, or other important messages. These days, alert boxes are most commonly used as a way to debug JavaScript code, so it's fair to say that they still have their place—it's just not a best practice to use them for their originally intended purpose. Also, if you use Mozilla Firefox, Apple Safari, or Google Chrome, you can simply use the console.log file for debugging purposes. The bottom line is that when all else fails, alert is a viable alternative and gets the job done. Creating an alert box is extremely easy: Simply type the alert function as a line of code and pass it an argument; it will open a window with the value of whatever you pass to it. For example, you can type in a simple string, or you can use the alert to display the value of a variable by passing it as an argument, which is a good example of how alert could be used for debugging. Here is a basic example of how you can use the alert function to generate an alert box:

alert("This can be a variable or a simple text string");

Confirm box

You use confirm boxes to verify an option a user has made on your website. For example, if you were the developer of a web application and a user had chosen to delete his or her user account, it would be a good idea to confirm that choice before allowing the user to proceed with submitting a request.

Typically, the confirm function is written into a conditional statement first to confirm that the user is intending to proceed with the choice made, and then, based on that decision, to determine whether to execute JavaScript code. Here's an example using the confirm function in a condition to determine which JavaScript code to execute:

if(confirm("Click for a response"))
{
    alert('You clicked OK');
}
else
{
    alert('You clicked Cancel');
}

Prompt box

When looking for a quick way to ask a question and allow a user to provide an answer, look no farther than prompt boxes. Typically, today's web developers are opting for custom inline pop-up windows. That said, prompts still exist, and they still have their place, especially when debugging. The prompt function, which is used to generate a prompt box, takes two parameters. The first is a custom text string, which is typically a question or statement prompting the user for some sort of response; the second parameter is a text string that is used as the default value for the text input that appears in the prompt box. The default value is optional, and you can change it during run time. Here is an example of the prompt function being used to ask a question of the user, and then showing the user's response in an alert box, using the return value from the prompt function:

var response=prompt("What is your favorite band?","Led Zeppelin");
if (response!=null && response!="")
{
   alert("response: "+ response);
}

Using cookies

Cookies exist to store data on the client side that your JavaScript code can later retrieve and reuse. Storing data on users' computers has many benefits when used wisely. You can use cookies to customize users' experience, determine how to present information to them based on prior actions, and so on. An example of cookie use includes storing a visitor's name or other pertinent information that can later be used to display on a website. A cookie is a text file stored in a visitor's web browser that includes a name-value pair, an expiration date, and the domain and path of the server it should be sent to.

Creating a cookie is simple: You just need to determine the information that you want to store, the duration of storage, and what you will name the cookie for future reference. However, although the creation is simple, the syntax is a bit tricky, and you need to get it right for it to function properly. The following code shows an example of how to create a cookie and store data in it:

document.cookie =
  'cookiename=cookievalue; expires=Sat, 3 Nov 2001 12:30:10 UTC; path=/'

The first part of the string stored in the cookie is the name-value pair, which is cookiename=cookievalue. A semicolon (;) separates the pair from the second part. The second part of the string is the expiration date in the correct format, followed by a semicolon to separate it from the third and final part, which is the path.

Storing data in a cookie requires a bit of tricky syntax, but it is simple to retrieve the cookie value by name at a later date. Here's how to retrieve a cookie value by name:

alert(document.cookie);

This code gets you the cookies for the current domain; however, more than one cookie may be saved to a domain, and the document.cookie is an array. Therefore, to retrieve the value of a specific cookie, you need to target it properly. You're in luck: The custom function in Listing 3 makes it as easy as passing the cookie name as a parameter and receiving the cookie's value.

Listing 3. Retrieving data from a stored cookie
function getCookie(c_name)
{
var i,x,y;
var cookieArray = document.cookie.split(";");
for (i=0;i<cookieArray.length;i++)
{
  x = cookieArray[i].substr(0,cookieArray[i].indexOf("="));
  y = cookieArray[i].substr(cookieArray[i].indexOf("=")+1);
  x = x.replace(/^\s+|\s+$/g,"");
  if(x == c_name)
  {
	  return unescape(y);
	  }
	}
}
alert(getCookie('cookiename'));

As you can see, cookies offer powerful functions and provide the ability to create a custom experience for your visitors or simply store data that can be used at a later date.


Timing

JavaScript offers several functions that let you control and set the timing of certain actions. The most common such functions are:

  • setInterval
  • clearInterval
  • setTimeout
  • clearTimeout

The setInterval function

In certain situations it is necessary to execute JavaScript code repeatedly without any user interaction. The setInterval function lets you do so easily. setInterval takes two required and one optional argument. The first required argument is the code that you want to execute repeatedly; the second argument is the milliseconds, which define the duration of time between each JavaScript code execution. The third, optional parameter is an argument that can be passed to a function call made through the code parameter. The duration you set between intervals can be a bit strange at first, as it's defined in milliseconds. So, if you want the interval to run every second, you would use 1000 milliseconds, 2000 milliseconds for 2 seconds, and so on. Table 2 lists each parameter and its role in the setInterval function.

Table 2. Parameters available to the setInterval function
ParameterRequired or optional?Description
codeRequiredJavaScript code that the setInterval function executes; this code can be custom or a function call.
millisecondsRequiredThe duration of time, in milliseconds, between each code execution.
argumentOptionalA useful parameter used to pass arguments to a function when a function is used as the code parameter.

The code that follows provides an example of how to use the setInterval function to execute another function every 10 seconds and pass an argument to it. The argument value can then be accessed within the executed function. This argument can be a variable, an object, or a simple text string, as in this example:

setInterval(myFunction, 10000, 'sample');
function myFunction(myArg)
{
   alert('myFunction argument value: '+ myArg);
}

If you want to end an interval, there's a function for that, as well.

The clearInterval function

Ending an interval requires the clearInterval function. However, the original interval you created must include a variable name to later reference it with clearInterval. The following code provides an example of how the clearInterval function references the variable that is previously set to an original setInterval:

var myInterval = setInterval(myFunction, 10000, 'sample');
function myFunction(myArg)
{
   alert('myFunction argument value: '+ myArg);
   clearInterval(myInterval);
}

As you can see, you have assigned a variable name to the original setInterval function and named it myInterval. You can then use myInterval later to reference the setInterval function and change the variable or stop the original interval using the clearInterval function. In this example, the function is only called once, because the clearInterval function is executed in the first function call.

The setTimeout function

The setTimeout function is similar to the setInterval function in that it can execute code or another function based on a certain time constraint. Even the parameters are the same as for setInterval (see Table 2). However, the big difference is that the setTimeout function only executes the code one time rather than repeatedly. Here's an example of how you can use the setTimeout function to execute a function after 10 seconds:

setTimeout(myFunction, 10000, 'sample');
function myFunction(myArg)
{
   alert('myFunction argument value: '+ myArg);
}

setTimeout is useful in situations where you want to execute certain code, but you don't want to execute it immediately. It's essentially a way to delay code execution.

The clearTimeout function

If for some reason you had a change of heart and needed to cancel the setTimeout interval, the clearInterval function can handle the job. As with the clearInterval function, you assign a variable name to the setTimeout function to later reference it and stop it using clearTimeout. The code that follows provides an example of how to use clearTimeout to stop a setTimeout call:

var myTimeout = setTimeout(myFunction, 10000, 'sample');
function myFunction(myArg)
{
   alert('myFunction argument value: '+ myArg);
   clearTimeout(myTimeout);
}

Here, you have assigned a variable name to the original setTimeout function and named it myTimeout. You can then use myTimeout to reference the setTimeout function and stop it using the clearInterval function.


Conclusion

JavaScript is arguably one of the most popular programming languages, and now you can see why. There are so many possibilities with this simple but rich scripting language, and the fact that it provides the tools to allow website visitors to interact with a web page after it has been downloaded is powerful. This article has laid the foundation for understanding the fundamentals of the JavaScript language: The next step is to put these concepts into practice and begin to explore JavaScript objects.

Resources

Learn

Get products and technologies

  • When you achieve a fundamental understanding of the JavaScript language, the jQuery library is a good way to speed up development.
  • The Dojo Toolkit, an open source modular JavaScript library, helps you quickly develop cross-platform, JavaScript/Ajax-based applications and websites.
  • Try out IBM software for free. Download a trial version, log into an online trial, work with a product in a sandbox environment, or access it through the cloud. Choose from over 100 IBM product trials.

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development
ArticleID=750307
ArticleTitle=Get started with the JavaScript language, Part 2: Events, cookies, timing, and more
publish-date=08022011