Introduction to JavaScript

JavaScript is a tool for creating conditional (if...then) content. Using JavaScript, you can create a page such that

In addition, in this course we will use JavaScript to illustrate how to program online calculators, search functions, and database query engines. However, in a real web site, it might be better to perform this function using programs on the server instead of JavaScript code.

Getting Ready

When you write scripts, you will want to debug them. You need to set your browser to do that. In Internet Explorer, go to tools/Internet options. Pick the "advanced" tab, and then check the box next to "Display a notification about every script error."

As with CSS, it is good practice to write your JavaScript code on a separate page from your HTML page. If you have not already done so, create a subdirectory called scripts under htdocs. From notepad, save as type "all files" a file called myjs.js under this scripts subdirectory.

Now, open up another copy of notepad for your HTML page. Save it as firstscript.html.

Your First Scripts

Here is some JavaScript code to try, along with the HTML page that uses the code:

/* This is the page that will be saved as myjs.js */
/* 1. This is our first function. All it does is say hello */
function sayhello(){
document.write ("Hello, world.<p>");
}

/* 2. This function detects the user's browser version and prints it out */
function browserReport(){
browser_version = navigator.appVersion;
document.write("Your browser is " + browser_version + "<p>");
}

/* 3. This function reacts when the user presses a button */
function alertUser(){
alert("You got me")
}

</script> </script> </script>

I will explain what is going on. First, however, copy the script page and copy the HTML page. Save the pages, and make sure that they work. When you view the HTML page through your browser, you should see some of the output of the script page. You also should see a button, and when you click the button you should see the alert message.

Note some similarities between JavaScript and CSS.

However, there are some important differences between JavaScript and CSS.