JavaScript examples
Learn JavaScript the easy way—by reviewing these examples:
Creating a JavaScript script block
JavaScript is a client-side and dynamic scripting language. JavaScript allows you to build interactivity into otherwise static HTML pages. To turn your static HTML page into a dynamic page, you can use the JavaScript code in your web page. To insert JavaScript code in your page, use the script tags almost anywhere inside your HTML page:
<script language="JavaScript">
JavaScript code
</script>
Make sure you close your <script> tag, after your JavaScript code, with the closing </script> tag. The <script> tag takes one important attribute: language, which specifies what scripting language you are using. Typically, its values is set to JavaScript.
To create a simple HTML document with a JavaScript script block, write the following code:
<html>
<body>
<script language="javascript">
document.write ("Learn JavaScript by examples.");
</script>
</body>
</html>
The document.write () is a JavaScript method that is used to display text on a webpage. Simply enclose the text that you want to display on a web page with single or double quotation marks. The following shows the output of the above JavaScript code:
Learn JavaScript by examples.
Using the <noscript> tag
As you work with JavaScript, keep in mind that JavaScript is not supported by all browsers (i.e., by old browsers). There is a small percentage of browsers that are not JavaScript-compliant, however. Even if a browser does support JavaScript, a user may turn off running JavaScript. When a browser does not support JavaScript or JavaScript is disabled to run on the browser, your JavaScript code cannot be run. You may want to inform the user what your JavaScript code does so the user can enable JavaScript, if possible.
The <noscript> tag is the solution for providing information to users whenever JavaScript cannot be run on a particular browser. Note the <noscript> tag is ignored by those browsers that support JavaScript; the <script> tag, on the other hand, is ignored by those browsers that don’t support JavaScript.
To use the <noscript>, simply place it after the closing </script> tag, as shown below:
<script language="JavaScript">
JavaScript code
</script>
<noscript>This page is trying to run JavaScript and your browser either does not support JavaScript or you may have turned-off JavaScript. If you have disabled JavaScript on your computer, please turn on JavaScript. Thank you</noscript>
Again, the code inside the <script> tag will be executed by those browsers that support and are enabled to run JavaScript. The code inside the <noscript> tag will be executed by those browsers that do not support JavaScript or when JavaScript is disabled.
Commenting your JavaScript code
When your scripting code becomes large, it become necessary to use comments. With comments, you can add extra information pertaining to your code. Comments are ignored (i.e., are not processed as coding instructions) by the computer. Comments not only help you understand your code when you look after a period of time but also others who are working with you on the same coding project.
JavaScript provides two types of comments:
Single-line comments.
Single-line comments start anywhere in the line and continue to the end of the line. Single-line comments begin with a double forward slash (//), causing the JavaScript interpreter to ignore everything from that point to the end of line. For example,
<script language="javascript">
// Author: Script Buzz
// Description: This JavaScript code prints a simple message.
document.write ("Learn JavaScript by examples."); // prints a message
</script>
Multiline comments.
Multiline comments span multiple lines. Multiline comments start with slash-asterisk (/*) and end with asterisk-slash (*/) pair. For example,
<script language="javascript">
/* Author: Script Buzz
Description: This JavaScript code prints a simple message.*/
document.write ("Learn JavaScript by examples."); // prints a message
</script>
You can add as many or few comments as you like in your JavaScript code. You do not have to comment every line but the idea is to write clear, concise, and meaningful comments to describe your code to help you or others understand what the code does.
Comments also can be used to debug (the act of finding and eliminating problems in your code) your code. By debugging with comments, you comment out lines of code that you think is causing the problem.
Including outside JavaScript code
When your code becomes large, you are likely to find that you are reusing identical JavaScript code on multiple pages of your web site. For example, if you have a dynamic menu common to all or most of your pages of your web site, it will make sense to reuse the JavaScript code that creates the dynamic menu. It is not efficient to maintain identical code in multiple files. The idea is to place your identical JavaScript code in one file (with a file extension .js) and use that file where ever needed. If you ever need to make any changes to your JavaScript code, you will be making changes just to your JavaScript file instead of everywhere else you use the code.
To create a .js file, simply place your JavaScript code in an empty file and save the file with .js file extension. Note when you place your JavaScript code in an external file, you do not use the <script> and </script> tags. You use the <script> and </script> tags when you want to use the external JavaScript file.
By adding the src attribute to the <script> tag, you can specify a relative or absolute URL for a JavaScript file, as in the following:
<script language="javascript" src="JavaScriptFileName.js">
</script>
The following shows an example of code inside an external JavaScript file called ExternalJavaScript.js:
// Author: Script Buzz
// Description: This JavaScript code is placed in a file called ExternalJavaScript.js
document.write ("A JavaScript print statement inside an external JavaScript file."); // prints a message
To link the code shown above in any of your web page, use
<script language="javascript" src="http://www.scriptbuzz.com/javascript/ExternalJavaScript.js">
/* The above line linked a JavaScript file called "ExternalJavaScript.js" via a src attribute of a <script> tag. */
</script>
Note above our src attribute is set to an absolute path (http://www.scriptbuzz.com/javascript/ExternalJavaScript.js) but you can use a relative path for your own scripts. With the above <script> tag, we are saying we want to execute the JavaScript statement(s) inside a file called ExternalJavaScript.js. The following shows the output when statements are executed:
A JavaScript print statement inside an external JavaScript file.
Outputting a variable
So once you’ve declared (or created) a variable, you want to use it in your program. You could, for example, store strings, numbers, etc., in your variables. Then, you could manipulate the values of your variables. At some point, you have to show the values of those variables to the screen. Your variable, for instance, may hold the total amount the customer owes to your website for the items he or she is purchasing.
We won’t create complex examples to show you how to output a value of a variable. To output a value of a variable, simply place the variable name as an argument inside the document.write method, as:
<script language="javascript">
var x
x = 50;
document.write (x); //prints the value of x
</script>
The above JavaScript code creates a variable called x (line 2) and sets it equal to 50 (line 2). On line 3, we use the document.write () method to print the value of the variable x to the screen. The following shows the output:
50
If your variable contains a string (a sequence of text containing letters, numbers and punctuation), printing that is the same as shown above. You just pass the variable name to the document.write () method to print a variable’s value. The following shows an example of printing both a numerical and string values of variables.
<script language="javascript">
var x, message;
x = 50;
message = "x is equal to ";
document.write (message); // prints the value of the message variable
document.write (x); //prints the value of x
</script>
On line 4 (message = “x is equal to “;) above we assign a string value to our variable called message. Anytime you want to assign a string value to variable, simply use double or single quotation marks around it. Line 5, document.write (message);, we print the value of the variable message. Line 6 print the value of the variable x. Following shows the output of the above code:
x is equal to 50
Performing Basic Math in JavaScript
After you declare and assign numerical values to your variables, you can perform mathematical operations on those values using JavaScript’s built-in arithmetic operators. As per discussion for this page, we will cover only four basic JavaScript mathematical operators:
- Addition – adds two values together; example: 30 + 78.
- Subtraction – subtracts one value from another; example: 450 – 21.
- Multiplication – multiplies two values together; example: 120 * 23.
- Division – divides one value by another; example: 40 / 2.
In JavaScript, like other programming languages, you can build complex mathematical expressions using combination of the basic mathematical operators mentioned above. Consider the following as an example:
50 + 40 / 10
The above expression says divide 40 by 10 and add this result to 50. The result would be 54. Remember division and multiplication operators has higher precedence than addition and subtraction operators.
The following JavaScript code shows some examples of mathematical operations:
<script language="javascript">
var x, y, z;
x = 50;
y = 10;
document.write ("x = "); // prints a message
document.write (x); // prints the value of x
document.write (", y = "); // prints a message
document.write (y); // prints value of y
document.write ("<br>x + y is "); // prints a string message
z = x + y; // adds 50 + 10 and assigns the result to the variable z
document.write (z); // prints the value of z, which is 60
document.write ("<br>x - y is "); // prints a string
z = x - y; // substracts x from y and assigns the resulting value to z
document.write (z); // prints the value of z, 40
document.write ("<br>x * y is "); // prints a message
z = x * y; // multiplies x * y and assigns result to z
document.write (z); // prints z, 500
document.write ("<br>x / y is "); // prints a message
z = x / y; // dividies x by y assigns result to z
document.write (z); // prints the value of z, 5
</script>
In this JavaScript code above, we declare and use three numerical variables. The example has many print statements. The first a few print statements print the values of x and y. Then, we print the value of z, after each mathematical operation. The following shows the output of the above code: x = 50, y = 10
x + y is 60
x – y is 40
x * y is 500
x / y is 5
Concatenating strings with the + operator
The most common operations performed with strings is concatenation. Concatenation is a process of combining two strings into one longer string. For example, we could combine the strings “Script” and “Buzz” into a new string as “Script Buzz.”
So what JavaScript operator do you use to concatenate a string? Well, you will use the “+” operator. Note this symbol is also used as a mathematical addition operator in JavaScript. So if you are using the “+” with numerical values it will add the two values; if you use the same operator with two strings, it will concatenate (combine into one) two strings.
The following shows a simple example:
<script language="javascript">
var string1, string2, stringConcatenated;
string1 = "Concatenating "; // first string
string2 = "strings"; // second string
stringConcatenated = string1 + string2; // Concatenating strings
document.write (stringConcatenated); // printing the Concatenated string
</script>
In the above example, we use three string variables. Remember a string is surrounded by either single or double quotation marks. On line 5, stringConcatenated = string1 + string2;, we use the “+” operator to concatenate two strings. Before the concatenation, we had two strings: “Concatenating ” and “strings.” After the concatenation, we end up with a combined longer string: “Concatenating strings.” The following verifies our output of the JavaScript code:
Concatenating strings
The following shows a more complex example of the concatenate operator:
<script language="javascript">
var strOut;
strOut = "<table width='300' border='1' cellspacing='0' cellpadding='3'>";
strOut = strOut + "<tr>";
strOut = strOut + "<th colspan='2'>The + operator in JavaScript</th>";
strOut = strOut + "</tr>";
strOut = strOut + "<tr>";
strOut = strOut + "<th>When used in</th>";
strOut = strOut + "<th>Performs</th>";
strOut = strOut + "</tr>";
strOut = strOut + "<tr>";
strOut = strOut + "<td>Mathematical expression</td>";
strOut = strOut + "<td>Addition</td>";
strOut = strOut + "</tr>";
strOut = strOut + "<tr>";
strOut = strOut + "<td>String expression</td>";
strOut = strOut + "<td>Concatenation</td>";
strOut = strOut + "</tr>";
strOut = strOut + "</table>";
document.write (strOut);
</script>
In this example, we use just one variable named strOut. One line 3, we assign a complex string to this variable. Notice we are using single quotes for attribute values of a table tag. Then, on line 4 we concatenate the string “<tr>” with the string “<table width=’300′ border=’1′ cellspacing=’0′ cellpadding=’3’>” and results in:
<table width=’300′ border=’1′ cellspacing=’0′ cellpadding=’3′>
<tr>
Similarly, we concatenate more strings, one at a time, to this string, and end up creating a table that looks like:
The + operator in JavaScript | |
---|---|
When used in | Performs |
Mathematical expression | Addition |
String expression | Concatenation |
Searching for text in strings with the search () method
When working with strings, sometimes there comes a need to determine if string contains some specific substring. In JavaScript, we can use the search () method to find substrings in a string. Suppose we have a string “JavaScript.” And, let’s say in that string we want to search for the string “Script.” To perform this search, we will use the search () method. The search () method returns a number greater than or equal to 0 corresponding to the first occurrence of the substring if the substring (“Script”) is found. If a substring is not found, the search () method returns -1.
The following shows the JavaScript code to perform the search using the search () method:
<script language="javascript">
var str, result;
str = "JavaScript";
result = str.search("Script");
document.write ("Substring found at position: " + result);
</script>
We perform the search on line 4. On line 4 we are searching for “Script” because this string is passed as an argument to the search () method. We search for that string in “JavaScript.” Line 5 displays the result. We would expect a number 0 or greater because the string “Script” occurs first in “JavaScript.” Because JavaScript starts counting at position 0 for an array, our string “Script” starts at position 4. See the following table to understand the corresponding position of each chracter in the string:
String | J | a | v | a | S | c | r | i | p | t |
Position | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
The following shows the output from the JavaScript code:
Substring found at position: 4
Replacing text with the replace () method
If you want to make changes to an existing string value, you could use the replace () method. By using this method, you can change some specific part of a whole string. For instance, you could replace the word “JavaScript” with “Buzz” “Script JavaScript.” Following shows the JavaScript code to replace that string:
<script language="javascript">
var str1, str2;
str1 = "Script JavaScript";
document.write ("Original string: " + str1 + "<br>");
str2 = str1.replace ("JavaScript", "Buzz");
document.write ("String after replacement: " + str2);
</script>
In the above code, we start by declaring two variables: str1 and str2. The str1 variable holds our “Script JavaScript” string (see line 3) and the str2 variable is assigned the replaced string (see line 5). Notice on line 5 we are passing two arguments to the replace () method. The first argument in parentheses contains the string we are searching for. The second argument contains the string that will replace the string that we are searching for, if found. Because the string “JavaScript” is in the “Script JavaScript” string, “JavaScript” is replaced with “Buzz”, resulting in as output of the code shows:
Original string: Script JavaScript
String after replacement: Script Buzz
If you have been following the other JavaScript examples on this site, you may notice that it is the first time here we are using the “+” operator to combine HTML code with the variables or other strings we want to print (see lines 4 and 6). We could have rewritten those lines as follows but our code becomes little longer:
document.write ("Original string: ");
document.write (str1);
document.write ("<br>");
document.write ("String after replacement: ");
document.write (str2);
Now, let’s make another point: the replace () method won’t make any changes if the substring that you want to replace in a string is not found. Consider the following example:
<script language="javascript">
var str1, str2;
str1 = "Script JavaScript";
document.write ("Original string: " + str1 + "<br>");
str2 = str1.replace ("HTML", "Buzz");
document.write ("String after replacement: " + str2);
</script>
For simplicity, we are using almost the same code that we used before except now we are trying to replace the string “HTML” in “Script JavaScript.” with “Buzz”; Because “HTML” is not in “Script JavaScript”, no change is made to “Script JavaScript” and the following shows the output of the code to support that conclusion:
Original string: Script JavaScript
String after replacement: Script JavaScript
Formatting text in JavaScript
JavaScript provides number of predefined functions (methods) to format some text. The methods we are about to discuss are:
- bold () – makes text bold using the HTML <b> tag.
- italics () – italicizes text using the HTML <i> tag.
- fontcolor () – changes the color of the text to the specified color as an argument. The fontcolor () method uses the HTML <font> tag with the color attribute.
- fontsize () – changes the size of the text to the specified size as an argument. The fontcolor () method uses the HTML <font> tag with the size attribute.
- toLowerCase () – changes text to all lowercase letters.
- toUpperCase () – changes text to all upper case letters.
From other examples presented on this site about JavaScript, you should know how to call (use) a JavaScript method. We simply call the method with object it belongs to. The methods shown above are part of a string object. The following shows the JavaScript code how to use the above mentioned text formatting methods ():
<script language="javascript">
var str = "Learn JavaScript with easy examples!";
document.write ("Original text: " + str);
document.write ("<br>Changed to bold: " + str.bold());
document.write ("<br>Changed to italics: " + str.italics());
document.write ("<br>Changed color: " + str.fontcolor("DarkGreen")); // could also use the Hexadecimal value: #006400
document.write ("<br>Changed size: " + str.fontsize("2")); // possible values 1 through 7
document.write ("<br>In lowercase: " + str.toLowerCase());
document.write ("<br>In upper case: " + str.toUpperCase());
</script>
Let’s discuss what the above JavaScript code does. We start with string variable. Line 3 displays the value of the variable. Line 4 prints our string as bold because of the bold () method being used with string object. Similarly, we call the other methods and pass arguments, when appropriate, inside the parentheses. The following shows the output of the above JavaScript code:
Just like in HTML we can use more than one tag to format a text, we can multiple methods on the same string object. For instance, in HTML if you wanted to display some text as bold, dark green and in bigger font size, you could use the <b> tag, <font> tag to adjust the color and size; respectively. See the following HTML code:
<font size="6" color="#006400">
<b>Formatting some text.</b>
</font>
for
Formatting some text.To produce the above shown output, notice our HTML code does not say:
<font size="6">
<font color="#006400">
<b>Formatting some text.</b>
</font>
</font>
This code uses two font tags instead of one yet the output of our code is unaffected. You may notice that this is long and is less efficient way of coding. By the same token, we want to avoid that in JavaScript. See the same example in JavaScript:
<script language="javascript">
var str = "Formatting some text.";
str = str.fontsize("6"); // sets size of the text to 6
str = str.fontcolor("#006400"); // sets color of the text to #006400
str = str.bold(); // makes text bold
document.write (str);
</script>
We create our string variable on line 2. Line 3 uses the fontsize () method to set the font size of this string to 6. Line 4 sets the color and line 5 makes the text bold. Finally, line 6 prints out result. Notice each time we make a change to the str variable, we assign the value to itself using the assignment operator.
The following JavaScript code is more concise and efficient to accomplish the same:
<script language="javascript">
var str = "Formatting some text.";
str = str.fontsize("6").fontcolor("#006400").bold();
document.write (str);
</script>
Notice on line 3 we are using three methods with the string object called str. We separate each method with a dot (specifically with dot operator). Notice the formatted string result is the same whether you use one method at a time or multiple methods in one step:
Creating arrays in JavaScript
In addition to simple data types, JavaScript supports a more complicated data type knows as an array. An array is an ordered collection of values that is grouped together by a single variable name. The syntax for creating an array is:
var arrayName = new Array (size);
The arrayName is the name of the array variable and the size is the number of elements or distinct values in the array. Note specifying size is optional when creating the array. If you don’t specify a size, JavaScript will automatically increase the size of an array as you add more elements to the array.
If you have not worked with arrays in any programming language before, the following display may help you to understand the concept of array:
index | 0 | 1 | 2 | 3 |
---|---|---|---|---|
value | JavaScript | HTML | ASP | Scripting tools |
The above visualization shows an array of size 4. Note the array index starts at 0 so the first element of an array is stored at index 0, the second is stored at index 1, etc. An index refers to an integer that identifies the location of an element. For instance, the index value is 4 for the element “Scripting tools.”
So you might be thinking when should I use an array or a variable? With a variable, you can store only one value at a time. If you had to store, let’s say, 40 different values to a related item, you could declare 40 variables. But managing that many variables would be insufficient. So use an array instead of size 40. As a concrete example, assume you wanted to store in your JavaScript code the names of the months in a year. To do this you could declare an array of size 12 as:
var monthArr = new Array (12);
instead of declaring 12 different variables for the names of each month as:
var jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec;
In some problems, it becomes obvious to use an array instead of a variable. For instance, assume you have 40 students in your class and you want to compute the average grade on the mid-term for these students. To do that, you do not want to create 40 variables, like var st1MidTermScore, st2MidTermScore, etc… Instead, you should create an array like:
var stMidTermScoreArr = new Array (40);
Populating an array
After you create an array, we can start storing values in to the array. To populate an array with values, you need to use the name of the array, the index (indicated inside square brackets []) where you want to store a value, and the value you want to store. For instance,
var URLsArray = new Array (4);
URLsArray [0] = "http://www.scriptbuzz.com";
URLsArray [1] = "http://www.script-buzz.com";
URLsArray [2] = "http://www.scriptbuzz.org";
URLsArray [3] = "http://www.buzzscrip.com";
On line 1, we declare an array called URLsArray and of size 4. Then, on lines 2 through 5, we populate the array with different website addresses. Beside using the index value inside the square brackets, the array is initialized similar to a variable.
In JavaScript, you can also initialize an array at the time you create the array by specifying the values as arguments to the Array () method. Note each value must be separated by a comma. For instance,
var URLsArray = new Array ("http://www.scriptbuzz.com", "http://www.script-buzz.com", "http://www.scriptbuzz.org", "http://www.buzzscript.com");
we declare an array called URLsArray and populate it the same values we used for the last example. If you populate your array this way, the size of the array is determined by the values you supply to the Array () remember though each value must be separated by a comma. The size of the array As a visualization, see the following table how to understand how data inside an array is stored:
index | value |
---|---|
0 | “http://www.scriptbuzz.com” |
1 | “http://www.script-buzz.com” |
2 | “http://www.scriptbuzz.org” |
3 | “http://www.buzzscript.com” |
In the following example, we use a for loop to populate our array:
<script language="javascript">
var numArr = new Array (10);
var i;
for (i = 0; i < 10; i++)
{
numArr[i] = i * i;
}
i = 0;
while (i < 10)
{
document.write ("numArr[" + i + "] = " + numArr[i] + "<br>");;
i++;
}
</script>
In this example, we create an array called numArr of size 10. We populate this array with numerical values using a for loop, see lines 4 through 8. The first time the for loop executes, numArr[0] is assigned 0 because i is 0 so 0 * 0 = 0. When the second time the loop executes, i becomes 1 and numArr[1] is assigned 1 because 1 * 1 = 1. The third time the loop executes, numArr[2] is assigned 4 and see below for other values populated to the array.
The i = 0; reinitializes i to 0 because after the for loop stops i was 10. We use variable i again in the while loop to print the values of the array. Again, to access the array we use the name of the array and an index value; for instance, to access the fourth element of numArr array, we would write numArr[3]. Remember array starts at index 0, so the first element is at index 0; second element at idnex 1, third element at index 2, etc. The following shows the output of our code:
numArr[0] = 0
numArr[1] = 1
numArr[2] = 4
numArr[3] = 9
numArr[4] = 16
numArr[5] = 25
numArr[6] = 36
numArr[7] = 49
numArr[8] = 64
numArr[9] = 81
Sorting an array
When working with arrays, sometimes you may want to sort the array. To sort an array, you can use JavaScript’s sort () method. Suppose we want to sort the following list in alphabetical order:
- Maryland
- Arizona
- California
- New York
- Virginia
- Texas
To sort this list, we will create an array using the following JavaScript code:
var statesArr = new Array(6);
statesArr [0] = "Maryland";
statesArr [1] = "Arizona";
statesArr [2] = "California";
statesArr [3] = "New York";
statesArr [4] = "Virginia";
statesArr [5] = "Texas";
The above code creates an array called statesArr with 6 elements. To sort this array, use the sort () method as:
statesArr.sort();
With that statement, our array is sorted. The followings shows the complete JavaScript code and how to print the sorted array using a for loop:
<script language="javascript">
var statesArr = new Array(6);
statesArr [0] = "Maryland";
statesArr [1] = "Arizona";
statesArr [2] = "California";
statesArr [3] = "New York";
statesArr [4] = "Virginia";
statesArr [5] = "Texas";
statesArr.sort();
for (i = 0; i <= 5; i++)
{
document.write (statesArr[i] + "<br>");
}
</script>
The following shows the output of the sorted array:
Arizona
California
Maryland
New York
Texas
Virginia
Outputting dynamic HTML
<p>This is some <b>HTML</b> content placed inside the <i><p> tag</i>.</p>
To print the above HTML code with JavaScript, we could use the document.write () method as:
document.write ("<p>This is some <b>HTML</b> content placed inside the <i><p> tag</i>.</p>");
The following shows the output if you place the above document.write () statement inside a JavaScript script block:
This is some HTML content placed inside the <p> tag.
So if you have not noticed already, you can place HTML tags directly inside document.write () method. The following shows a more complex example:
<script language="javascript">
document.write("<p>Creating an unordered list with JavaScript:</p>");
document.write("<ul id='indent20px'>");
document.write("<li>HTML</li>");
document.write("<li>ASP</li>");
document.write("<li>CSS</li>");
document.write("<li>Dreamweaver</li>");
document.write("<li>JavaScript</li>");
document.write("<li>Scripting tools</li>");
document.write("<li>XHTML</li>");
document.write("<li>XML</li>");
document.write("</ul>");
</script>
So in this example, we create an unordered list. Notice each of document.write () method takes only one string argument. The following shows the list
Creating a unordered list with JavaScript:
- HTML
- ASP
- CSS
- Dreamweaver
- JavaScript
- Scripting tools
- XHTML
- XML
If you wanted, you could combine your strings with the concatenation + operator as shown below to improve the above example:
<script language="javascript">
var dynamicHTML;
dynamicHTML = "<p>Creating an unordered list with JavaScript:</p>";
dynamicHTML += "<ul>";
dynamicHTML += "<li>HTML</li>"
dynamicHTML += "<li>ASP</li>"
dynamicHTML += "<li>CSS</li>"
dynamicHTML += "<li>Dreamweaver</li>"
dynamicHTML += "<li>JavaScript</li>"
dynamicHTML += "<li>Scripting tools</li>"
dynamicHTML += "<li>XHTML</li>"
dynamicHTML += "<li>XML</li>"
dynamicHTML += "</ul>"
document.write(dynamicHTML);
</script>
In this example, we use the concatenation + operator to combine our strings. For instance, line 4, dynamicHTML += “<ul>”;, adds “<ul>” to “<p>Creating an unordered list with JavaScript:</p>” (from line 3) to result in
"<p>Creating an unordered list with JavaScript:</p> <ul>"
Also, you can also use both HTML and JavaScript to produce some output, for instance:
<p>Creating an unordered list with JavaScript:</p>
<ul>
<script language="javascript">
var dynamicHTML;
dynamicHTML += "<li>HTML</li>"
dynamicHTML += "<li>ASP</li>"
dynamicHTML += "<li>CSS</li>"
dynamicHTML += "<li>Dreamweaver</li>"
dynamicHTML += "<li>JavaScript</li>"
dynamicHTML += "<li>Scripting tools</li>"
dynamicHTML += "<li>XHTML</li>"
dynamicHTML += "<li>XML</li>"
document.write(dynamicHTML);
</script>
</ul>
In this example, our paragraph is created with HTML. The <ul> tag is opened and closed with HTML as well. However, each item of our list is created with JavaScript. Note our output remains the same despite the fact that we used static (HTML) and dynamic (JavaScript) content.
Outputting date
Sometimes you may decide to display current date on your web page. You could do that, for instance, when you display a form to the user and have your JavaScript automatically fill the date field. To display date in JavaScript, you can use the Date object. A Date object contains date information. For instance, the following JavaScript code
<script language="javascript">
var currDate = new Date ();
currDate = currDate.toString();
document.write (currDate);
</script>
prints current date and time information:
Mon Sep 27 2021 12:42:53 GMT+0000 (Coordinated Universal Time)
But what if you want to display only current month, day, year, or date in some custom format? Well, the date object supports number of methods to obtain specific information about time and date, as summarized in table 1.
Table 1 Date methods | |
---|---|
Method | Description |
getSeconds() | Returns the seconds |
getMinutes() | Returns the minutes |
getHours() | Returns the hour in military time |
getDate() | Returns the day of the month |
getDay() | Returns the day of the week; where 0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday |
getMonth() | Returns the number of the month, where 0 = January, 1 = February, 2 = March, 3 = April, 4 = May, 5 = June, 6 = July, 7 = August, 8 = September, 9 = October, 10 = November, 11 = December |
getFullYear() | Returns the year number |
getTime() | Returns the time value, expressed as the number of milliseconds since January 1, 1970. |
Note in table 1 above JavaScript starts counting days and months at 0. When the getDay () method returns 0, it indicates the day is 0. When the getMonth () method return 11, it indicates that the month is December. The following shows Date methods in use:
<script language="javascript">
var dateObj = new Date();
document.write ("Current Date: " + dateObj.toString());
document.write ("<br>getSeconds() : " + dateObj.getSeconds());
document.write ("<br>getMinutes() : " + dateObj.getMinutes());
document.write ("<br>getHours() : " + dateObj.getHours());
document.write ("<br>getDate() : " + dateObj.getDate());
document.write ("<br>getDay() : " + dateObj.getDay());
document.write ("<br>getMonth() : " + dateObj.getMonth());
document.write ("<br>getFullYear() : " + dateObj.getFullYear());
document.write ("<br>getTime() : " + dateObj.getTime());
</script>
The above JavaScript code produces:
Current Date: Mon Sep 27 2021 12:42:53 GMT+0000 (Coordinated Universal Time)
getSeconds() : 53
getMinutes() : 42
getHours() : 12
getDate() : 27
getDay() : 1
getMonth() : 8
getFullYear() : 2021
getTime() : 1632726773884
So if you wanted to control the format of the date, you can use the above mentioned date methods. Let’s say we want to display date in a custom form such as: January, 5 2005. To print date in such format, we will use:
- getMonth () method to obtain the current month number. We will use an array that contains all the months that corresponds to one of the values returned by the getMonth () method.
- getDate () to get the current date.
- getFullYear () to get the current year.
The following JavaScript code shows how to display a date in the above mentioned custom format:
<script language="javascript">
var currMonth, currDate, currYear;
var dateObj = new Date();
var monthsArr = new Array();
currMonth = dateObj.getMonth();
currDate = dateObj.getDate();
currYear = dateObj.getFullYear();
monthsArr[0] = "January";
monthsArr[1] = "February";
monthsArr[2] = "March";
monthsArr[3] = "April";
monthsArr[4] = "May";
monthsArr[5] = "June";
monthsArr[6] = "July";
monthsArr[7] = "August";
monthsArr[8] = "September";
monthsArr[9] = "October";
monthsArr[10] = "November";
monthsArr[11] = "December";
document.write (monthsArr[currMonth] + ", " + currDate + " " + currYear);
</script>
In the above JavaScript code, we use an array to store the names of the months. In our document.write () statement, we use the value returned by getMonth () to print the name of the month. The currDate variable prints the current date and the variable currYear prints the value of current year. The following shows the output of the above code:
September, 27 2021