JavaScript and Web Page Integration
 
 

HTML pages are usually integrated with JavaScript functions. Having knowledge in JavaScript is useless without knowing how to use it in your web pages.  JavaScript is the main scripting language used to make web pages dynamic after they've loaded into the reader's browser. Knowing how to edit values on your web page HTML is the first step in completing JavaScript knowledge and web page integration. 

Basic HTML Tags and the Id Property

There are two main identification tags in HTML: name and id. The name tag isn't used as much anymore as the id tag, and JavaScript provides a getElementById function that lets you easily grab an HTML element. Since you can only have one unique ID value per web page (meaning, you cannot have 2 elements with the same ID), you know when you use the getElementbyId function that you're only grabbing one element with an associated value. 

Take a look at the following HTML code to see an example of a div element with the id of "mydiv." 

<!DOCTYPE html>
<html>

<body>

<div id="mydiv">My First JavaScript code.</div>

</body>
</html>

The above code displays a simple static web page that displays the text "My First JavaScript code." Suppose you want to change that text to something different when the web page loads. You can perform this action using JavaScript. Let's add a JavaScript script snippet in the HTML code. 

<!DOCTYPE html>
<html>

<script>
    document.getElementById("mydiv").innerHTML = "My new JavaScript text.";

</script>

<body>

<div id="mydiv">My First JavaScript code.</div>

</body>
</html>

Notice the new JavaScript code is placed in the script tag. This tag indicates to the web browser that some kind of client-side expression is enclosed. In this example, the getElementById function is used, and the "mydiv" element id is specified. The "innerHTML" property is a part of the element's properties. What you place as the property value is added to the div's inner HTML and displayed. Instead of showing "My First JavaScript code" to the user, the inner HTML text is replaced with "My new JavaScript text." Note that if you specify an incorrect id value in the getElementById function, your JavaScript will throw an error. 

Event Handling

The previous section's code was a great first-time example of using JavaScript, but there is no control over when the code executes. Because the code isn't a function and nothing else displays on the page, the code doesn't depend on any user input. Normally, when you use client-side scripting, you run a function when an event happens. 

If you're new to programming, you might be new to events. Events are actions performed by users. They are always actions such as pressing a button, pressing a keyboard key or clicking a mouse button. Note that events are different from method actions, because events are always action input from the user. You tie JavaScript event handling with custom functions to define what happens when a user triggers an event. 

For example, using the above HTML and JavaScript code, suppose you only want to change the inner HTML of the "mydiv" div when the user clicks a button. In this case, the button event handler is the "onclick" action. By default, the button does nothing when the user clicks, but you can override the default and add your own custom JavaScript function to the onclick event. Take a look at the following code. 

<!DOCTYPE html>
<html>

<head>

<script> 

 function ChangeText() {

   document.getElementById("mydiv").innerHTML = "My new JavaScript text.";
}
</script>

<body>

<div id="mydiv">My First JavaScript code.</div>

<button type="button" onclick="ChangeText()">Change It</button>

</body>
</html>

Notice that we added a button that displays "Change It" to the user. The "onclick" event handler hooks the new "ChangeText" function to the click event. Instead of doing nothing, the function is called. In this example, the same code is executed that changes the inner HTML of the mydiv div to "My new JavaScript text." You'll use the onclick event handler several times in your coding career. It's one of the most common event handlers when coding client-side UIs in JavaScript. 

You can also make your functions with parameters. You pass parameters to the function when you call your events. Let's make our onclick event more dynamic and display text dependent on the button the user presses. 

<!DOCTYPE html>
<html>

<head>

<script> 

 function ChangeText(text) {

   document.getElementById("mydiv").innerHTML = text;
}
</script>

<body>

<div id="mydiv">My First JavaScript code.</div>

<button type="button" onclick="ChangeText('My new JavaScript text.')">Change It 1</button>

<button type="button" onclick="ChangeText('My other new JavaScript text.')">Change It 2</button>

</body>
</html>

Notice the ChangeText function takes one parameter. In this example, the function uses the parameter to display the text to the user. If the user presses the "Change It 1" button, "My new JavaScript text" is displayed in the div. If the user presses "Change It 2," the text "My other new JavaScript text" is displayed in the div. This is one example of making your JavaScript dynamic based on user input. Most JavaScript functions take some kind of input from the user, and you'll need to understand how to make it work within your HTML code. 

Working with Windows (Popups)

Interested in learning more? Why not take an online JavaScript course?

JavaScript has several main utilities you can use to work with browser properties and events. One object is the "window" object. This object handles all events and properties contained within the user's browser. A new window opens a new browser instance, so you can have multiple windows opened on the user desktop. Remember that client-side code runs on the user's desktop, which means that the user has some control over what type of actions you can perform. You should also be considerate of the user's desktop when you work with web applications. Browser popup blockers stop web applications from opening new windows, so you should be careful when relying on the window object in your JavaScript code. 

