Some Javascript Examples

Note:

  1. clicking on the title header will link you to the actual html webpage whose source code you are viewing.
  2. Starting from the Anchors example, I will stop pasting the source code here since I have created a php sources server (which was an interesting project)

Event Handling
Random notes
Search Highlighted Text
My PHP Sources Server
DOM Anchors
Pop Up Functions
Functions
Variadic Functions
Error Handling
Loan Calculator
BMI Calculator
FlexiSum Calculator
Nested Functions as Closures
Closures2
Methods Properties on Strings
Methods Properties on Dates


Event Handling

These are notes I took while reading the txt book chapter 17.

Basic Event Handling

HTML is case-insensitive while XHTML and javascript are not, therefore be careful when writing your code.
Event Handlers as properties:

function plead( ) { document.f1.b1.value += ", please!"; }
document.f1.b1.onmouseover = plead;

Please note that to define event handlers in javascript, you assign the function itself and not the result of invoking the function hence the =plead; above instead of =plead();

Advanced Event Handling with DOM Level 2

How to check for an empty form

<form action="search.cgi"
      onsubmit="if (this.elements[0].value.length == 0) return false;">
<input type="text">
</form>

this keyword issues
What is the diff. between
button.onclick= o.mymethod;
and

button.onclick = function( ) { o.mymethod( ); }
??
The first statement makes button.onclick refer to the same function that o.mymethod does i.e. calling this.mymethod refers to the button object.
Meanwhile, in the second statement, the this keyword would refer to the object o.

Table 17-3 (Chapter 17.2.5) lists the common event types, their interface and detail properties. Most properties are read only and can be used to extract details about an event for example detail property on the click event shows how many consecutive clicks have occured.

Event - defines two methods that are also implemented by all event objects: stopPropagation( ) and preventDefault( ). Any event handler can call stopPropagation( ) to prevent the event from being propagated beyond the node at which it is currently being handled. Any event handler can call preventDefault( ) to prevent the browser from performing a default action associated with the event. (Chapter 17.2.6.1)
UIEvent
MouseEvent

The Internet Explorer Event Model

Mouse Events

Key Events
There are three keyboard event types: keydown, keypress, and keyup; they correspond to the onkeydown, onkeypress, and onkeyup event handlers.

The onload Event
Sometimes you may want some functions on your webpage to only run once the page has fully loaded. Therefore, this code below can help. You can include the array of the functions that you want to run in the runOnLoad.funcs = [];and they will be only run when the page loads.

/*
 * runOnLoad.js: portable registration for onload event handlers.
 *
 * This module defines a single runOnLoad( ) function for portably registering
 * functions that can be safely invoked only when the document is fully loaded
 * and the DOM is available.
 *
 * Functions registered with runOnLoad( ) will not be passed any arguments when
 * invoked. They will not be invoked as a method of any meaningful object, and
 * the this keyword should not be used. Functions registered with runOnLoad( )
 * will be invoked in the order in which they were registered. There is no
 * way to deregister a function once it has been passed to runOnLoad( ).
 *
 * In old browsers that do not support addEventListener( ) or attachEvent( ),
 * this function relies on the DOM Level 0 window.onload property and will not
 * work correctly when used in documents that set the onload attribute
 * of their <body> or <frameset> tags.
 */
function runOnLoad(f) {
    if (runOnLoad.loaded) f( );    // If already loaded, just invoke f( ) now.
    else runOnLoad.funcs.push(f); // Otherwise, store it for later
}

runOnLoad.funcs = []; // The array of functions to call when the document loads
runOnLoad.loaded = false; // The functions have not been run yet.

// Run all registered functions in the order in which they were registered.
// It is safe to call runOnLoad.run( ) more than once: invocations after the
// first do nothing. It is safe for an initialization function to call
// runOnLoad( ) to register another function.
runOnLoad.run = function( ) {
    if (runOnLoad.loaded) return;  // If we've already run, do nothing

    for(var i = 0; i < runOnLoad.funcs.length; i++) {
        try { runOnLoad.funcs[i]( ); }
        catch(e) { /* An exception in one function shouldn't stop the rest */ }
    }

    runOnLoad.loaded = true; // Remember that we've already run once.
    delete runOnLoad.funcs;  // But don't remember the functions themselves.
    delete runOnLoad.run;    // And forget about this function too!
};

// Register runOnLoad.run( ) as the onload event handler 
 for the window
if (window.addEventListener)
    window.addEventListener("load", runOnLoad.run, false);
