Introduction to JavaScript, Part 1 of 3

JavaScript. You may not have heard it, but if you’ve used the internet, then chances are you have seen JavaScript working on a webpage without even knowing it! JavaScript is the most popular scripting language used by developers to add interactivity to webpages. JavaScript uses client-side scripting, meaning that the client side (the web browser) is running the script. Once the page (or browser) is closed, the script will stop running.

JavaScript can make your webpage dynamic in many different ways. It can write text, it can react to events (like a button being clicked or the page being loaded), it can change the content of the page, it can add or remove HTML elements, it can validate form data, it can detect which browser a visitor is using, it can create cookies, and many other things.

Learning JavaScript

This article is in three parts. The first article will introduce JavaScript and will demonstrate a few simple examples to make your webpage dynamic. Article 2 will delve into JavaScript even further, showing how to use events, manipulating the DOM to change the page’s content and creating cookies. Article 3 will provide even more advanced examples of JavaScript such as form validation, drop down navigational menus, and browser detecting.

In this article, we will be using WebMatrix. Microsoft WebMatrix is a free tool that allows you to create, customize and publish websites. It’s amazingly easy to use, and can be downloaded from http://www.microsoft.com/web/webmatrix.

WebMatrix gives you a number of different ways that you can create a new web site. You can use an existing open source application such as WordPress, Joomla, DotNetNuke or Umbraco, or you can create a site yourself by either coding everything or by using a small, simple template.

Open WebMatrix once it is downloaded and installed. On the WebMatrix Welcome Screen you will see the different options you have for creating a new application.

clip_image002

Figure 1. WebMatrix Welcome Screen

Create a WebMatrix Webpage

For this article we will be using an empty site. Click “Site From Template” on the WebMatrix welcome screen. Choose “Empty Site” and give it a name.

clip_image004

Figure 2. WebMatrix Site from Template Screen

We will be taken to our WebMatrix workspace.

clip_image006

Figure 3. WebMatrix Workspace

Before we can create a new webpage, we have to navigate to our files workspace. To get to our files workspace, click on “files” on the lower left of WebMatrix or “Browse your files” in the middle of your screen.

When you get to your files workspace you will see an empty folder on the left. This is your website.

clip_image008

Figure 4. WebMatrix Files Workspace

We now need to create a new webpage. You can do this by clicking on the “new” icon on the menu ribbon or by clicking “Add a file to your site” in the middle of your screen.

A popup box will appear. Here we can choose what type of file we want to create. For this example, we can use a simple HTML page. JavaScript was created to provide dynamic functionality to static HTML webpages.

clip_image010

Figure 5. Create new File

We will now have an empty, HTML5 compatible webpage open.

clip_image011

Add a Script to your Webpage

Adding JavaScript to your webpage is so easy! All JavaScript code must be inside a <script> tag. Commonly, <script> tags will appear in the page header <head> but this is not required. A <script> tag can appear anywhere on the HTML page. Also, you are not limited to 1 <script> tag per page; you can have as many scripts on your page that you want!

Note: For this example, we will place all of our JavaScript in the page <head>.

Let’s add some simple JavaScript to our webpage. Somewhere after <head> and before </head>,

Add:

 

 

<script type="text/javascript">

</script>

Notice, we define the MIME type of our script. The browser uses this information to determine if they can handle the scripting language. Not all browsers support all type of scripts! With HTML5, the language and type attributes are no longer required but for this example, we will still define our script type.

 

 

You page should look similar to this:

clip_image012

Run your page by clicking on “Run” on the menu ribbon.

clip_image014

This will run your page on your local host. Notice your page is blank. That’s because we haven’t written any JavaScript code yet!

clip_image016

 

 

Add a JavaScript Alert to your Webpage

Alerts are one of the most basic JavaScript functions. A JavaScript alert is a popup box, containing some sort of information where the user will have to click “Ok” to continue. Alert boxes can be triggered by the page loading, a visitor clicking a button, or even moving the mouse over an element.

Alerts are easy to add to your webpage with one line of code!

Head back to your WebMatrix webpage.

After:

<script type="text/javascript">

And before:

</script>

Add:

alert("<your text here>");

Replace <your text here> with whatever text you want to appear in the alert box. Make sure your text is within “ “ or ‘ ‘. This tells the alert that your text is a string.

Your code should look something like this:

clip_image018

Run your file. An alert box should popup as the page loads, displaying your text.

clip_image020

Alert boxes are not restricted to strings. They can also display numbers and variables. You can also combine variables, numbers, and strings. This can be done using the + sign.

For example, if our code were to look like this:

