Javascript Programming

Javascript supports many of the same programming constructs that are common in other programming languages such as Python.  What follows is a brief introduction to some of its features.

Variables are declared using the var keyword, and values are assigned to variables using the equal sign (=). Declaration and assignment are often combined into one statement as:

var pi = 3.14;

var name = “John Doe”;

var flag = true;

var weekDays = new Array(“Mon”,”Tue”,”Wed”,”Thu”,”Fri”);

As shown above, Javascript variables can be of various types including numbers, strings, Booleans, and arrays.  A declared but unassigned variable has value “undefined” and a variable can be assigned the value “null” to give it no value.

Conditionals are supported through if…else statements, such as shown here:

if (x==3)   {
alert(“This shows up if x equals 3.”);
}
else   {
alert(“This shows up if x is not equal to 3.”);

}

Conditional expressions are enclosed in parentheses.  Comparison operators for conditional statements include:

  • ==             equal to
  • !=              not equal to
  • ===           identical to (equal to and of the same data type)
  • !==           not identical to
  • >                greater than
  • >=             greater than or equal to
  • <                less than
  • <=             less than or equal to

Loops can be used in Javascript.  Several types of loops are supported including: for and while loops.  Here are a couple of examples.

for (var i=0; i&lt;3; i++)   {

alert(“This is alert number “ + i);  //This loop triggers three alerts - numbers 0, 1, and 2

}

var colors=[“red”,”orange”,”yellow”,”green”,”blue”,”indigo”,”violet”);

var i=0;

while (colors[i])   {

document.write(colors[i] + “&lt;br&gt;”);    //This loop displays all values of the colors array

i++;

}

Functions are blocks of code that are only executed when called (referenced) by other code.  You have already seen an example of a Javascript function in the example on page 2, and alert, which was used in several examples above, is a built-in function that displays an alert message.

Here is an example of a function that would accept two values as arguments and return the resulting sum.

function sumNumbers(a,b)   {

return a + b;

}

This function might be called from the body with a block of code such as:

<script>

document.getElementById(“demo”).innerHTML = sumNumbers(3,8);

</script>

After execution, the innerHTML of the “demo” element would be:  11.

The Document Object Model (DOM) defines all of the web page elements that can be manipulated via Javascript.  When a web page is loaded by a browser, the browser creates a DOM which consists of a hierarchical tree of objects.  A simple DOM might look something like this:

Untitled

The DOM defines:

  • All HTML elements as objects
  • The properties of all HTML elements
  • The methods for accessing all HTML elements
  • The events for all HTML elements

Using Javascript and the DOM, you can:

  • Change any of the HTML elements or attributes on the page
  • Change any of the CSS styles on the page
  • Remove existing HTML elements and attributes or add new ones
  • Respond to any HTML events on the page or create new ones

The following methods allow you to get specific HTML elements or objects:

  • document.getElementById()  —  finds an element by its ID
  • document.getElementsByTagName()  —  finds all elements with a particular tag name
  • document.getElementsByClassName()   —  finds all elements by class name
  • document.body  —  returns the body of the document
  • document.cookie  —  returns the document’s cookie
  • document.URL  —  returns the document’s URL

The following methods allow you to change HTML elements:

  • element.innerHTML=  —  change the HTML contents of an element
  • element.attribute=  —  change the attribute of an HTML element
  • element.setAttribute(attribute,value)  —  set the attribute of an HTML element
  • element.style.property=  —  change the style of an HTML element
  • document.createElement()  —  create a new HTML element
  • document.write()  —  write HTML to the output stream

Javascript can respond to events in the browser environment.  Common events include:

  • onclick  —  mouse click
  • onchange  —  the contents of a form field change
  • onfocus  —  an element gets focus
  • onload  —  the page or an image loads
  • onmouseover  —  the mouse moves over an element
  • onsubmit  —  a form submit button is clicked

The Browser Object Model (BOM) defines elements of the browser that can be manipulated via Javascript.  Examples of browser properties that can be obtained by Javascript include:

  • window.innerWidth  —  inner width of the browser window
  • window.innerHeight  —  inner height of the browser window
  • screen.availWidth  —  width of the user’s screen in pixels
  • screen.availHeight  —  height of the user’s screen in pixels
  • window.location.href  —  URL of the current page

Examples of methods that can be used in Javascript to control elements related to the browser include the following:

  • window.open(“URL”)  —  opens new browser window
  • window.close()  —  closes browser window
  • window.resizeTo(width,height)  —  resizes browser window
  • window.location.assign(“URL”)  —  directs browser to a specific URL
  • window.alert(“some text”)  —  generates an alert box (the window prefix is optional)

window.setTimeout(milliseconds)  —  creates a pause for a specified time