else if (window.attachEvent) window.attachEvent("onload", runOnLoad.run);
else window.onload = runOnLoad.run;

Synthetic Events

Back to Top


Random notes

This is an extract from 15.6 in O'Reilly's javascript txtbook. When finding elemnts in a document, the getElementsByTagName() method is a convenient body property that returns an array of all <body> elements within the document.

Back to Top


Search Highlighted Text

View the page: [http://galiwood.com/javascript/search]
View the Source Code

This function searches either wikipedia, google or freedictionary for the text that you select/highlight with your mouse.
I have plans to develop this idea further into some tool because it can be quite helpful. I have been interrupted manytimes when reading to open browsers to search for meaning of words which can be slow and annoying. what if there was a one stop shop for different types of searches, a marshup of some sort.

The main function here is getSelectedText which takes no argument and simply traverses the selected document or window (depending on what is selected) in order to extract the text to be returned and queried by the corresponding search engines.
Once returned, we utilize the property that you can pass javascript code as a url to open a new window with results of the search. Notice that I used all possible attributes to show how one can manipulate window opening within a link in javascript for the Wikipedia link.

Back to Top


My PHP Sources Server

View the page: Sources Server
View the Source Code

This was created to easily provide Prof. Rasala access to the source code of the files that I was working on on my server. I searched around the net for tools to do this at first but they were all for sale so I decided to dig into scripts and tutorials on how to do it myself until I came up with this from two different sources.
I have pretty good documentation/comments in the source code itself to explain what is happening so please read through.

Back to Top


List Anchors Example

View the page: List Anchors
View the Source Code

This DOM example is supposed to open a new window once you click the button and then list all the links within the document. However, I don't know yet why it's not working…qn. for Prof. Rasala
This was just unresourcefulness on my part. I simply was not passing the document object to the listanchors function.
Understanding the code: We have already determined that we pass the entire document to the listanchors function once the button is clicked.
In order to list all anchors, we first attain how many anchors are in our page using d.anchors.length so we can know when to terminate our iteration.
Then in the for loop, we firstly assign the array of anchors in our document to a variable a. Then we configure our function different browsers i.e. IE and Netscape.
Therefore for each element in the array a (which would be an anchor), we parse it so as to make it a link in our new document which will be a pop-up window.
As commented in the source code, never forget to close the document.

Back to Top



Pop Up

This just shows the three main interactive javascript functions, alert, confirm and prompt, which can be used to get user values to pass to a function.

I also manipulated the built in date function in this example.

Source Code:


<html>
<head>
<script type="text/javascript">
//Write "Lunch-time!" if the time is 11
var d=new Date()
var time=d.getHours()
if (time==11)
{
document.write("</br><b>Lunch-time!</b></br>")
}
else
{
document.write("</br><b>Oh Well, not yet breakfast then</b></br>")
}
</script>
</head>
<body>
<script type="text/javascript">
document.write("Hello World!")
confirm("sometext")
alert("anothertext")
prompt("sometext","defaultvalue")
</script>
</body>
</html>
[[/code]]
Back to Top


Functions
This is just a general introduction to Javascript functions. In the source code you can see examples of how we use try and catch in javascript. Please see the Error Handling example for more details.
Source Code:

<html>
<head>
<script type="text/javascript">
function Gali()
{
for (var i=0;i<5;i++)
{
document.write("</br>This is crazy "+i + "<br />")
}
var x
var myNames = new Array()
myNames[1]="Alan"
myNames[2]="Alan2"
myNames[3]="Alan3"
myNames[4]="Alan4"
for(x in myNames)
{
document.write(myNames[x]+ "<br />")
}
}
 
var txt=""
function trycatch()
{
try
  {
  adddlert("Welcome guest!")
  }
catch(err)
  {
  txt="There was an error on this page.\n\n"
  txt+="Error description: " + err.description + "\n\n"
  txt+="Click OK to continue.\n\n"
  alert(txt)
  }
}
 
function mythrow()
{
x = prompt("Enter a number between 0 and 10","")
try{
if (x<0) throw "err1" 
 if (x>10)throw "err2" 
}
catch(myerr)
{
if (myerr=="err1") alert("number is less than 0")
if (myerr=="err2") alert("number is greater than 10")
}
}
</script> 
</head>
<body>
<form>
<input type="button"
onclick="Gali()"
value="heello"
>
</form>
 
<a href="http://www.galiwood.com"
onmouseover="alert('An onMouseOver event');return false">
<img src="../images_movies/club.gif" width="100" height="30">
</a> 
</br>
<b>Try and Catch example</b>
<input type="button" value="TryCatch" onclick="trycatch()" />
</br>
<b>Throw example</b>
<input type="button" value="Throw" onclick="mythrow()" />
</body>
</html>

Back to Top


Variadic Functions
This script finds the largest number given an arbitrary number of elements

Source Code:

<html>
<head>
<script type="text/javascript">
function max(/* ... */)
{
    var m = Number.NEGATIVE_INFINITY;
    // Loop through all the arguments,  looking for, and remembering, the biggest
    for(var i = 0; i < arguments.length; i++)  if (arguments[i] > m) m = arguments[i];
    // Return the biggest
    alert("m is "+m);    return m;
}
var largest = max(1, 10, 100, 2, 3, 1000, 4, 5, 10000, 6);
alert("largest is" +largest);
</script> 
</head>
<body>
 <input type="button" value="Max" onclick="max(1, 10, 100, 2, 3, 1000, 4, 5, 10000, 6);">
</body>
</html>

Back to Top


Error Handling
This is a useful function that will help us identify a script error on any webpage.
It uses a onerror event function to identify what sort of error happened and at what line. This can be helpful in coding to catch your errors.
I have messed around with the original example to see how the browsers deal with the error. It seems that the example above shown, it goes ahead and executes the program until the line of the error after which it throws the popup error message as expected.
Source Code:

<html>
<head>
<script type="text/javascript">
onerror=handleErr
var txt=""
function handleErr(msg,url,l)
{
txt="There was an error on this page.\n\n"
txt+="Error: " + msg + "\n"
txt+="URL: " + url + "\n"
txt+="Line: " + l + "\n\n"
txt+="Click OK to continue.\n\n"
alert(txt)
return true
}
function message()
{
alert("Welcome guest!")
popo
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>

Back to Top


Loan Calculator
This is an HTML form that allows the user to enter data and allows JavaScript to display the results it computes back to the user. The form elements are embedded in a table to improve their appearance. The form itself is given the name "loandata", and the fields within the form are given names such as "interest" and "years". These field names are used in the JavaScript code that follows the form. Note that some of the form elements define "onchange" or "onclick" event handlers. These specify strings of JavaScript code to be executed when the user enters data or clicks on a button.

It has a JavaScript function that makes the example work. Note that this script defines the calculate() function called by the event handlers in the form. The function reads values from the form <input> fields using the names defined in the previous HTML code. It outputs its results into the named <span> elements.

Source Code:

<html>
<head>
<title>JavaScript Loan Calculator</title>
<style>
/* This is a CSS style sheet: it adds style to the program output */
.result { font-weight: bold; }  /* For elements with class="result" */
#payment { text-decoration: underline; } /* For element with id="payment" */
</style>
</head>
<body>
<form name="loandata">
  <table>
    <tr><td><b>Enter Loan Information:</b></td></tr>
    <tr>
      <td>1) Amount of the loan (any currency):</td>
      <td><input type="text" name="principal" onchange="calculate();"></td>
    </tr>
    <tr>
      <td>2) Annual percentage rate of interest:</td>
      <td><input type="text" name="interest" onchange="calculate();"></td>
    </tr>
    <tr>
      <td>3) Repayment period in years:</td>
      <td><input type="text" name="years" onchange="calculate();"></td>
    </tr>
    <tr>
    <td>Gali comment: In this case, the onclick functionality of the button below is 
    redundant because of the onchange functionality already embedded into the form's 
    input such it the calculate funtion is called each time a value changes. 
     </td>
      <td><input type="button" value="Compute" onclick="calculate();"></td>
    </tr>
    <tr><td><b>Payment Information:</b></td></tr>
    <tr>
      <td>4) Your monthly payment:</td>
      <td>$<span class="result" id="payment"></span></td>
    </tr>
    <tr>
      <td>5) Your total payment:</td>
      <td>$<span class="result" id="total"></span></td>
    </tr>
    <tr>
      <td>6) Your total interest payments:</td>
      <td>$<span class="result" id="totalinterest"></span></td>
    </tr>
  </table>
