Introduction to JavaScript: Part 3 of 3

In the first two parts of the JavaScript article we introduced alerts, writing text to a webpage using document.write, functions, adding external JavaScript files, event handlers, manipulating the DOM and creating cookies. This article will explore browser detection, form validation and drop down navigational menus.

If you read the previous parts of this article, you can skip the next section about using WebMatrix. If you skipped the other parts of 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 www.microsoft.com/web/webmatrix.

Create a new Webpage with WebMatrix

WebMatrix gives you a number of different ways that you can create a new website. 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 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.

image

For this article we will be using an empty site. Click "Templates" on the WebMatrix welcome screen. Choose "Empty Site" and give your site a name.

image

We will be taken to our WebMatrix workspace.

image

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 a mostly-empty folder on the left. This is your website.

image

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 on "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. Like our previous examples, we can use a simple HTML page.

image

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

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        
    </body>
</html>

Browser Detection

In a perfect world all browsers would be compatible. But, in the real world not all versions and types of browsers are compatible. Sadly, some JavaScript just doesn't work on certain browsers. In order to make your webpage the most compatible it can be, JavaScript can be used to detect your visitor's browser. You can write functionality on your webpage that works with whatever browser your visitor is using.

JavaScript has a Navigator object which will detect the browser and the version. And best of all, the Navigator object is easy to add to your page!

Let's add a Navigator object script to our webpage. Between <head> </head> of your page, add:

<script type="text/javascript">
    document.write("Browser Name: " + navigator.appName);
    document.write("<br />");
    document.write("Browser Version: " + navigator.appVersion);
</script>

Run your page. Our JavaScript will write the browser name and browser version to our webpage

image

Once we have retrieved what browser our visitor is using, we can write code that acts a certain way depending on the browser. A simple example of this is:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script type="text/javascript">
            var browserName =  navigator.appName;
            if (browserName == "Microsoft Internet Explorer") {
                document.write("You are using IE");
            } else if (browserName == "Netscape") {
                document.write("You are using a Netscape browser");
            } else {
                document.write("You are using a browser other than IE and Netscape!");
            }
        </script>
    </head>
    <body>
    </body>
</html>

Here we retrieve the browser name and store it into a variable. We then check if our browser is IE or Netscape. We then print a corresponding message.

Run your page. If you are viewing your page with IE, you will see:

image

Browser detection is important to include on your webpage in order to make it the best it can be! Isn't it important that everyone can view your page properly?

Form Validation

HTML forms are an important part of sending data to a server from a webpage. Validating this data before it is sent to the server is even more important. JavaScript can be used to validate form data by checking if required fields are empty, a valid email or date were entered, or even if text was entered into a numeric field.

One of the easiest ways to validate a form using JavaScript is to check if any of the required fields are empty. This can be done with a simple function and the form's "onSubmit" event.

First things first, we need a form on our webpage. Add to the <body> of your webpage:

<form name="myForm" onsubmit="validateForm()" >
   First Name: <input type="text" name="firstName" /><br />
   Last Name: <input type="text" name="lastName" /><br />
   Email: <input type="text" name="email" /><br />
   <input type="submit" value="Submit" />
</form>

This is a simple form with three input boxes and a submit button. Notice that we have already defined our form's onsubmit event with a function called "validateForm." Let's write that function now.

In the <head> of your page, add:

<script type="text/javascript">
  function validateForm() {
    if (document.myForm.firstName.value == "" || document.myForm.lastName.value == "" || document.myForm.email.value == "") { 
      alert("You have not filled in all the required fields!");
    }
  }
</script>

Our form's validate function checks if there are values for our three input boxes using JavaScript's document object. If our three input boxes values are equal to "" (or empty) we alert the user that part of the form is empty.

Run your webpage. You should see a simple form with our three input boxes and a submit button.

image

If you submit the form with at least 1 input box empty, you will receive an alert notifying you that you have not filled in the required fields.

image

Checking if the input fields are empty is one of the easiest ways to ensure that the correct data is being sent to the server when the form is submitted. You can add even more form validation methods with JavaScript in order to ensure that the data being sent to the server is the data that you want!