clip_image022

In the code we have created a string variable with a value. We then combine our variable with a string and a number using the + sign. Notice in our alert text that our message variable and number do not have quotes around them. This tells the script that these elements are not strings.

Running our page would cause this alert box to popup:

clip_image024

 

 

Adding Text to our Page with JavaScript

Another basic JavaScript command is document.write. It will print the text to your webpage. Similar to alerts, document.write can print strings, variables, and numbers. You can also combine these elements by using the + sign. Unlike alerts, you can define HTML elements within the document.write statement.

Let’s add a document.write statement to our WebMatrix webpage. In our file,

Somewhere after:

<script type="text/javascript">

And before:

</script>

Add:

 

 

var name = "Mickey Mouse"

document.write("Hi " + name);

You code should be similar to this:

 

 

clip_image026

Run your webpage. You will see that our script wrote our text on our webpage.

clip_image028

Now, we can add HTML elements to our document.write statement. If we wanted our “Hi” text to be a header, we can simply add the <h1></h1> tags around it. If our code looked like this:

clip_image030

Running our page look like this:

clip_image032

Notice that since we defined “Hi” as a header, it is written to our page as a header.

JavaScript Functions

One of the easiest ways to write JavaScript is to use functions because they give you more control over your code. A function is code that you can control to run at a specific time as functions do not run automatically. One reason to use functions is to stop the browser from executing the script when the page is loaded. Functions are executed when they are called, which can occur by an event (like a mouse click) or by another function. Event handlers will be introduced in part 2 of this article.

All functions have the same layout:

 

 

function uniqueName() {

// put your JavaScript your code here

}

Note: all functions must have a unique name!

 

 

Let’s look at an example of using a JavaScript function. Say we want to gather input from our user (a number) and multiply their response by 15. We then want to write the answer to our page.

Look at the code below to see how we can do that.

clip_image034

We have a function called writeMessage that uses a prompt window to retrieve input from the website’s visitor. It stores the visitor’s response into a variable. This variable is then multiplied by 15 and the value is saved into another variable. The answer is then written to the page using the document.write command (which was discussed earlier in this article).

If we were to run our page without calling our function somewhere, nothing would happen! We must call our function somewhere in order for it to run. As noted earlier, we can place <script> tags anywhere on our webpage. We place a <script> in the body of our page with a call to our writeMessage function. This means that our function will be called when the browser renders the page’s body element.

If we run our page, we will immediately receive a prompt window.

clip_image036

Enter a number and hit “Ok”. We will now see our page with the answer of our number * 15.

clip_image038

This is just a simple example of how functions work. Since we have our function called in the page’s <body>, we can do the same thing without a need for a function. Part 2 of this article will work with functions even more.

Using an External JavaScript File

In addition to being able to place JavaScript anywhere on your page, you can also place it in an external file! This is great because it allows you to use the same code on multiple webpages. Instead of having to add the code to each page (and subsequently changing it on each page), you can place links to the JavaScript file in the <head> of each page you wish to use the script on. When you need to change or add to the code, you can simply change the one file and have it reflected on all webpages! This idea is similar to using external CSS files.

Adding an external JavaScript file is simple and can be done in 1 line of code! But, before we can add a JavaScript file, we will need to create one.

In WebMatrix, click the “New” button on the menu ribbon. To create a JavaScript file, select “JScript” and give your file a name.

clip_image040

We will now have a blank document. Notice, this document is completely blank unlike the blank HTML page (which contained the basic structure of an HTML page). Since our file is a JavaScript file, we do not need to (and should not) define <script> tags like we had to in our HTML document.

We can add some simple code to our JavaScript file. In the blank page add:

alert("hello world");

Now we need to link our JavaScript to our webpage. You can create a new webpage or use one you already have. In the file, somewhere after <head> and before </head>, add:

<script src="example.js" ></script>

That’s all we have to do to link our external JavaScript file!

Run your page. You should receive an alert saying “hello world”.

clip_image042

You can have more complex JavaScript code in your external JavaScript file. The external file is meant to replace any script code you would have in the <head> or <body> tags of your page. External files are especially nice if you have long, complex JavaScript code.

This was a quick and simple introduction to JavaScript. There are 2 more articles on JavaScript discussing event handlers, manipulating the DOM, creating cookies, browser detection, form validation and even navigation menus. Read on to learn how to make your webpages dynamic with JavaScript!

You can discuss this article using the adjacent Facebook talkback.

For technical questions please visit our discussion forums, where we have a vibrant community of developers like you, as well as Microsoft engineers who are ready to answer your questions!