Book: Beginning JavaScript with DOM Scripting and Ajax

Chapter Three

DOM obj Test

Testing for document.getElementById && document.createTextNode should be used to test the DOM support of a browser.

if(!document.getElementById || document.createTextNode){return;}

I am using document.getElementById and innerHTML to write the message below -

addPopUpLink

Small function opens up all links that have the class "smallpopup" in a new window and adds a message that this will happen. The function uses ubobtrusive JS because the onclick function for the popup window is added to the links with that class within the main JS. There is no onclick event handler manually added to the links.

Try it. This link has the class smallpopup on it jwolfproperties.com

This function uses getElementsByTagName, createTextNode and appendChild. return false; was used after the popup window was triggered so that the function would not return and follow the link (thus opening the window and proceeding on to the page).

linksInit()

In this exercise we create a link by passing it parameters of linkTarget and linkName. linksInit() uses both functions by taking the generated links and appending them to an element. If no element ID is defined then the append is to the body of the document.

linksInit() checks whether DOM is available and creates a link with a target of #top and "back to top" as link text. The first list item has an id of "itemone" and that parameter is passed to appendLink() as the elementID.

It then invokes appendLink() and sends BACK to initLink() the newly generated link as a parameter. If a target element is not sent, then elementId is null so that appendLink() will add the link to the body of the document.

The second time initLinks() invokes createLink(), it sends the target "close.html" and "go to page close.html" as the link text and applies the link the HTML element with the ID of main via the appendLink() function. If there is an element with the ID of "itemtwo", then appendLink() adds the link to the element; if not, it uses the document body as a fallback option. In this example, the second list item has an ID of "itemtwo"

The point of this exercise is to show how linksInit() passes parameters to createLink() that uses return tempLink to pass back the result to linksInit() where that values are used by appendLink() to create the list items shown below.

document.createElement(), appendChild(document.createTextNode(), and document.getElementById() are used in this exercise.

createNavlistLinks()

I wrote my own little program using the appendLink() function from the example above, to create the "quick links (intrapage links)" at the top of this page. The Quick Links are actually links within list items, styled using CSS to look like buttons. The program uses getElementById(), document.createElement('li') and setAttribute('id', [i]), appendChild(), getAttribute(), firstChild.getAttribute('id'), childNodes[1].nodeValue to create the link items from the <h3> and associated target anchors.

<h3><a id="unique ID"></a>Heading Text</h3>

Ternary Operator

To avoid the long complex if or switch statements using the ternary operator. For example, instead of an if and else setup, you could use the one line of code shown below.

var variable = condition ? trueValue : falseValue;
var direction = x < 200 ? 1 : -1

If x is less than 200 the direction equals 1 else the direction equals -1

Object Literal

Keeping scripts safe by creating an object and using your functions as methods of those objects. The long-hand way to create an object and the object funtions is like this -

myscript=new Object();
	 myscript.init=function() {
	 	//some code
		};
	  myscript.validate=function() {
	  	//some more code
		};

The shortcut notation creates the object and applies each of the functions as object methods instead of stand-alone functions. This example show how to do the linksInit(), createLink() and appendLink() from the linksInit() exercise above.

var dynamicLinks={
linksInit:function() {
  if(!document.getElementById || !document.createTextNode) { return; }
     var backLink=dynamicLinks.createLink('#top', 'back to top');
         dynamicLinks.appendLink(backLink, 'itemone');
     var goLink=dynamicLinks.createLink('close.html', 'go to page close.html');
         dynamicLinks.appendLink(goLink, 'itemtwo');
  }, //note the commma after the curly bracket
createLink:function(linkTarget, linkName) {	
  if(linkTarget == null) { linkTarget='#top'; }
  if(linkName == null) { linkName='dummy'; }
  var tempLink=document.createElement('a');
      tempLink.setAttribute('href', linkTarget);
      tempLink.appendChild(document.createTextNode(linkName));
      return tempLink;
  },	
appendLink:function(sourceLink, elementId) {
  var element=false;
  if(elementId==null || !document.getElementById(elementId)) {
     element=document.body;
   }
   if(!element) {
      element = document.getElementById(elementId);
   }
      element.appendChild(sourceLink);
   }//end appendlink
}//end dynamicLinks object 
window.onload=dynamicLinks.linksInit;

All the functions are contained as methods inside the dynamicLinks object and in order to call them you need to add the name of the object before the funtion name.

If you want to use variables that should be accessible by all the methods INSIDE the object you can do that with this syntax -

var myObject = {
  objMainVar:'preset',
  objSecondaryVar:0,
  objArray:['one','two','three'],
  init:funtion() { },
  createLinks:function() { },
  appendLinks:function() { }
  }//end myObject

Summary

Older scripts are likely to: