Affiliated Business
Home Building Hosting Promotion Make Money Advanced Tools Homebusiness Resources
Web Programming | CGI & JavaScript | Homebusiness Tools | Payment Processing | Articles On Web Programming   Bookmark |  Tell A Friend  
ONLINE BUSINESS RESOURCES
  Affiliated Buisness Blog
  Affiliate Program      Directory
  Affiliate Marketing      Web2.0 Directory
  e-Commerce Software
  Google AdSence
  Graphic Editors
  InfoProduct MallInfoProduct Mall
  Internet Marketing
  Merchant Account
  Newsletter & e-Zine
  Offshore Incorporation
  Online Site Builder
  Online Store Builder
  Payment Processing
  Search Engines
  Site Templates
  Success Stories
  Web Programming
  Web Directories
  Web Design
  Web Design Software
  Web Marketing Guides &     Tools
  Web Promotion     Strategies
  Webmaster Tools
AFFILIATED BUSINESS TOOLS
Site Build It!

SATELLITE TV for PC
SATELLITE TV for PC

2007 TITANIUM EDITION Get over 4000 Stations for a small one-time fee!



JavaScript

Basics of JavaScript for a Webmaster

RELATED THEMES

JavaScript is fun.

Here is what this part of the tutorial covers:


Orientation
How the browser knows it is JavaScript
This is how JavaScript works
Some programming basics


~~ Orientation

Let's clear up any confusion there may be between JavaScript and Java:

Although they have similar names, they are very different. Java is a compiled language with modules that load into your browser from a source external to the web page. JavaScript, on the other hand, is an interpreted language and is almost always an integral part of the web page source code.

"Compiled language" means the source code of the program is translated (compiled) into machine-language (composed only of 0's and 1's) before use. When it is time to run the program, the translated version is used by the computer instead of the original source code. Unless you are the programmer, you might never see the source code of the program you are using.

"Interpreted language" means when it loads a page, the browser's interpreter uses the original source code and translates it into machine language. The translation is stored in the browser's memory ready to run all or portions of it as appropriate. When the browser window gets ready to load a different web page, the previous page's translated JavaScript is discarded.

JavaScript can be easier to learn than some other languages because there is a great abundance of examples on the internet. Just use your browser's "view source" menu choice and you can see the source code of web pages.

Note: Some browsers will display only the active source code when you "view source". In other words, you see only the source code that is actually being used to display the page at the time you are viewing it.
If you suspect your browser is "censoring" parts of the source code on a particular page, you can use Master Snooper. Master Snooper shows you all of the code in its glory or lack thereof. Just go to http://willmaster.com/master/snooper/MasterSnooper.cgi and type in the URL of the web page. (Master Snooper is also good to see how framed, doorway, and redirection pages are built, because it shows you only the source code rather than drawing the display or getting itself redirected.)


JavaScript can be quick to develop because you can make a change and test it immediately. To set it up, load the source code file into both your word processor and your browser. When you can change something, save the file and click your browser's "reload/refresh" button for immediate feedback.

Be sure to use a plain text word processor. NotePad.exe and BBEdit are both good. I use Arachnophilia (CareWare [no monetary requirements] -- Windows) for almost all of my HTML and JavaScript development.

~~ How the browser knows it is JavaScript:

JavaScript program lines must be between <script...> </script> tags unless the line is within an HTML tag. The JavaScript between the <script...> </script> tags must also be enclosed with HTML comment tags.

Often, you'll find JavaScript in this format:


<script language="JavaScript">
<!-- programmer comments can go here
JavaScript program code goes here
// programmer comments can go here -->
</script>

The language="JavaScript" part is not specifically required. However it is good to get in the habit of typing it in because there are other script languages out there, Active X for example, and the language designation tells the browser which scripting language is being used.

Without the <!-- and --> HTML comment begin/end tags, the browser tries to display the JavaScript as regular text -- this last statement may not be true for the very latest browsers, but it is true for most recent browsers and it certainly is true for browsers that are not JavaScript enabled.

The second line contains the HTML comment begin tag. The JavaScript interpreter ignores the entire line so long as it begins with that tag. Some people put a copyright notice or other comments on the rest of that line.

Notice the characters


//

on the second from last line. Two slashes next to each other tell the browser's JavaScript interpreter that the rest of the line is not valid JavaScript code -- it is ignored the same as all programmer comments are ignored by the interpreter. The rest of the line contains, of course, the HTML end comment tag. (You can use the space between // and --> for comments of your own -- the JavaScript interpreter will ignore it, and it is still inside the HTML comment tag so the HTML interpreter will ignore it, too.)

You can put your comments anywhere in a JavaScript program so long as they begin with the characters: //

There is no "end" comment code for JavaScript. All JavaScript comments that begin with // end automatically at the end of that same line.

