by Lars Vogel

Follow me on twitter

Lars Vogel on Google+

Javascript - Tutorial

Lars Vogel

Version 1.1

27.04.2011

Revision History
Revision 0.1 31.05.2009 Lars
Vogel
created
Revision 0.2 - 1.1 13.06.2009 - 27.04.2011 Lars
Vogel
bug fixes and enhancements

Learning JavaScript

The article contains a introduction to JavaScript and JSON.


Table of Contents

1. JavaScript Overview
1.1. What is JavaScript?
1.2. Your first JavaScript (embedded))
1.3. Your first JavaScript (external))
2. Debugging
3. Programming in JavaScript
3.1. Variables
3.2. Arrays
3.3. Functions
3.4. Prototype in JavaScripts
3.5. Assigning functions to HTML buttons
3.6. HTML Events
4. JavaScript and HTML interaction
4.1. HTML DOM
4.2. Manipulation HTML with JavaScript
5. JSON
6. Examples
6.1. Create a dynamic link using the webpage information
6.2. Reading META Tags via JavaScript
6.3. HTML forms and JavaScript
7. Thank you
8. Questions and Discussion
9. Links and Literature

1. JavaScript Overview

1.1. What is JavaScript?

JavaScript is a scripting language which is primary used within HTML webpages. JavaScript is executed directly in the browser and all main browsers contain a compiler or interpreter for JavaScript. JavaScript is case sensitive. JavaScript and Java are completely different programming languages even though they have a similar name.

You can put JavaScript into an external file or directly into the HTML page. If you put the JavaScript code into the HTML page you can either put it into the header or in the body of the HTML page. JavaScript which is embedded into an HTML page must be surrounded by <script type="text/javascript"> </script> tags. The type is mandatory, even if the browser only supports JavaScript.

JavaScripts in the body will be executed while the page loads. JavaScripts in the header will be executed when other JavaScript functions in the body call them.

1.2. Your first JavaScript (embedded))

Create the following HTML page (via a standard text editor) and open it with a browser. In this example we will embedded the JavaScript into the HTML page.

				
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
<!--This is single line comment --> 
/*
This is a multi line commend
The following command write output the text into the HTML code. -->
*/
document.writeln("Hello, JavaScript!");
</script>
</body>
</html>
			

Open the HTML page in a browser. The commands within the script tags will run and "Hello, JavaScript!" will be written to the webpage.

1.3. Your first JavaScript (external))

You can also put the JavaScript in a separate file and include it into the HTML page. For example create the file "helloworld2.html" with the following content.

				
<!DOCTYPE html>
<html>
<body>
<script src="myfirstjsfile.js"></script>
</body>
</html>
			

Create the file "myfirstjsfile.js" in the same directory as the HTML page. As the JavaScript is in a separate file you don't have to to use the <script> </script> tag. Simple write the code directly into the file.

				
document.writeln("<b>Bold Hello World via an external js file!</b>");
			

Open the HTML page in a browser. The script should get executed and you should see the message.

2. Debugging

The easiest way to "debug" JavaScript is to use the alert() method which allows to give the user some feedback. This is the equivalent to "println" in other programming languages. For example the following program give a popup with the currently value to the user.

			
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

<body>
<script type="text/javascript">
/*Declare a text variable and print it to the HTML page*/
var mytext= "Example Text.";
/*Call the function*/
alert(mytext);

</script>
</body>
</html>
	
	
		

3. Programming in JavaScript

3.1. Variables

The following demonstrates how to declare and use variables in JavaScript.

				
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
/*Declare a text variable and print it to the HTML page*/
var mytext= "Hello, hello. Turn the radio on. Is there anybody out there...";
document.writeln(mytext);


/* Declare Variables for doing some math*/
a=5;
var b=1;
document.writeln(a-b);

/* Concatenate two strings*/
var mytext1 ="I like spanish";
var mytext2 =" because the melodie is nice.";
document.writeln(mytext1+mytext2);
</script>
</body>
</html>

			

You may notice that there are two ways of declaring variables.

				
a=5;
var b=1;
			

Variables defined without the keyword "var" are global variables. Variables defined with "var" are scoped according to their declaration, e.g. if you define a "var" in a function this variable is only valid in this function.

It is good JavaScript practice to always use the "var" keyword.

JavaScript has four basic types, Object and the primitive types Number, String, and Boolean.

3.2. Arrays

Arrays are Objects in JavaScript. You can define them and use the method pop() to remove the first element and push(newValue) to add a new element at the end. You can also iterate over it.

				
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">

var myArray = ["Android", true, 7]
alert(myArray[0]);
alert(myArray.length);
myArray.pop();
alert(myArray);
myArray.push("Eclipse")
alert(myArray);

/*Iterate over the array and write it to the console of the browser*/