The most common window methods is window.open(). This method opens a new browser window on the user's desktop. Typically, you open a new window when a user clicks a button on your web page. For instance, you might want to open a new window when the user clicks a button to open a contact form that then sends you user feedback. You hook your JavaScript function to the button's onclick event and open a new window to take user feedback. Let's use this scenario for our next code example. Take a look at the following code. 

<!DOCTYPE html>
<html>

<head>

<script> 

 function OpenWindow(url) {

  var myWindow = window.open(url, "New Window", "width=200, height=100");
 myWindow.document.write("<p> This is a new window. </p>");
}
</script>

<body>

<div id="mydiv">My First JavaScript code.</div>

<button type="button" onclick="OpenWindow('contact.html')">Contact me!</button>

</body>
</html>

The above code is similar to the previous examples we used. We have the same button and text displayed when the user loads the page. We changed the function to "OpenWindow" with a url parameter. The url string passed is what the window.open() method uses when it opens a new window. After the window is opened, the document.write() method is called on the open window. Notice that the new "myWindow" object variable is specified. We can use the main page to edit code on the opened window as long as we assign the window object to a variable container. This is similar to previous lessons where we called methods specific to the object variable container. In this instance, the window container is the object, and we're using the object instance to edit the window's properties and call methods specific to that particular window. 

When the button is pressed, the "contact.html" URL is passed to the OpenWindow function. This URL is then used in the window.open method. The last string value in the window.open method is optional. These options tell the browser how to size the window. In this instance, the window dimensions are 200 in width and 100 for the height. The second window.open parameter is the name of the window, which is also optional. You can also call the window.open method with no parameters, which opens a default new browser window. You can use several options such as scrollbar, full screen, width, height and allowing the user to resize the window. All of these options are available when you use the windows object. 

Getting started with HTML and JavaScript takes some time when you're learning the language. Work with event handlers and test out the code for yourself to get a feel of how the client-side language works with the user's browser.

The Document Object Model (DOM)

When you work with JavaScript, you'll hear the term "DOM" repeated often. The DOM is the document object model. The DOM represents an HTML page and its elements. The root element is the HTML tag you use at the beginning and end of every HTML page. The root element then contains the head and body tags, which are the next part of the model. Think of the DOM as an HTML structure that has a main HTML root container. All tags within the body tag are also a part of the DOM. You can then use the DOM with JavaScript to dynamically edit your tag content. This lesson covers the basics of the DOM and how you can use it with JavaScript to create dynamic UI elements.

DOM Elements and Structure

The DOM is not unlike any other class object. You have a main DOM object (document) and methods and properties within the object. You can use the DOM to directly access elements within a page. You can access one element or several, which are returned in an array. In the previous lesson, we used the DOM's getElementById method that access one specific tag element. You can also access a group of elements using the getElementsByTagName. Take a look at the following code. 

<!DOCTYPE html>
<html>

<script>
    var tags = document.getElementsByTagName("div");

    tags[0].innerHTML = "My changed JavaScript code.";

</script>

<body>

<div id="mydiv">My First JavaScript code.</div>

<div id="mydiv2">My First JavaScript code.</div>

</body>
</html>

Notice that each div element has a different id value. This is required as part of the standard for HTML pages and coding syntax. There are two div tags in the DOM. The JavaScript code gets all div tags and assigns the array to the "tags" variable. The second JavaScript expression assigns the first element in the array the text "My changed JavaScript code." This means that the "mydiv" tag inner HTML tag text is changed to this phrase when the page loads. 

Each element within the body tag is accessible in the DOM, and JavaScript offers several properties and methods that you can use to traverse the page's text, values, and properties. The above example uses the DOM to change the first div tag's text, but you can also use the same type of code to get the value of the tag's text. You'll need to get a tag's value often when you work with user input, especially when working with forms. The following code shows you how to assign a variable with the value of the first div tag's inner HTML. 

<!DOCTYPE html>
<html>

<script>
    var tags = document.getElementsByTagName("div");

    tags[0].innerHTML = "My changed JavaScript code.";

    var firstDiv = tags[0].innerHTML

    tags[1].innerHTML = firstDiv;

</script>

<body>

<div id="mydiv">My First JavaScript code.</div>

<div id="mydiv2">My First JavaScript code.</div>

</body>
</html>

The above HTML and JavaScript builds on the previous section's code. The first two JavaScript expressions perform the same output as the previous section. The next two lines of code are different. The next line of code gets the inner HTML from the first tag element and then assigns the inner HTML text to the second tag in the array. The above code prints "My changed JavaScript code" to both the div tags in the DOM. 