Sometimes, you'll find JavaScript within HTML tags:

For mouseovers and some other functionality, you will find JavaScript code within the anchor tag. Example:


<a href="somedomain.com"
onMouseover="do_some_function()"
onMouseout="do_different_function()">
<img ...>
</a>

JavaScript code is also found within other HTML tags. Two of the most used are the <body...> and <input...> tags.

An example of JavaScript code in a <body...> tag:


<body onLoad="do_some_function()">

An example of JavaScript code in an <input...> tag:


<input type="submit" onClick="do_some_function()">

The reason non-JavaScript enabled browsers don't get confused when they find JavaScript in HTML tags is because they are programmed to ignore anything in tags that they do not recognize.

~~ This is how JavaScript works:

When someone visits a web page, it loads into the browser. The HTML is converted into a visible display.

If the browser is JavaScript enabled then the JavaScript program lines are interpreted and executed. If the JavaScript directs any visible effects, those effects become visible in the page display.

Although all of thee JavaScript code is interpreted during loading not all of it will be executed right away.

JavaScript program lines within HTML tags are executed only when the link or form element is activated, such as the mouseover link example above. And functions are executed only when a program lines calls them.

~~ Some programming basics:

Where to put JavaScript program code:

The JavaScript program lines above the <body...> tag are interpreted and appropriate lines executed before the HTML page is loaded. The JavaScript below the <body...> tag is interpreted and appropriate lines executed at the same time as the HTML page.

JavaScript program code that must be put above the <body...> tag are


any that must execute before the entire page has finished loading, such as code that immediately determines what kind of browser the visitor is using, and