for(var i = 0; i < myArray.length; i++) { alert(myArray[i]) }

</script>
</body>
</html>

			

3.3. Functions

A function in JavaScript encapsulates reusable code and are represented as Objects. Functions can be directly called via other JavaScript code. It is recommended that you put functions in the header of the HTML page.

Functions are declared via the function keyword. You can call a function directly, or use the apply method on the function.

				
<!DOCTYPE html>
<html>
<header>
<script type="text/javascript">
/*Write the text twice to the document*/
function writetext(text)
{
document.writeln(text);
document.writeln(text+ "<p>");
}
</script>

</header>
<body>
<script type="text/javascript">
/*Declare a text variable and print it to the HTML page*/
var mytext= "Example Text.";
/*Call the function*/
writetext(mytext)
/*Call it via apply*/
writetext(mytext + "apply").apply();
</script>
</body>
</html>

			

3.4. Prototype in JavaScripts

JavaScript does not support classes and inheritance of classes like object orientated programming languages. JavaScript is a prototype-based language, by this approach you can re-use functions by cloning existing objects.

3.5. Assigning functions to HTML buttons

The following gives an example how to assign a function to an HTML button.

				
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> 
<script type="text/javascript">
function writetext(mytext)
{
document.writeln(mytext);
}
function addNumber(a,b){
	var result = a+b;
	return result;
}
</script>

</head>
<body>

<input type="button" value="Write Text after click"
onclick="writetext('Hello function')" >

<input type="button" value="Add number"
onclick="writetext(addNumber(1,3))" >
</body>
</html>
			

3.6. HTML Events

JavaScript can react to certain event on the page and / or on certain webpage elements, e.g. buttons. You can register a function to a event in the HTML page.

Table 1. Events in Javascript

Event Description
Onload Triggered then the user loads the page. The onload even can for example be used to check the visitors browser type.
onChange Called whenever a field is changed. Can for example be used to validate an input field of a form.
onSubmit Called then a user clicks on the submit button of a form.
OnMouseOver and OnMouseOut Called then the mouse enters a certain element on the page or leaves it.


4. JavaScript and HTML interaction

4.1. HTML DOM

A HTML webpage is represented via a HTML Document Object Model (DOM). The HTML DOM is defined via a W3C standard This HTML DOM defines a standard way to access and manipulate HTML documents. You can use JavaScript to modify the HTML DOM.

4.2. Manipulation HTML with JavaScript

You can for exmaple search via JavaScript for certain elements and modify their properties. The following example shows how to find HTML elements with a certain div class and set the display property to hide / show them.

				
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> 
<script type="text/javascript">

function hideshow() {
	
	var allHTMLTags = new Array();

	//Create Array of All HTML Tags
	var allHTMLTags=document.getElementsByTagName("*");

	//Loop through all tags using a for loop
	for (i=0; i<allHTMLTags.length; i++) {

	//Get all tags with the specified class name.
		if (allHTMLTags[i].className=="revhistory") {
		
	// Hide or display the elements
			if (allHTMLTags[i].style.display == "none") {
				allHTMLTags[i].style.display = "";
			} else {
				allHTMLTags[i].style.display = "none";
			}
		}
	}
}
</script>

</head>
<body>

<div class="revhistory"> This is the text which will be manipulated via JavaScript</div>

<input type="button" value="Show/ Hide"
onclick="hideshow()">


</body>
</html>
	
	
			

5. JSON

JSON (JavaScript Object Notation) is a independent data exchange format. JSON is a subset of the ECME-Script Specification (JavaScript) and can therefore directly used in JavaScript.

In JSON a data structure is a key / value pair. The key is a string, the value can be a numerical value, a bollean value (true or false) or an object. Lists are one or more values surrounded by [] and separated by ",". An object is a set of key / name pairs which starts with "{" and ends with "}".

The following is an example of an JSON object and its usage in JavaScript. You evaluate the JSON via the function eval and can then assign it to an object. This object can then be used in your JavaScript source code.

			
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<script type="text/javascript">
<!--Evaluate the object and assign to variables --> 
var user = eval(
{
 firstName:'Lars',
 lastName:'Vogel',
 address: {
 	street:'Examplestr.',
 	number: '31'
 }
}
);
<!--Use the object--> 
alert(user.firstName + ' lives in street ' + user.address.street); 
document.writeln(user.firstName + ' ' +user.lastName);
</script>
</body>
</html>
		

6. Examples

6.1. Create a dynamic link using the webpage information

The following shows how an URL for an link can be dynamically created via JavaScript. This examples uses JavaScript to create a link for the website "digg".

				
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

/* This script will read the current URL and the title of the document
and submit this webpage to the social bookmarking website. */