</form>
 
<script language="JavaScript">
function calculate() {
    // Get the user's input from the form. Assume it is all valid.
    // Convert interest from a percentage to a decimal, and convert from
    // an annual rate to a monthly rate. Convert payment period in years
    // to the number of monthly payments.
    var principal = document.loandata.principal.value;
    var interest = document.loandata.interest.value / 100 / 12;
    var payments = document.loandata.years.value * 12;
 
    // Now compute the monthly payment figure, using esoteric math.
    var x = Math.pow(1 + interest, payments);
    var monthly = (principal*x*interest)/(x-1);
 
    // Get named <span> elements from the form.
    var payment = document.getElementById("payment");
    var total = document.getElementById("total");
    var totalinterest = document.getElementById("totalinterest");
 
    // Check that the result is a finite number. If so, display the
    // results by setting the HTML content of each <span> element.
    if (isFinite(monthly)) {
        payment.innerHTML = monthly.toFixed(2);
        total.innerHTML = (monthly * payments).toFixed(2);
        totalinterest.innerHTML = ((monthly*payments)-principal).toFixed(2);
    }
    // Otherwise, the user's input was probably invalid, so display nothing.
    else {
        payment.innerHTML = "";
        total.innerHTML = ""
        totalinterest.innerHTML = "";
    }
}
</script>
</body>
</html>