Drop Down Navigational Menus

Drop down navigational menus are an easy way to add style to your site. You may have seen numerous sites with drop down menus and wondered "how do I do that?" Adding a drop down menu is as simple as adding an unordered list, a little bit of CSS, and some JavaScript!

The first thing we need to do to add a drop down menu is to create an unordered list. The most popular way to implement a drop menu is using an unordered list and then using CSS to stylize it.

Add a nested unordered list to the body of your page. In order for the menu to be drop down, we need a nested unordered list. Add something similar to this:

            <ul id="menu">
                <li><a href="#" onmouseover="hide('submenu')">Home</a></li>
                <li><a href="#" onmouseover="hide('submenu')">About</a></li>
                <li><a href="#" onmouseover="show('submenu')" >Products</a>
                    <ul id="submenu">
                        <li><a href="#">Cupcakes</a></li>
                        <li><a href="#">Cakes</a></li>
                        <li><a href="#">Fruit Tarts</a></li>
                    </ul>
                </li>
                <li><a href="#" onmouseover=" hide('submenu')">Contact</a></li>
            </ul>

We now have a simple, nested unordered list. Notice that we have already defined our mouse over events. We will write these later. But first, let's add some CSS to make our unordered list appear as a horizontal menu.

You can create a separate CSS file and link it on your page by <link rel="stylesheet" type="text/css" href="menu.css" />. You can also add the style to the head of your page using the <style> tags. Either way is fine but since we will have quite a bit of CSS, we will create an external CSS file.

Add the styling for our menu:

#menu li {    
    float: left;
    font: 12px tahoma;
    list-style: none;
}

#menu li a {    
    display: block;
    margin: 1px 1px 1px 1px;
    padding: 5px 5px;
    width: 75px;
    background: black;
    color:white;
    text-decoration: none;
    text-align: center;
}

#menu li a:hover { background: purple}

#submenu {    
    position: absolute;
    visibility: hidden;
    margin: 0;
    padding: 0;
    background: black;
    font: 12px tahoma;
}

#submenu li {    
    float: left;
    font: 12px tahoma;
     list-style: none;
    float: none;
}
    
 #submenu li a {    
    position: relative;
    padding: 5px 10px;
    text-decoration: none;
    text-align: left;
    background: black;
    color: white;
} 

#submenu a:hover { background: purple; } 

You can change the widths, margins, padding, and colors to your preferences.

And now for the JavaScript! If you noticed earlier, we defined 2 JavaScript functions that we use to hide and display our submenus. We will write these in the <head> of our page

        <script type="text/javascript">
            function show(id) {
                document.getElementById(id).style.visibility="visible";
            }
            
            function hide(id) {
                document.getElementById(id).style.visibility="hidden";
            }
        </script>     

We call these JavaScript functions when we want to show our submenu or when we want to close it using the mouse over event. You can us this same idea of changing the css style visiblity from hidden to visible to write even more complex functions. This is just a simple example to get you started.

Our whole code should look like this:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
        <link rel="stylesheet" type="text/css" href="menu.css" />
        <script type="text/javascript">
            function show(id) {
                document.getElementById(id).style.visibility="visible";
            }
            
            function hide(id) {
                document.getElementById(id).style.visibility="hidden";
            }
        </script>        
    </head>
    <body>
            <ul id="menu">
                <li><a href="#" onmouseover="hide('submenu')">Home</a></li>
                <li><a href="#" onmouseover="hide('submenu')">About</a></li>
                <li><a href="#" onmouseover="show('submenu')" >Products</a>
                    <ul id="submenu">
                        <li><a href="#">Cupcakes</a></li>
                        <li><a href="#">Cakes</a></li>
                        <li><a href="#">Fruit Tarts</a></li>
                    </ul>
                </li>
                <li><a href="#" onmouseover=" hide('submenu')">Contact</a></li>
            </ul>
    </body>
</html>

If we were to run our page, our menu would look like this:

image

Mousing over the different menu links will cause our drop down menu to appear and disappear.

Conclusion

This was a brief introduction to JavaScript. JavaScript can be used for much more than the examples provided in these articles. These articles are merely a starting point.

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!