<script type="text/javascript">
function toDiggUrl(){
	var result = "http://digg.com/submit?phase=2&url=";
	result += encodeURIComponent(location.href);
	result += "&title=";
	result += encodeURIComponent(document.title);
	result += "&topic=programming";
	window.location = result;
}
</script>
</head>

<body>

<b>Here we write some information to the HTML page.</b>
<BR>
Write the current URL to this HTML document
<script type="text/javascript">
document.writeln(location.href);
</script>

<BR>
<BR>
<b>Encodes the current URL so that special characters will get
encoded</b>
<BR>
<script type="text/javascript">
document.writeln(encodeURIComponent(location.href))
</script>


<BR>
<BR>
<b>More fancy stuff, evalute page information and send this to a
social bookmarking website (digg)</b>
<BR>


<table border="0" cellpadding="10" cellspacing="0" width="100%">
	<tr>
		<td width="320">If you press the hyperlink below the JavaScript
		will run <BR>
		<a href="javascript: toDiggUrl()">Digg this site</a></td>
	</tr>
</table>



</body>
</html>
			

6.2. Reading META Tags via JavaScript

You can use JavaScript to read existing meta tags from the webpage. The following reads the content of the meta tag description from the webpage.

				
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

<head>
<meta name="description" content="Tutorials from www.vogella.de!"> 

<script type="text/javascript">
function getMetaDescription () {
  var metaElements = document.all ?
    document.all.tags('META') :
    document.getElementsByTagName ?
    document.getElementsByTagName ('META') : new Array();
  var metaKeywords = new Array();
  var i = 0;
  for (var m = 0; m < metaElements.length; m++)
    if (metaElements[m].name == 'description')
      metaKeywords[i++] = metaElements[m].content;
  return metaKeywords;
}
</script>
</head>

<h2>
This will write the meta tag description to this page
</h2>

<body>

<script type="text/javascript">
	document.write(getMetaDescription());
</script>


</body>
</html>
			

6.3. HTML forms and JavaScript

The following is an example on checking input data of HTML forms and setting hidden parameters via Javascript, in this case the URL is automatically determined and send to the service once submit is pressed.

				
function updateFormAction(){
	
	document.forms["myform"].elements["webpage"].value = encodeURIComponent(location.href);
	var value = document.forms["myform"].elements["user"].value;
	if (value==null||value=="")
  	{
  	 	var Textknoten = document.createTextNode("Please fill out all fields");
  	 	document.getElementById("replace").replaceChild(Textknoten, document.getElementById("replace").firstChild);
  	
  	    return false;
  		}
	var value = document.forms["myform"].elements["email"].value;
	if (value==null||value=="")
  	{
  		return false;
  		}
  	var value = document.forms["myform"].elements["summery"].value;
	if (value==null||value=="")
  	{
  		return false;
  		}
  		
  	var value = document.forms["myform"].elements["comment"].value;
	if (value==null||value=="")
  	{
  		return false;
  		}
	return true; 
	
}	

			

				
<html> 
<head> </head>
<body>
<!-- Favorites -->
<table border="0" cellpadding="10" cellspacing="0" width="100%">
	<tr>
		<td>

		<div dojoType="dijit.TitlePane" title="Feedback Form">
		So how did you like this webpage?  <BR>
		<FORM id=myform " NAME="myform" ACTION="http://www.vogella.de/FeedbackForm/FeedbackSave" method="get"
			onclick="return updateFormAction()"><input TYPE="hidden"
			NAME="webpage" VALUE="test">

		<table>
			<tr>
				<td></td>
			</tr>
			<tr>
				<td align="right">User: (*)</td>
				<td><input name="user" type="text" size="30" maxlength="30"></td>
			</tr>
			<tr>
				<td align="right">Email:(*)</td>
				<td><input name="email" type="text" size="30" maxlength="30">
				(will not be visible)</td>
			</tr>
			<tr>
				<td align="right" valign="top">Summery:(*)</td>
				<td><input name="summery" type="text" size="30" maxlength="30"></td>
			</tr>
			<tr>
				<td align="right" valign="top">Comment:(*)</td>
				<td><textarea name="comment" rows="6" cols="40"></textarea></td>
			</tr>
			<tr>
				<td></td>
				<td><input type="submit" value="Submit"></td>
			</tr>
			<tr> <td colspan="2"> <div id="replacefeedback"> (*) are required </div></div> </td></tr>
		</table>
		</FORM>
		</div>
		</td>
	</tr>
</table>
</body>
</html>
			

7. Thank you

Please help me to support this article:

Flattr this

8. Questions and Discussion

Before posting questions, please see the vogella FAQ. If you have questions or find an error in this article please use the www.vogella.de Google Group. I have created a short list how to create good questions which might also help you.

9. Links and Literature

Not yet listed