/* now we'll create the dog object,
* ask it to bark, and display how
* many times our dog obeyed us and spoke.
*/
var luna = new Dog();\n
luna.speak();\n
luna.speak();\n
result(luna.getBarks()+", Good girl Luna! You're awsome!
... now get the paper!");\n
\n
document.getElementById('resultbox').innerHTML = document.getElementById('resultbox').innerHTML;
function Dog(){\n
var barks = 0;\n
\n
this.getBarks = function(){\n
return barks+" barks";\n
};\n
this.speak = function(){\n
barks++;\n
result('Luna, speak!');
result('Rough!');
};\n
}\n
var i; i = $('div[id*=appDiv]').length+1; // check for number of colored boxes and add 1. /** a colored box may have been deleted, so we'll check if a box is already * assigned the value i and loop until we have an unassigned value to name it. **/; while($('#appDiv'+i).length > 0){ i=i+1; } writeResult(i+" divs"); // display the number of colored boxes. var newdiv = document.createElement('div'); // define the new colored box. newdiv.id = 'appDiv'+i; newdiv.style.position = "absolute"; newdiv.style.top = (i*25)+"px"; newdiv.style.left = (i*25)+"px"; newdiv.style.width = "180px"; newdiv.style.height = "180px"; newdiv.style.padding = "10px"; newdiv.style.backgroundColor = get_random_color(); newdiv.innerHTML = "Div "+i+": Drag me, or double click me to change my color"; newdiv.style.display = "none";
if(i<7){ var newbut = document.createElement('input'); // define new control button. newbut.type="submit"; newbut.id="ctrlAppDiv"+i; newbut.value="Del "+i; document.getElementById('promo').appendChild(newbut); // add the control button. document.getElementById('ctrlAppDiv'+i).onclick = function(e){ $('#appDiv'+i).fadeOut(500, function(){$(this).remove();}); $('#ctrlAppDiv'+i).remove(); } }
document.body.appendChild(newdiv); // add the new colored box. $('#appDiv'+i).draggable(); $('#appDiv'+i).fadeIn(500); $('#appDiv'+i).dblclick(function(){ document.getElementById('appDiv'+i).style.backgroundColor = get_random_color();});
function get_random_color() { var letters = '0123456789ABCDEF'.split(''); var color = '#'; for (var i = 0; i<6; i++ ) { color += letters[Math.round(Math.random() * 15)]; } return color; } // loops with no increment control for(x=0; x != 120; ) x++; str = "With no Increment: " result(str+x);
// bodiless loops var sum = 0; for(i = 1; i < 15; sum += i++) ; str = "Bodiless "; result(str+sum);
// loops with multiple control variables str = "Multiple control vars: "; result(str); str = "    x="; var str2 = " y="; for(x=0, y=10; x <= y; ++x, --y) result(str+x+str2+y); // create a new object that displays an alert box. x=new alerttest1();
// now replace that object with a new object which will override the // first function and will have a value within it's own private get method. x=new alerttest2();
// now display the overriding function's private value stored in memory // thanks to closures. result("Variable x is "+x.getSize()+" meters");
function alerttest1(){ result("variable x"); }
function alerttest2(){ result("new variable x"); var size=5; this.getSize = function(){ return size; } } // binding methods to objects
var obj = { greet: 'Hello, my name is', buildGreeting: function (name) { return this.greet + ' ' + name; } }
result(obj.buildGreeting('Brandon')); // displays: Hello, my name is Brandon
f = obj.buildGreeting; result(f('John')); // displays: undefined John
g = bind(obj, obj.buildGreeting); result(g('Dwight')); // displays: Hello, my name is Dwight
function bind(obj, method) { return function() { return method.apply(obj, arguments); } } // static local variable
function count() { return count.i++; } count.i = 0;
count(); count(); count(); result("The count function was called "+count.i+" times"); // assertion
function assert(condition, exp, message) { try{ if (!condition) { result(exp.toString().toUpperCase()+message); throw new Error(exp); } } catch (oException) { } }
assert(false, assert != null, ": The object assert exists."); assert(false, assert.name == "assertion", ": Assert is named assertion."); assert(false, 1+2==4, ": 1+2 is equal to 4"); assert(false, "this is a string"=="this is a string", ": The 2 strings are equivalent"); assert(false, "b" == "B", ": the characters 'b' and 'B' are equal"); // try catch statement preventing app failure upon referencing an undeclared object. function runNonExistantObj(){ try { x = someObject; } catch (err) { if (err instanceof TypeError) { result("A TypeError occured."); result("Message: " + err.message); result("First case"); } else if (err instanceof RangeError) { result("A RangeError occured."); result("Message: " + err.message); result("Second case"); } else if (err instanceof SyntaxError) { result("A SyntaxError occured."); result("Message: " + err.message); result("Third case"); } else { result("A " + err.name + " occured."); result("Message: " + err.message); result(""); result("Although this is a last resort effort because it") result("doesn't have code to handle the specific problem,"); } } finally { result(""); result("the error has been handled."); } }
runNonExistantObj(); String.prototype.toCapitalCase = function() { var re = /\s/; var words = this.split(re); re = /(\S)(\S+)/; for (i = words.length-1; i >= 0; i--) { re.exec(words[i]); if(words[i].length==1 || isNaN(words[i])==false){ words[i] = words[i].toUpperCase(); } else { words[i] = RegExp.$1.toUpperCase() + RegExp.$2.toLowerCase(); } } return words.join(' '); }
var myfield = "For every minute you are angry, you lose sixty seconds of happiness."; myfield = myfield.toCapitalCase(); result(myfield); // initialize an object with a property.
function Puppy(name){ this.changeName = function(name){ this.name = name; };
this.changeName(name); }
var puppy = new Puppy("Cherry"); result("The puppies name is "+puppy.name);
puppy.changeName("Princess"); result("The puppies new name is "+puppy.name); /** server side functions are used fro the primary validation of user input. * Here are examples of some server side validation functions. * * binarySearch - returns the index of the match if found, -1 if not found * toString - casts the input as a string * minLength - returns true if the string is at least 7 characters * phone - returns true if the string can be read as a US phone number * email - returns true if the email address is valid * password - returns 'pass' if the word meets criteris * Min criteria: 8-12 chars, 1 lower, 1 upper, 1 number, * 1 special, 4 sequential, no banned words [the, when, come, can, * and, think, you, what, password, dictionary, enter, pass, open] **/
var myInput = "passQWERTY"; var myFunction = "password"; // myList must be in order var myList = "10, 17, 20, 22, 26, 29, 30, 31, 34, 38, 44, 45, 46, 50, 56";
run_ajax(myInput, myFunction, myList);
//Browser Support Code function run_ajax(op, func, op2){ var ajaxRequest;
try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e) { // Internet Explorer Browsers try { ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } // function that will receive data sent from the server ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ //var ajaxDisplay = document.getElementById('cal_writable'); result(ajaxRequest.responseText); } }
var queryString = "?o=" + op + "&f=" + func + "&o2=" + op2; ajaxRequest.open("GET", "./demobox_ajax_return" + queryString, true); ajaxRequest.send(null); } //create the array that will store user's objects. var user = new Array();
// define the users function person(first, last){ this.idnum = last+first; this.first = first; this.last = last; }
// function to a new users to the array. function addUser(first, last){ var len; len = user.length; user[len] = new person(first, last); }
// find, then display the number of users. len = user.length; result(user.length+ " people found:");
var indent = " "; // add indentation in results
// go through the users and list each of them. for(var i=0; i < len; i++) result(indent+user[i].last+", "+user[i].first); //create the array that will store user's objects var user = new Array();
// define the users function person(f, l, p){ // local variables var first = ""; var last = ""; var phone = ""; // setter methods to set local variables this.setFirst = function(f){ first = f; }; this.setLast = function(l){ last = l; }; this.setPhone = function(p){ phone = p; }; // getter methods to get local variables this.getFirst = function(){ return first; }; this.getLast = function(){ return last; }; this.getFullName = function(){ return last+", "+first; }; this.getPhone = function(){ return phone; }; // set local variables on initiation this.setFirst(f); this.setLast(l); this.setPhone(p); }
// function to add new users to the array function addUser(first, last, phone){ var len; len = user.length; user[len] = new person(first, last, phone); }
// addMethod - By John Resig (MIT Licensed) function addMethod(object, name, fn){ var old = object[ name ]; if ( old ) object[ name ] = function(){ if ( fn.length == arguments.length ) return fn.apply( this, arguments ); else if ( typeof old == 'function' ) return old.apply( this, arguments ); }; else object[ name ] = fn; }
// function to define and overload search functions. function UserSearch(){ addMethod(this, "find", function(){ // search all contacts result("Contacts:"); len = user.length; for(var i=0; i < len; i++) result(indent+user[i].getFullName()+" - "+indent+user[i].getPhone()); result(""); result(len+" total"); }); addMethod(this, "find", function(l){ // search by last name len = user.length; var matches = 0; result("Matches:"); for(var i=0; i < len; i++) { if(user[i].getLast() == l){ result(indent+user[i].getFullName()+" - "+indent+user[i].getPhone()); matches++; } } result(""); result(matches+" found"); }); addMethod(this, "find", function(l, f){ // search by first and last name len = user.length; var matches = 0; result("Matches:"); for(var i=0; i < len; i++) { if(user[i].getLast() == l && user[i].getFirst() == f){ result(indent+user[i].getFullName()+" - "+indent+user[i].getPhone()); matches++; } } result(""); result(matches+" found"); }); } // This is a helper class that contains the inheritance functionality // Inspired by base2 and Prototype, written by John Resig (function(){ var initializing = false, // Determine if functions can be serialized fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/; // Create a new Class that inherits from this class Object.subClass = function(prop) { var _super = this.prototype; // Instantiate a base class (but only create the instance, // don't run the init constructor) initializing = true; var proto = new this(); initializing = false; // Copy the properties over onto the new prototype for (var name in prop) { // Check if we're overwriting an existing function proto[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function(name, fn){ return function() { var tmp = this._super; // Add a new ._super() method that is the same method // but on the super-class this._super = _super[name]; // The method only need to be bound temporarily, so we // remove it when we're done executing var ret = fn.apply(this, arguments); this._super = tmp; return ret; }; })(name, prop[name]) : prop[name]; } // The dummy class constructor function Class() { // All construction is actually done in the init method if ( !initializing && this.init ) this.init.apply(this, arguments); } // Populate our constructed prototype object Class.prototype = proto; // Enforce the constructor to be what we expect Class.constructor = Class; // And make this class extendable Class.subClass = arguments.callee; return Class; }; })();
// Class definitions var Animal = Object.subClass({ init: function(f, b){ var food = f; var blastula = b; this.set_food = function(f){ food = f; }; this.set_blastula = function(b){ blsatula = b; }; this.get_food = function(){ return "I eat "+food; }; this.get_blastula = function(){ return "Do I have an embryonic blastula stage? "+blastula; }; } }); var Mammal = Animal.subClass({ init: function(b, m){ this._super("everything, especially veggies", "Of course"); var blood = b; var mammary = m; this.get_blood = function(){ return "I'm "+blood; }; this.get_mammary = function(){ return "I have "+mammary; }; } }); var Primate = Mammal.subClass({ init: function(f, t){ this._super("warm-blooded", "mammary glands"); var fingers = f; var thumbs = t; this.get_fingers = function(){ return "I have "+fingers+" fingers"; }; this.get_thumbs = function(){ return "I have "+thumbs; }; } }); var Human = Primate.subClass({ init: function(b, s){ this._super("5", "opposable thumbs"); var brains = b; var stand = s; this.get_brains = function(){ return "I have a "+brains; }; this.get_stand = function(){ return "I "+stand; }; } });
var A = new Animal("alot of everything", "All animals do!"); var M = new Mammal("warm-blooded", "mammary glands"); var P = new Primate("5", "opposable thumbs"); P.set_food("alot of bananas, as well as veggies"); var H = new Human("higher brain", "stand erect"); H.set_food("steaks, as well as alot of bananas and some veggies"); result("Animal:"); result(A.food+", Oops! var food is indeed private."); result(A.get_food()); result(A.get_blastula()); result(""); result("Mammal"); result(M.get_food()); result(M.get_blastula()); result(M.get_blood()); result(M.get_mammary()); result(""); result("Primate:"); result(P.get_food()); result(P.get_fingers()); result(P.get_thumbs()); result(""); result("Human"); result(H.get_food()); result(H.get_brains()); result(H.get_stand()); //create the array that will store user's objects var people = new Array();
// define the peoples function Person(f, l, p, r, t){ // local variables var first = ""; var last = ""; var skill = ""; var ball = ""; var possession = ""; var play = ""; var team = ""; // setter methods to set local variables this.setFirst = function(f){ first = f; }; this.setLast = function(l){ last = l; }; this.setSkill = function(p){ skill = p; }; this.setBall = function(b){ ball = b; }; this.setPossession = function(p){ possession = p; }; this.setPlay = function(i){ play = i; }; this.setTeam = function(i){ team = i; }; // getter methods to get local variables this.getFirst = function(){ return first; }; this.getLast = function(){ return last; }; this.getFullName = function(){ return last+", "+first; }; this.getSkill = function(){ return skill; }; this.getBall = function(){ return ball; }; this.getPossession = function(){ return possession; }; this.getPlay = function(){ return play; }; this.getTeam = function(){ return team; }; // set local variables on initiation this.setFirst(f); this.setLast(l); this.setSkill(p); this.setPlay(r); this.setTeam(t); }
// function to add new peoples to the array function addPerson(first, last, skill, play, team){ var len; len = people.length; people[len] = new Person(first, last, skill, play, team); }
function findMan(){ var pl; var check = 0; var players = 0; var possess = 0; var count = 0; var throwspeed;
// look to see if anyone is playing. for(i=0; i < people.length; i++){ if(people[i].getPlay()==1) players++; if(people[i].getPossession() > 0) possess = i+1; }
if(out>0) people[out-1].setPlay(0); // if the ball was caught, call the person who threw it out.
for(i=0; i < people.length; i++){ if(i!=pl) people[i].setPossession(0); // take possession from anyone who may have had it. } }
//writeResults(0, "Dwight", "out", " "); function writeResults(i, name, status, results){
if(status=="in") status = "nLIn"; else status = "nLOut";
var nR = "nRStd"; switch(results){ case "Caught it": nR = "nRCaught"; break; case "Dodged it": nR = "nRStd"; break; case "Hit": nR = "nRHit"; break; case " ": nR = "nROut"; break; case "": nR = "nROut"; break; default: nR = "nRStd"; }
var newdiv; var newSpan; var newSpanL;
newdiv = document.createElement('div'); // define the new colored box. newdiv.id = 'appDiv'+i; newdiv.className = 'nDiv'; newdiv.style.position = "relative";
document.getElementById('resultbox').appendChild(newdiv); // add the new colored box.
newSpan = document.createElement('div'); // define the new colored box. newSpan.id = 'apSpanL'+i; newSpan.className = status; newSpan.innerHTML = name;
document.getElementById('appDiv'+i).appendChild(newSpan); // add the new colored box.
if(results.length>0){ newSpanR = document.createElement('div'); // define the new colored box. newSpanR.id = 'apSpanR'+i; newSpanR.className = nR; newSpanR.innerHTML = results;
document.getElementById('appDiv'+i).appendChild(newSpanR); // add the new colored box. }
if(status == "nLIn"){ if(nR == "nRCaught" || nR == "nRStd" || nR == "nRHit"){ $('#appDiv'+i).animate({ backgroundColor: "#91a4de" }, 0 ).animate({ backgroundColor: "#7088d5" }, 4000 ); } // close nR multiples } // close status == "nLIn" }
Dynamically add new divs and buttons to the page and bind the buttons to the divs. We'll also define jQuery effects and selectors and change the background colors.
Control loops, the C++ way
C++ offers many powerful features that are less known in javascript. These are the realms of cs majors rather than web designers. Here, infinite loops, bodiless loops, multiple control variables, and missing control statements are demonstrated.
Function override and closures
Create a variable, override it, and display a private variable stored in memory through closures.
Binding methods to objects
This binds a method to an object; it takes an object and method, and returns a function that always calls the method in the context of that object.
Local static variable
Local variable that retains it's value between calls.
Assert function
Ensure that an expression evaluates to true during execution. If the expression evaluates to false, there may be a bug in the code or logic.
Error handling, the try/catch
The try catch statement is used when an exception may occur that needs to be handled to prevent application failure.
Prototypes and functions - toCapitalCase
Here we'll add a function to the String object's prototype. It will ensure every word begins with a capital letter with all the remaining letters lower case.
Initialize objects with properties
Create a new object with a public property via an accessor.
Ajax server calls
Ajax script to run one of several server side scripts and return the result.
Storing objects in arrays
This will demonstrate the assignment of objects to arrays. Objects (people) are created, assigned to an array, and their properties accessed.
Storing objects in arrays - advanced
Continuing on the previous example, objects store information in local variables and function overriding is used in object variable searches.
Object inheritance
Explore javascript's object oriented inheritance capabilities with classes implementing private variables and accessors.
Dodgeball OO
Demonstration of object orientation in a dodgeball like framework. Demonstrates object creation, private variables, accessors, passing objects through arguments, object arrays, and array searches.
var str=document.getElementById('func_i').innerHTML;
str = str.replace(/\\n/g, '');
document.getElementById('example').value=str;