Back to Top


BMICalculator
This example was inspired by the loan calculator. There was a helpful lesson learnt by Prof. Rasala and I that in order to force a var to be of type int or float in javascript, one has to use either eval or the "+" sign before it as shown below.
Otherwise the code and functions are similar to the loan example above.

Source Code:

<html>
<head>
<title>Gali's Overweight Calculator</title>
<style>
/* This is a CSS style sheet: it adds style to the program output */
.result { font-weight: bold; }  /* For elements with class="result" */
#payment { text-decoration: underline; } /* For element with id="payment" */
</style>
</head>
<body>
<form name="bodydata">
  <table>
    <tr><td><b>Enter Your Body Weight and Height Information:</b></td></tr>
 
  <tr>
      <td>1) Height: <input type="text" name="ft" onchange="calculate();">feet </td>
      <td>and  <input type="text" name="inches" onchange="calculate();"> inches</td>
   </tr>    
 
    <tr>
      <td>2) Weight: <input type="text" name="weight" onchange="calculate();"> 
      pounds</td>
    </tr>
 
    <tr>
      <td><input type="button" value="Compute" onclick="calculate();"></td>
   </tr>
 
    <tr><td><b>Health Information:</b></td></tr>
    <tr>
      <td>Your BMI is:</td>
      <td><span class="result" id="bmi"></span></td>
    </tr>
    <tr>
      <td>You are currently:</td>
      <td><span class="result" id="weightclass"></span></td>
    </tr>
 
  </table>
</form>
 
<script language="JavaScript">
 
function calculate() {
    // Get the user's input from the form. Assume it is all valid.
    // Convert interest from a percentage to a decimal, and convert from
    // an annual rate to a monthly rate. Convert payment period in years
    // to the number of monthly payments.
    var ft = document.bodydata.ft.value * 12;
    var inches = document.bodydata.inches.value;
    var weight = document.bodydata.weight.value * 703;
    var height = eval(inches) + eval(ft);
    var denom = Math.pow(height, 2); var totalbmi = weight/denom;
 
    // Get named <span> elements from the form.
    var bmi = document.getElementById("bmi");
    var weightclass = document.getElementById("weightclass");
 
    // Check that the result is a finite number. If so, display the
    // results by setting the HTML content of each <span> element.
    if (isFinite(totalbmi)) {
        bmi.innerHTML = totalbmi.toFixed(2);        
        if (totalbmi<18.5) weightclass.innerHTML = "Underweight, eat some food!";
        if (totalbmi>=18.5 && totalbmi<24.9) weightclass.innerHTML = "Normal, looking hot!!";
        if (totalbmi>=24.9 && totalbmi<29.9) weightclass.innerHTML = "Overweight, tighten it up!";
        if (totalbmi>=30) weightclass.innerHTML = "FAT, hit the GYM!!";
    }
    // Otherwise, the user's input was probably invalid, so display nothing.
    else {
        bmi.innerHTML = "nada";
        weightclass.innerHTML = "nada";
    }
}
</script>
</body>
</html>

Back to Top


Array Sum Calculator
I wondered how to read variables in from the user and remembered that you can use a prompt function for testing purposes.
However,we should realise that this is not very user-friendly and should be used for testing purposes.

Source Code:

<html>
<head>
<script type="text/javascript">
function flexisum(a){
    var total=0;
    for(var i = 0; i < arguments.length; i++) 
    {
        var element = arguments[i];
        if (!element) continue;  // Ignore null and undefined arguments
        // Try to convert the argument to a number n, based on its type
        var n;
        switch(typeof element) {
        case "number":
            alert("You entered a number,GREAT! no conversion needed");
            n = element;                  // No conversion needed here
            break;
        case "object":
            if (element instanceof Array) // Recurse for arrays
            n = flexisum.apply(this, element);
            else n = element.valueOf();   // valueOf method for other objects
            break;
        case "function":
            n = element();
            alert("You entered a function, Trying to invoke functions");
            break;
        case "string":
            n = parseFloat(element);
            alert("You entered a string, Trying to parse strings");
            break;
        case "boolean":
            n = NaN;
            alert(" You entered boolean, Can't convert boolean values");
            break;
        }
 
        // If we got a valid number, add it to the total.
        if (typeof n == "number" && !isNaN(n)) total += n;
        // Otherwise report an error
        else throw new Error("sum(): can't convert " + element + " to number");
    }
    alert("This is the sum of all the elements you entered"+ total);
    return total;
}
</script>
</head>
<body>
<script>
var sum  = new Array();
sum[1]=prompt("Enter number 1:","");
sum[2]=prompt("Enter number 2:","");
sum[3]=prompt("Enter number 3:","");
sum[4]=prompt("Enter number 4:","");
sum[5]=prompt("Enter number 5:","");
//We could have done some more checking to ensure that only int's are entered but that's not our focus
alert("Calling flexisum(sum), this function adds up all the elements in the array which you have created above");
flexisum(sum);
</script>
</body>
</html>

Back to Top


Nested Functions as Closures

I am still a little confused about closures, but this is a good example to show how javascript scoping works, I would get the source code and try to follow to see how the functions move from one to the next and which variables (x) are in scope at any given time. It explains a lot by seeing it in action.

Source Code:

<html>
<head>
<script type="text/javascript">
var x = "global";
alert("global is:" + x)
function f() {
    var x = "local";
    function g() { alert("local is: "+x); }
    alert("calling g()");
    g();
}
alert("calling f()");
f();  // Calling this function displays "local"
</script>
</head>
<body>
</br>
</body>
</html>

Back to Top



Closures II

This further explains how nested functions work in js and also the this keyword.
In the code, the object has variables a and f (function) within it's scope. When f: refers to a++ with its "this" keyword, a is accessible and defined because f is within the general scope of object which has a variable "a" to refer to. Therefore, the first two alerts on f() should return 0 and 1.
However, if define a var g that is a call to object.f, then the this.a++ now refers to the global scope and not a:0. Therefore, the alert on g() will return NaN since there is no global variable "a" defined at that point.

The proceeding code further validates the explanation above by doing the "else" case of the scenario i.e. in var h, global and local.
Those four alerts with h.call show —->

EDIT this part, Clarify

Source Code:

<html>
<script>
 
var object = {
  a: 0,
  f: function() { return this.a++;}
};
 
var g = object.f;
 
alert(object.f());
alert(object.f());
alert(g());
 
var a = 100;
 
alert(g());
alert(g());
 
var h = function() { return this.a--; }
 
alert(h.call(object));
alert(h.call(object));
alert(h.call(null));
alert(h.call(null));
 
</script>
</html>

Back to Top

These links are great resources that show all the properties and methods that can be applied to strings, dates, arrays etc in javascript broken down by browser type.
Methods and Properties


Nested Methods and Properties on Strings


Nested Methods and Properties on Dates

Back to Top


this is a random but useful text I got from the book "JavaScript: The Definitive Guide, by David Flanagan. Copyright 2006 O'Reilly Media, Inc., 978-0-596-10199-2." For even simpler experiments with JavaScript, you can sometimes use the javascript: URL pseudoprotocol to evaluate a JavaScript expression and return the result. A JavaScript URL consists of the javascript: protocol specifier followed by arbitrary JavaScript code (with statements separated from one another by semicolons). When the browser loads such a URL, it executes the JavaScript code. The value of the last expression in the URL is converted to a string, and this string is displayed by the web browser as its new document. For example, you might type the following JavaScript URLs into the Location field of your web browser to test your understanding of some of JavaScript's operators and statements: javascript:5%2 javascript:x = 3; (x > 5)? "x is less": "x is greater" javascript:d = new Date(); typeof d; javascript:for(i=0,j=1,k=0,fib=1; i>5; i++,fib=j+k,k=j,j=fib) alert(fib); javascript:s=""; for(i in navigator) s+=i+":"+navigator[i]+"\n"; alert(s);

Back to Top

page_revision: 47, last_edited: 1188321949|%e %b %Y, %H:%M %Z (%O ago)
Unless stated otherwise Content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License