Changing Element Properties 

So far, we've only changed and read a div tag's innerHTML properties, but there are several properties to work with when you use the DOM. Any property that's valid in HTML is also valid when working with JavaScript. Suppose you want to dynamically change the background of an element when the user clicks a button. You can do this with the DOM and JavaScript. We'll build on the previous HTML pages and change the JavaScript code to change the first div's background color. Take a look at the following code. 

<!DOCTYPE html>
<html>

<head>

<script> 

 function ChangeBackgroundColor() {

  var tags = document.getElementsByTagName("div");

 tags[0].backgroundColor = "red";
}
</script>

</head>

<body>

<div id="mydiv">My First JavaScript code.</div>

<button type="button" onclick="ChangeBackgroundColor()">Change It</button>

</body>
</html>

You'll recognize the above code from the previous chapter. The event handler "onclick" is assigned the JavaScript function ChangeBackgroundColor. In this example function, the background color for the first div is changed to red. The backgroundColor attribute is a part of the DOM for div tags. You can also get the current background color using similar syntax. The following code assigns the variable "bgcolor" with the current background color of the div element. 

<!DOCTYPE html>
<html>

<head>

<script> 

 function GetBackgroundColor() {

  var tags = document.getElementsByTagName("div");

 var bgcolor = tags[0].backgroundColor;
}
</script>

</head>

<body>

<div id="mydiv">My First JavaScript code.</div>

<button type="button" onclick="GetBackgroundColor()">Get It</button>

</body>
</html>

Instead of changing the background color, the above example gets the current color from the DOM. Notice the event handler function name was changed to match a more appropriate name for the function, which is GetBackgroundColor. This function is fired when the user clicks the button. 

Working with Cookies

Have you ever seen forms where the web page automatically knows your username or some property that you've entered into the website's stored data? Values stored that persist through leaving the site or closing the browser use cookies. Cookies are small files stored in the browser's cookie directory. These files are generally harmless and help a website identify you and basic information when you open the website. One issue to note is that you never store sensitive information in a cookie. For instance, you wouldn't store a user's password in a cookie. Cookie files are stored in plain text, so anyone who has access to the user's cookies would be able to read this sensitive information. Don't store passwords, credit card information or social security numbers in cookies. 

The cookie property is stored in the document object. You must give the cookie a name and a value. The name is used to call the cookie when the user returns, and the value is what you want to display or process when the user returns. 

Take a look at the following JavaScript code (the HTML is excluded in this example). 

document.cookie = "username=jdoe"; 

The above code assigns a new cookie to the browser. The cookie name is "username" and the value assigned is "jdoe." When the user returns to the page, you can use this cookie to automatically display the user's name. 

When you create a cookie, you should also give it an expiration date. The expiration date tells the browser when it can delete the cookie. For instance, you might want to force a user to enter his username and password in 30 days for security reasons. You could then set a cookie's expiration date to 30 days from the current date. The following code shows you how to set an expiration date for your new username cookie. 

var now = new Date();

now.setDate(now.getDate() + 30);

document.cookie = "username=jdoe; expires=" + now.toString(); 

You'll recognize the Date object from a previous chapter. This code gets the current date, adds 30 days to the date, and then it assigns this value to the cookie's "expires" property.  Now, when the user closes his browser after 30 days, the browser will automatically delete the cookie. Remember that the Date object gets the date on the user's computer because JavaScript is client-side code. If the date on the user's computer is wrong, your code will add 30 days to the user's clock settings and not your local server's time. Working with localized time is done on the server-side code that you can pass to the browser. Incidentally, you can force a cookie to delete immediately after the user closes the browser. If you set the cookie's expiration date to a passed date, the cookie is automatically expired and the browser removes it as soon as the user is done with your web application. 

You've set your cookie, but how do you get the cookie and its value? What if you have multiple cookies? Each cookie is separated by a semicolon. You can use a "for" loop to go through each cookie object and find the one you want to use. The following code gives you an example. 

    var cookies = document.cookie.split(';');

    for(var i=0; i< cookies.length; i++) {

        var c = cookies [i];

        if (c.indexOf("username") != -1)

        document.getElementById("cookiediv").innerHTML = c. substring(("username").length,c.length);

    }

The above code is a bit complex. There is no way to read a cookie by name like most languages. The above code splits the cookie array by semicolon and loops through each value until it finds the cookie name "username." Then, it identifies the cookie's value by getting the substring from the array string. You might need to tweak this code to match your own requirements, but the takeaway is that you need to loop through JavaScript cookies to find the one you want to read. 

The DOM is a part of all JavaScript coding. You'll need to get very familiar with the object model to access data, change data, and dynamically work with user input to create great UIs.