Introduction to JavaScript: Part 2 of 3

In the first part of the JavaScript article we introduced alerts, writing text to a webpage using document.write, functions, and adding external JavaScript files. In this part of the article we will look at event handlers, manipulating the DOM, and creating cookies.

If you read the first part of this article, you can skip the next section about using WebMatrix. If you skipped the first part of this article, we will be using Microsoft’s new, free tool called WebMatrix. WebMatrix allows you to create, customize, and publish websites. It's amazingly easy to use, and can be downloaded from www.microsoft.com/web/webmatrix.

Creating a 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>

Now let’s get started adding JavaScript!

Using Events

One of the most popular ways to use JavaScript is through event handlers. Elements on a webpage can have triggers, which cause some event to happen. This can occur by a mouse click, the page loading, moving the mouse over something, moving the cursor in or out of a form, and many more. In part 1 of this article, we introduced functions. Events normally occur through a function. This means, calling a function will cause the event to occur on the page.

One of the most popular JavaScript events is “OnClick.” This event occurs when an element on the webpage is clicked. This functionality can be added to a link or a button. Let’s take a look at how we would add an onclick event to a webpage.

Open your webpage. First thing we can do is add a button. Somewhere in the <body> of our file, add:

<input type="button" value="Click Me" />

Now that we have our button we can add our event with a function. Between <head></head> of your file, add:

<script type="text/javascript">             
</script>

Now we can write our function that will be triggered by clicking our button. Between <script></script>, add:

function ourEvent() {
     document.write("We just wrote our first event!");
}

So how do we add a trigger for our function? Simple, it’s an attribute for our button. Go back to our button and replace:

<input type="button" value="Click Me" />


With:

<input type="button" value="Click Me" onClick="ourEvent()" /> 

We just added our onClick event to our button. Notice that our function call consists of our function name with () brackets. This is required when a function is called anytime!

Run your page (by clicking the “Run” button on the menu ribbon). Your page will open in your browser with a button.

image

Once you click on the button, your function will be called. Our button is replaced with the text we defined with our document.write command in our function.

image

Our whole code should look like this:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script type="text/javascript">
            function ourEvent() {
                document.write("We just wrote our first event!");
            }
        </script>
    </head>
    <body>
        <input type="button" value="Click Me" onClick="ourEvent()" />
    </body>
</html>

Adding events to your webpage is that easy! The make our webpage even more dynamic, we can manipulate the DOM to change our page’s content. We will see how to do that in the next section.

Manipulating the DOM

The Document Object Model (DOM) is the structure (or model) of a document. With a valid DOM document, you have the ability to manipulate the document! Getting access to objects in your documents means you can add elements, change elements, or delete elements from your page. We can manipulate the DOM using JavaScript events.

One of the first steps to manipulate the DOM is to get the page’s element that you wish to change. You can retrieve a page’s element three different ways: getElementById, getElementsByTag, getElementsByTagName. The easiest way is getElementById but this requires that the element have an id that you know.

Let’s first change content on our page using an onClick event. We need to add content to our page before we can change it. In the <body> of our webpage, add:

<div id="mydiv">
     <p id="first">This is my first paragraph.</p>
     <p id="second">This is my second paragraph.</p>
</div>
<input type="button" value="click me!" onclick="manipulateDOM()" />

Now we have a <div> with some content and a button with an onclick event calling the function manipulateDOM(). We can now write our function manipulateDOM.

Between <head> and </head>, add:

<script type="text/javascript">
     function manipulateDOM() {
          var somep = document.getElementById("first");
          somep.innerHTML = "I just changed this text using the DOM!"; 

          document.getElementById('second').innerHTML = "This text is also changed!";
     }
</script>

Our function retrieves our <p> with the id of “first”. We then set the <p>’s value (using .innerHTML) to a new string. We then change the text of our second <p> (with an id of “second”) with 1 line of code. Both ways work so use whichever way that makes sense to you!

Run your page. We have two paragraphs and a button. Our text will change when we click the button because our function will be called.

image

Once we click the button, our text will change.

image

Wasn’t that easy? You can do more than change text; we can add and remove elements from our page. Take a look at the following code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
            <script type="text/javascript">
           function manipulateDOM() {
                changeObjects();
               removeObjects();
                addObjects();
            }
        
            function changeObjects() {
                var somep = document.getElementById("first");
                somep.innerHTML = "I just changed this text using the DOM!"; 
                document.getElementById('second').innerHTML = "This text is also changed!";
            } 
            
            function removeObjects() {
                var parentDiv = document.getElementById('mydiv');
                var headerRemoved = document.getElementById('myHeader');
                parentDiv.removeChild(headerRemoved);
            }
            
            function addObjects() {
                var parentdiv = document.getElementById('mydiv');
                var newdiv = document.createElement('h3');
                newdiv.innerHTML = 'This is my new element!';
                parentdiv.appendChild(newdiv);
            }
            </script>
    </head>
    <body>
        <div id="mydiv">
        <h1 id="myHeader">This element will be removed when you click the button!</h1> 
            <p id="first">This is my first paragraph.</p>
            <p id="second">This is my second paragraph.</p>
        </div>
        <input type="button" value="click me!" onclick="manipulateDOM()" />
    </body>
</html>

In addition to the functions we wrote earlier, there are now a functions that will remove a <h1> and that will add a new <h3> to our page.

If you ran this code, you would see a <h1> tag, 2 paragraphs, and a button. Clicking the button will change the paragraphs text, remove the header and add a new <h3>.

image

Click the button. You will now see that the header has indeed been removed. The two paragraphs’ text has been changed. There is also a new <h3> on our page.

image

These are just a couple examples of how we could manipulate the DOM on our webpage with an onClick event.

Cookies

JavaScript can be used to add and retrieve cookies. Cookies are used to store information on a visitor’s computer. Some types of information that can be stored in cookies are a visitor’s name, password, and the date they last visited your site.

The most basic way to use a cookie is to simply store a name and the expiration date of the cookie. This can be done with a simple JavaScript function:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script type="text/javascript">
            function setCookie() {
                var today = new Date();
                var expire = new Date();
                expire.setTime(today.getTime() + 3600000*24*10);
                document.cookie = "Cookie name="+escape("cookie's value") + ";expires="+expire.toGMTString();
            }
        </script>
    </head>
    <body onLoad="setCookie()">
        
    </body>
</html>

We have a function that retrieves today’s date and then sets the expiration date to 10 days in the future. We then use document.cookie to set a cookie with a name, a value, and the expiration date. Our cookie will be set when the page loads.

Run your file. If you check your cookies, you will see you now have a cookie set under localhost (if you are running your page on your localhost) with a name and expiration date of 10 days from the current date.

Setting cookies are that simple. In addition to setting cookies, we can also delete cookies. Cookies can be deleted simply by setting a new value and expiration date before the current date. You can also set the expiration to -1 to have the cookie erased immediately. You can use the code below to delete a cookie:

document.cookie = "value=deletecookie; expires="+ -1;

For even more advanced examples of JavaScript such as form validation, drop down navigational menus, and browser detecting, continue on to part 3 of Introduction to 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!