functions (we'll describe what they are and other stuff about them in a later part of this series) that are called within the <body...> tag.
JavaScript program code that must be put below the <body...> tag are any that adjust the page's visual elements, such as printing text or displaying graphics.

Oftentimes, it won't matter whether the program code is above or below the <body...> tag. Many programmers, this author included, usually opt for the "above" position. It helps keep all or most of the program code in one place rather than scattered about.

How to make your program remember things:

You can specify stuff that the JavaScript program must remember. And you can access that remembered stuff later on.

In order to store stuff in memory and access it later, that memory spot must have a name. The memory spot, itself, is called a "variable" because the contents of the memory spot can change.

To declare that a variable exists and give it a name, you type something like


var blahblah;

which creates a variable called "blahblah" where you can store stuff.

To store something into that memory spot, you type something like


blahblah = 5;

and the number "5" is stored in (assigned to) that memory spot.

You can also do all the above in one line, if you want, by typing


var blahblah = 5;

However, once a variable name has been declared, don't declare it again. If, later on in the program, you want to change the contents of the variable "blahblah", do it as a simple assignment statement, like


blahblah = 4;

To access what you have stored in a variable (the value you assigned to it), you either have to print it (have it show up on your web page) or assign it to another variable. To print it to your web page, you type


document.write(blahblah);

and, when interpreted and executed, that program line will print the value of "blahblah" on your web page.

Here it is, all put together:


<script language="JavaScript">
<!--
var blahblah = 5;
document.write(blahblah);
// -->
</script>

Put the above JavaScript code somewhere below the <body...> tag of a web page and you'll see how it prints the value of "blahblah". (You put it below the <body...> tag because it actually writes something to the page -- and some browsers protest if you try to write something to the page above the <body...> tag.)

The above demonstrates a simple use of a variable. Other uses (described in a later part of this series) include doing mathematical calculations, manipulating strings of characters, storing form field contents, and having your program make decisions based on what a variable contains.

Using strings of characters:

Strings of characters need to be enclosed between either apostrophes (') or quote marks (").

Whichever character you choose, it must be used both at the beginning and at the end of the string.

If you have one or more apostrophes within your string, it makes good sense to choose quote marks to contain the string. Example:


"I'm hot."

On the other hand, if you have one or more quote marks within your string, it makes sense to enclose it within apostrophes, like this:


'He said, "hot".'

A special situation arises when you have a string with both an apostrophe and a quote mark within it. In that case, you put a backslash character in front of each occurrence of the character that encloses the string. For example, the string of characters


He said, "I'm hot."

can be enclosed within apostrophes as


'He said, "I\'m hot."'

or within quote marks as


"He said, \"I'm hot.\""

The backslash tells the browser's interpreter to treat the character following the backslash as a literal character rather than an "end of string" marker. Once the interpreter has done that, it discards the backslash from the string.

(If you want to use a backslash in a string, you must use two of them in sequence -- the browser will discard the first one.)

Try this JavaScript program code in a web page to see it work:


<script language="JavaScript">
<!--
var hotstuff = 'He said, "I\'m hot."';
document.write(hotstuff);
// -->
</script>

~~ To come:

This article has reached its length limit.

The part in this series will describe useful things to do with variables and will also describe functions and how to call them.

Function Basics

by William Bontrager

Unlike many programming languages, JavaScript can be written in bits and pieces. It may be interspersed with HTML code on a web page so long as the JavaScript conforms to its own programming language rules.

Understanding and using JavaScript programming language rules is the purpose of this article series.

Here is what this part of the tutorial covers:


Using/Calling functions
How to make your own functions


A JavaScript function is a block of code (one or more lines of JavaScript code together in a set) with a name.

The JavaScript language includes many functions, called built-in functions. You can also make your own functions.

"Netscape JavaScript Reference" and "Netscape - Client-Side JavaScript Guide" contain lists of built-in functions. The references are linked from http://search.netscape.com/Computers/Programming/Languages/JavaScript/References

The examples in this article make extensive use of the built-in function alert()

~~ Using/Calling functions

When you call a function, the browser runs the lines of code in the function. Whether the function is built-in or one you made, call it in your program by typing the function's name.

A function name always includes a pair of parenthesis at the end. There might or might not be something between the parenthesis.

If you want to send data to a function when you call it, put the data between the parenthesis. For example,


alert("Hello everybody!")

is a function call that displays an alert box proclaiming: Hello everybody!

If there is more than one unit of data to send to the function, separate them with commas. (A unit of data can be either a number or a string of characters, the latter being enclosed between single or double quotes and being called a "string" in most programming languages with which I am familiar.)

If you send more data units than the function will use, the excess is ignored. The alert() function expects only one data unit. So sending more than one, such as


alert("Hello everybody!","extra")

will cause only the first unit to be displayed in an alert box: Hello everybody!

On the other hand, if the units of data you send to a function numbers less than the function expects, the function will assume the rest is undefined. Trying to do calculations with something undefined usually produces an error message. Printing something that is undefined will usually produce the word "undefined". For example,


alert();

will display an alert box with: undefined

To find out how many units of data a built-in function expects to receive, you can consult documentation or emulate how someone else used it. The first method is more certain to be correct while the latter may be faster with sufficient certainty for the job at hand.

Links to JavaScript reference manuals and sites (link no longer works)

~~ How to make your own functions

Here is a function template:


function blahblah() {
alert("This is function blahblah() speaking!");
}

The first line of functions you create must contain the word "function", a space, and then the name you assign to your function. The open curly brace character can follow on the same line or be placed on the line following.

Below the open curly brace is the function body, those lines of program code that will be run when the function is called. Immediately below the function body is a close curly brace.

In the above example, the function name is: blahblah()

The function body between the open and close curly braces in the example is composed of one line which calls a built-in function. So when you call blahblah() an alert box appears with: This is function blahblah() speaking!

You can call your function blahblah() from an HTML anchor link such as


<a href="javascript:blahblah()">click here</a>

(Notice how the browser is told it is a link to a JavaScript function rather than to a regular URL.)

Or, you can call your function with a form button such as


<form>
<input type="button" value="Click!" onClick="blahblah()">
</form>

(Because the word "onClick" is JavaScript code, the browser knows blahblah() is a JavaScript function -- and when it doesn't find a built-in function by that name it looks for one you created.)

Your functions can call built-in functions and they can call functions you make. Example:


function example() {
alert('Here!');
blahblah();
alert('Back to you...');
}

When you call the example() function, it first displays an alert box with: Here!

then it calls your blahblah() function which displays an alert box with: This is function blahblah() speaking!

and after that, it displays an alert box with: Back to you...

The ability to call other functions from within functions that you create is highly advantageous.

Consider that your program might have a dozen or so functions, most of which require a specific action as part of their larger purpose. Let's say that action is calculating the number of milliseconds that have elapsed since the visitor arrived at your page.

So you make a function to do the calculation, called elapsedmilliseconds(). Now, instead of writing the code to do the calculation in each of your other dozen functions, you just call the elapsedmilliseconds() function where appropriate.

Here is what a set of code might look like:


<script name="JavaScript">
<!--
var Now = new Date(); // Grab the current date.
var Start = Now.getTime(); // Initialize variable Start
// with the # of milliseconds
// elapsed since 1Jan70.
// (Netscape chose 1Jan70 as
// a standard date from which
// to do JavaScript time
// calculations.)
//
// See "Useful stuff to do
// with variables," in a
// section of this article,
// below, for an explanation
// of how the "Now" and
// "Start" variables are
// assigned their values.

function elapsedmilliseconds()// Calculates elapsed time
{
var n = new Date(); // Grab new copy of date
var s = n.getTime(); // Grab current millisecond #
var diff = s - Start; // Calculate the difference.
return diff; // Return the difference.
}

function decider()
{
var d = elapsedmilliseconds();
if(d < 600000) { alert("Elapsed milliseconds: " + d); }
else { window.location = "http://willmaster.com/"; }
}
// -->
</script>

<form>
<input type="button" value="Check Elapsed Milliseconds"
onClick="decider()">
</form>

When the page first loads, it assigns the current (this moment) date/time value to the variable Now. Then it uses that value to determine the current millisecond number with which to initialize the variable Start.

When you click the "Check Elapsed Milliseconds" on your page, it calls your decider() function. decider() calls the function elapsedmilliseconds() to determine the number of milliseconds that have elapsed since the page was first loaded -- when the variable Start was initialized.

When elapsedmilliseconds() is called, it determines the difference between it's own calculation and the value stored in the variable Start. It stores the result in variable diff.

Then elapsedmilliseconds() returns the value of the variable diff, which is what decider() assigns to its own variable d.

Last, decider() decides whether or not the page has been displayed a total of less than 10 minutes (600,000 milliseconds). If true, it displays an alert box with the value stored in d. Otherwise, it sends the visitor off to http://willmaster.com/

Hopefully, this has given you a glimmer of what is possible. Not only can you call your elapsedmilliseconds() function whenever you want, but other functions can call it, too, and make decisions based on what it returns.

Further elaboration and uses for program decision and flow control statements such as if(), for(), and while() will be in another section of this tutorial series.

(By the way, it took me 243740 milliseconds to write the above seven paragraphs while eating three small handfuls of popcorn.)

Let's suppose you want to modify your decider() function so you can tell it how many seconds to wait before sending the visitor off somewhere. And let's suppose you also want to tell it the location of that somewhere.

So you will modify your decider() function to accept a number (for the number of seconds) and a string of characters (for the URL). It will also be modified to use those data units where appropriate.

Here is the modified decider() function:


function decider(s,url)
{
var d = elapsedmilliseconds();
s = s * 1000; // s multiplies itself by 1000
if(d < s) { alert("Elapsed milliseconds: " + d); }
else { window.location = url; }
}

The decider() function receives two units of data when it is called, the number of seconds and the url, and stores them in variables s and url, respectively.

The variable "d" is then compared with "s" to see whether the alert box is displayed or the visitor is redirected to the value in "url".

You can call your modified decider() function with


<form>
<input type="button" value="Check (90 seconds)"
onClick="decider(90,'http://mydomain.com/')">
<input type="button" value="Check (45 seconds)"
onClick="decider(45,'http://mydomain.com/')">
</form>

or with


<a href="javascript:decider(90,'http://mydomain.com/')">
(90 seconds)</a>
<a href="javascript:decider(45,'http://mydomain.com/')">
(45 seconds)</a>

The above will send your function either the number 90 or the number 45 (for the number of seconds) and the string of characters http://mydomain.com (for the URL).

In a later article of this series, you will learn how to type stuff into a form (such as the number of seconds and the url, for the above example) and send that data to the function -- rather than hard-coding the data into a link.

And, you will often want to display function results in ways other than plain alert boxes.

Future articles will help you build popup boxes with your own design, on demand. They will help you display text and graphics on your page depending on which browser your visitor is using, depending on a name typed into a form, or other decisions your custom functions make.

Much of what you do with JavaScript depends on your program making decisions based on the contents of variables:


if([something]) then do this, else do that.

while([something]) do this.

for([each of a series]) do this.


The next article deals with those and other methods of program flow control.

Copyright 2000 by William and Mari Bontrager

William Bontrager
"WillMaster Possibilities"
http://willmaster.com/possibilities/
subscribe-possibilities@willmaster.com

 

AddThis Social Bookmark Button

 
INTERNET MARKETING TOOLS
1MerchantCart - eCommerce Automation
1MerchantCart - eCommerce Automation

The All-in-One Merchant Shopping Cart and Affiliate Processing Software


Day Job Killer
Day Job Killer

Learn ruthless tactics from the new $1M affiliate
See it here...

Be quick! Grab it before the price goes up...


Build A Niche Store
Build A Niche Store

Everything is already in place for you to start making money by building your own affiliate stores that connect people to eBay's products.
Build A Niche eBay Store


Get Google Ads Free
Get Google Ads Free

"Internet Marketer Gets $87 Million in Google Pay-Per-Click Ads FREE! ... And Makes Over $314 Million as a Result! ... And Now He's Going to Give You This Same Secret for Next to Nothing!"



Web site Top Affiliated-Business.com: The art of making money online... Web site Top
Home | Building | Hosting | Promotion | Make Money | Tools | Homebusiness | Resources | Tell A Friend | Add To Favorities | Link To Us | Partner With Us | Site Map |
About Affiliated-Business.com  |  Privacy Policy  |  Disclaimer  |  Copyright  |  Terms of Service  |  Collection Of Links  |
©2004-2007 Affiliated-Business.com® - All rights reserved.