Lecture 4

Common.js/Global.js

Every JS developer has a file called common.js (well, most of us do, some call it global.js). This file has a few crucial functions that serve as a mini library. When we aren’t using a full-blown library that handles this stuff natively, we just use the common.js. Everyone’s common.js file is different. As you collect functions that are useful and universal, you can add them to your personal common.js library. But watch out! It will get big so practice regular pruning and source version control :)

Here’s a common.js with some goodies

How to know if a Script is good

  • Read the Documentation
  • Avoid scripts that use document.all, document.layers, navigator.appName
  • Is the code readable?
  • How light is it?
  • Can you rewrite it better?
  • Search Google for answers :)

Beyond Other People’s Code

Building your own JavaScript Library

Further Reading

In Class: Playing with Common.js

Download test.html here

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<title>Valid XHTML Document!</title>
        <script src="common.js" type="text/javascript"></script>
        <script type="text/javascript"><!--
		addEvent(window, 'load', function(){
			addEvent(
				document.getElementById('myEl'), 
				'click', 
				function(){
				// function
					//alert('You clicked the div');
					//toggle(document.getElementById('myEl'));
					// same thing:
					toggle('myEl2');
				}
			);
		});
		--></script>
		<style type="text/css"><!--
		.box {
			width:100px;
			height:100px;
			background-color:#036;
			cursor:pointer;
		}
		.orange {
			background-color:#f60;
		}
		--></style>
	</head>
	<body>
    <div class="box" id="myEl"></div>
    <div class="box orange" id="myEl2"></div>
 
	</body>
</html>

Download common.js here

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
// common.js
function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}
 
var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();
addEvent(window,'unload',EventCache.flush);
 
//9) addLoadEvent()
//
//Originally written by Simon Willison and highly adopted by many others as a simple way to add events to trigger after the page has loaded. This of course attaches all your events to the onload event handler which some still see as necessary, nevertheless it does exactly what it’s supposed to, and does it well.
//addLoadEvent() by Simon Willison
 
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}
 
//Of course another method is to simply assign multiple event listeners to the window by using addEvent() as described in number 10 as follows:
//assigning multiple load events to window
//
//addEvent(window,'load',func1,false);
//addEvent(window,'load',func2,false);
//addEvent(window,'load',func3,false);
//
//8) getElementsByClass()
//
//Originially written by nobody in particular. Several developers have implemented their own version and no one single version has proven to be better than another. As you might expect, my humble self has even had a crack at it. This function was spawned from developers needing a quick and elegant way of grabbing elements by a className and to a developer’s surprise, it’s not an original DOM method as one might think…afterall, we have getElementById, getElementsByName(), getElementsByTagName, what the hell happened to getElementsByClass??? Here it is in all its glory:
//getElementsByClass by Dustin Diaz
 
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}
 
//Simply add a class name to the beginning of the funciton and the 2nd and 3rd arguments are optional and the magic is done for you!
//7) cssQuery()
//
//Originally written by Dean Edwards as a way to query the DOM according to CSS properties which supports a multitude of selectors. However in all fairness, this is more like a mini-library and not quite so light on the weight factor, but still, a very kick-ass function. Due to its length (and CC lisencing) I won’t post it on this site. Full documentation can be found on the myCssQuery reference and download page.
//6) toggle()
//
//To be totally honest, there are probably more variations of this function than there needs to be. The history of ‘toggling’ basically comes down to showing/hiding an element upon an event being fired. To make matters much simpler, I too have put one together. But by no means is it considered the ultimate toggle function, but it does do the basic functionality of showing and hiding.
//toggle() by the masses
 
function toggle(obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = '';
	}
 
}
 
//5) insertAfter()
//
//As far as I know, Jeremy Keith sort of came up with this idea even though one would have thought this too would be a DOM core method. But just like getElementsByClass, it isn’t. So rather than pulling the function straight out of the book, I’ll leave that up to you to buy it yourself. Instead I’ve pulled this simple method from public domain:
//insertAfter() on public domain
//
//function insertAfter(parent, node, referenceNode) {
//	parent.insertBefore(node, referenceNode.nextSibling);
//}
//
//4) inArray()
//
//This too is very sad that this isn’t part of the DOM core functionality. But hey, it makes for fun references like this! This function however isn’t quite a function; it’s a prototype that extends the DOM Array object. I remember one day thinking to myself “surely I can do this in PHP, it’s gotta be in JavaScript.” Well, this extension makes it work just like you’d expect if you’re a PHP developer. Here is a version from EmbiMEDIA
//inArray Prototype Array object by EmbiMedia
 
 
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};
 
//3, 2, & 1) getCookie(), setCookie(), deleteCookie()
//
//I honestly don’t know what I would do without these guys. I hate the DOM implementations of setting cookies in JavaScript. In PHP it’s so easy, and it’s easy for one main reason, they work just like the functions below. All three of these functions were found to be public domain and free to use.
//getCookie(), setCookie(), deleteCookie() open domain
 
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}
 
function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+"="+escape( value ) +
		( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}
 
function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) 
		document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ';domain="' + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
 
//Last but not least, a bonus function: The Prototype Dollar Function
//
//This function straight up kicks so much ass. First of all, just look at it.
//Prototype function $
 
function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}
 
// Sample Usage:
var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2');
function alertElements() {
  var i;
  var elements = $('a','b','c',obj1,obj2,'d','e');
  for ( i=0;i<elements.length;i++ ) {
    alert(elements[i].id);
  }
}

Q&A

Here’s your chance to ask questions about the final or any other programming related queries.

Final Due!

I need this by the end of the class.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Web Development Courses, Rants, Tutorials and Hacks