Javascript: Introduction to Javascript



Author: Ronald S. Holland
at
Total Application Works



<

To contact us



HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript ]

© 2002 - 2014 All Rights Reserved Total Application Works


  • Tell a friend about this site (copy and paste the following HTML page into a file (e.g., using Notepad).)
  • <html>
    <head>
    <title>Example of a link </title>
    </head>
    <body>
    <a href="http://sumtotalz.com/TotalAppsWorks/Javascript/JS_Intro.html">
    Introduction </a>
    </table>
    </body>
    </html>

JavaScript Date Object

Introduction

The purpose of this tutorial is to introduce and explore JavaScript. This tutorial assumes that you have some prior programming experience. It is not intended to be a comprehensive discussion on Javascript or programming. In the next section, we will briefly describe Javascript basics.

What is Javascript?

Javascript is a scripting language developed by Netscape that enables Web designers to create interactive sites/web pages. Javascript and Java have many features and structures in common, however, they were developed independently. When Javascript is embedded within HTML source code, it enables Web designers to spice up their sites with dynamic content. JavaScript is used in Web pages by designers to:

  • Improve the Web page dynamic content design;
  • Add interactivity to HTML pages;
  • Validate forms and gather data from users;
  • Detect browsers;
  • Create cookies;
  • Etc.
JavaScript is a scripting/interpreted language, which can execute without having to compile the source code. Java and JavaScript are similar but are not the same. They are two completely different languages in both concept and design. JavaScript runs on the client's computer and does not require constant downloads from your web site.

What can you do with JavaScript?

  • As an interpretive language, JavaScript allows HTML designers the ability to add logic/functionality to their HTML/Web pages.
  • JavaScript can write dynamic/variable text into an HTML page. Consider the following statement var aText = "This is any text". The variable aText can contain just about any random value, subject to change pending user stimulus and then written into an HTML page.
  • The table below contains some HTML attributes that can cause Javascript to respond to the event they cause.

    TAG
              Description of Attributes    
         INPUT     
    onBlur: script to call when this field loses the focus
    onChange: script to call when this field is changed
    onClick: script to call when the user clicks here
    ondblclick: script to be run on a mouse double-click
    onFocus: script to call when this field gets the focus
    onKeyDown: script to run when a key goes down while the field has the focus
    onKeyPress: script to run when a key is pressed
    onKeyUp: script to run when a key goes up while the field has the focus
    onmousedown: script to run when mouse button is pressed
    onmousemove: script to run when mouse pointer moves
    onmouseout:Script to run when mouse pointer moves out of an element
    onmouseover: Script to run when mouse pointer moves over an element
    onmouseup: Script to run when mouse button is released
    onreset: Script to run when the form is reset
    onselect: Script to run when the element is selected
    onsubmit: Script to run when the form is submitted
    onunload: Script to run when a document unloads
    Below is an example using the Input tag.
     
    <INPUT TYPE="BUTTON"  NAME="bCalc"
                    OnClick="Circle_calc(this.form);" 
                    VALUE="calculate"> 
    
     
     
    
    Below is an example using the Body tag.

    <body onload="setCalc()" bgcolor="#ffffff">
    Script to be run when a document loads

    The body element defines the document's body. The body element contains all the contents of an HTML document, such as text, hyperlinks, images, tables, lists, etc.
    Figure 1: Attributes that cause Events


    Figure 1 shows how JavaScript can be set to execute when an event occurs. This can be triggered when a page has finished loading or when a user clicks on an HTML element e.g., a button.
  • JavaScript can read and write to a HTML document - For example, JavaScript can read and change the content of an HTML page. Consider the following example.

    <script>
    document.writeln( "<h3>This is a demonstration</h3>");
    document.writeln("<p>This is an example of how write text
    to a web page.</p>");
    </script>
    Figure 2: Writing to a HTML Web Page


  • JavaScript can be used to validate data - Consider a page that contains ten fields and the user enters the wrong type of data in each field. Suppose that when the data in a field is found to be invalid on the Server, processing is halted and an alert is sent back to the user. This alert informs the user that a particular field has invalid data entered and that the user should correct the error. Multiply this processing time by ten and you have a feel for the waste of server processing. Now consider validating all of fields at one time with JavaScript and then alerting the user of each field containing invalid data at one time. This saves the server from extra processing and the user in turn-around time.
  • JavaScript can be used to detect the visitor's browser by using the Navigator object. The JavaScript Navigator object contains all information about the visitor's browser. For example, it can
    1. Obtain additional details about the visitor's browser by using the following properties:
      • appName - Application Name
      • appVersion - Application Version
      • appCodeName - Application Code Name
      • platform - Platform on which application is running
      • cookieEnabled - cookie Enabled
      • userAgent - Browser's user agent header
    2. Obtain all details about the visitor's browser, by using the following properties:

How can we obtain all details about the visitor's browser?

We will use one of the Navigator properties to determine which browser the user is on. To accomplish this, we need to know the properties we can use with the Navigator object. Figure 3 below shows you the properties available with the Navigator object.

Navigator Properties

  • appCodeName - The name of the browser's code name e.g., "Mozilla".
  • appMinorVersion - The minor version number of user's browser.
  • appName - The name of the browser e.g., Microsoft Internet Explorer or Netscape Navigator.
  • appVersion - The browser version value which could include a compatability value and operating system name.
  • cookieEnabled - If cookies are enabled in the browser, a boolean value of true is returned, otherwise a value of false is returned.
  • cpuClass - Common Intel microprocessors (including Pentium-class CPUs and Macintoshes running Windows emulators) return x86.
  • mimeTypes - An array of MIME type descriptive strings that are supported by the browser.
  • onLine - A boolean value of true or false.
  • opsProfile
  • platform - A description of the operating system platform. In my case it is "Win32" for Windows 95.
  • plugins - An array of plug-ins supported by the browser and installed on the browser.
  • systemLanguage - The language being used such as "en-us".
  • userAgent - In my case it is "Mozilla/5.0 (compatible; Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0)" which describes the browser associated user agent header.
  • userLanguage - The languge the user is using such as "en-us".
  • userProfile
 
<script type="text/javascript">
document.write("CodeName = " + 
         navigator.appCodeName + "

"); </script>


Figure 3: Writing to a HTML Web Page


In the next section, we will show how to detect the visitor's browser and browser version.

How can we Detect the visitor's browser and browser version

In this section, we will use navigator.appVersion attribute to determine the user's browser's version.

 
<head>
<script LANGUAGE="JavaScript">
function isWindows() {
fWinVer2.tIsWin.value = ( navigator.appVersion.indexOf("Win") != -1) 
}

function isWin95NT() {
fWinVer2.tIsWinNT.value = ("Testing" + navigator.appVersion.indexOf("Win") != -1) 
}
</script>
</head>
<body>
<form NAME=fWinVer2>


<INPUT TYPE="BUTTON" NAME=bIsWin OnClick="isWindows();" VALUE="WIN?"> <INPUT TYPE="TEXT" NAME="tIsWin" SIZE="10" > </form> </body>




Figure 4: Writing to a HTML Web Page


In the above example, we used the following tags and properties.

  1. <head> - start of the header content of the HTML document.
  2. <script LANGUAGE="JavaScript"> - indicates the start of the JavaScript content.
  3. function isWindows() - function key word declares the start of the isWindows()
    • Note: - the function name, isWindows() must begin with a lower case letter
  4. function isWin95NT() - function key word declares the start of the isWin95NT()
  5. </script> - start of the interpreted script program.
  6. </head> - end of the header content of the HTML document.
  7. <body> - start of the body content of the HTML document. This is the content that is visible to the user.
  8. <form NAME=fWinVer> - indicates start of an input form.
  9. <INPUT TYPE="BUTTON" - an input element on a form of the type button
    • NAME=bIsWin - name of the input putton
    • OnClick="isWindows();" - indicates that a switch to the function isWindows() if this button is clicked.
    • VALUE="WIN?"> - is the text printed on the button
    • <INPUT TYPE="TEXT" NAME="tIsWin" SIZE="10" > - an input element on a form of the type text with a name/label of tIsWin.
  10. </form> - indicates end of an input form.
  11. </body> - end of the body content of the HTML document.
  12. Alert user, depending on browser - see next section.

Alert user, depending on browser

The script below displays a different alert, depending on the visitor's browser:

Example Code Demo: Example Code
 
<html>
<head>
<script type="text/javascript">
function goodBrowser() {
   var browser   = navigator.appName;
   var b_version = navigator.appVersion;
   var version   = parseFloat(b_version);
   if ((browser == "Netscape" || 
      browser == "Microsoft Internet Explorer")
      && ( version >= 4) ) {
         alert("Your browser " + browser + " is good enough!");
      }
   else {
       alert("It's time to upgrade your browser!" + " " + browser);
   }
}
}
</script>
</head>  

<body>
<form NAME=fWinVer>
<INPUT TYPE="BUTTON"  NAME=bIsBrow
                OnClick="goodBrowser();" 
                VALUE="GOOD BROWSER?"> 
</form>
</body>
</html>
 


Figure 5: Sending an Alert

Calling a Function

How do functions run? Executing the code in a Function is not automatic. When the web page loads, all of its functions are in the sleep-mode until they are called. This means an instruction must be sent to the function telling it to run. The most common methods to call a function are from:

  • An event handler (see next section), or
  • Another function.

Calling a Function From an Event Handler

What is an event? An event is anything that requests browser-attention. For example, an event occurs when the user presses a button. An event handler is a command that calls a function when an event happens, such as the user clicking a button. Consider the code in Figure 5 above. When the button is pressed, the browser you are using to view this tutorial caused the function goodBrowser() to be called. The button attribute used is OnClick. The command OnClick="goodBrowser();" tells the browser to go to the function goodBrowser() when clicked/pressed.

Calling a Function From Another Function

Functions can also call other functions. Simply enter the name of the function to be called, with its parentheses, like so:

Example Code Demo: Example Code
 
<html>
<head>
<script type="text/javascript">
function firstFunct() {
   alert("Entering first function. About to call second function.");

   secondFunct() ;
}
function secondFunct() {
   alert("Entering Second function. About to finish...");
}</script>
</head>  

<body>
<form NAME=fWinVer>
<INPUT TYPE="BUTTON"  NAME=bIsBrow
                OnClick="firstFunct();" 
                VALUE="Call Function"> 
</form>
</body>
</html>
 
Figure 6: Function called from another function


By adding the functions and the button, we have made the web page in Figure 6 interactive. The JavaScript code runs on user's client computer; therefore it does not require constant downloads from your web site.

What Runtime Environment is needed to run Javascript?

Is there a special runtime environment needed to run Javascript? The support to run Javascript is contained within most web browsers. If visitors to your site are running web browsers that support Javascript and have Javascript enabled then Javascript will execute the code in your web page.

Do I need to learn Javascript to be able to use it?

Do I need to learn Javascript to be able to use it? This is a yes and no answer. If you visit online sites like:

  • Sears
  • Advance Auto Parts - Replacement Parts, Accessories, Tools, Books, Etc.
  • Amazon - books, music, Electronics, etc.
  • half.com - books, music, movies, games, etc.
  • and others...
you will find that these sites have Javascript code embedded in them. Upon visiting these sites, you are using Javascript without being aware of their content. However, if you want to customize or create unique JavaScript code for your own web page, you either have to find code that fits your needs or you have to write the JavaScript code. If you have to write the JavaScript code, then it would be a good idea to know/learn JavaScript.

What do I need to write Javascript?

What do I need to write Javascript? The source code for Javascript can be written using any text editor, such as Notepad. As mentioned above, most web browsers have built-in runtime capability. Therefore, any plain text editor will suffice in writing Javascript.

Can I use HTML instead of Javascript?

Can I use HTML instead of Javascript? HTML and Javascript are two completely different types of languages that are used for different purposes. HTML is a layout/tag language that is used to organize text and/or images on a static web page content in a static format. Javascript is a programming language designed for performing dynamic tasks. Therefore, the answer to the question, "Can HTML be used instead of Javascript?" is no.

Can I use PHP or some other server side language instead of Javascript?

Can PHP or some other server side language instead of Javascript? Why would you consider using PHP?

  • PHP is designed to run on various platforms (Linux, Unix, Windows, etc.)
  • PHP is compatible with most of the servers used today (Apache, IIS, etc.)
  • PHP is free and can be downloaded from the official PHP site: www.php.net
  • If you have some programming experience, you will find that PHP is easy to learn and runs efficiently on the server side
  • PHP is a scripting language originally designed for producing dynamic web pages.
  • PHP is now officially known as "PHP: HyperText Preprocessor".
  • It is a server-side scripting language usually written in an HTML context.
  • Figure 7 is a depiction of a client/Server application.

     
      Tier 1        Tier 2         
    +--------+     +--------+     
    | Client |<--->| Server |
    +--------+     +--------+     
       GUI                
     
    Figure 7: Client/Server


Perhaps, it depends on where the code needs to run. If it can run before the page loads you can use a server side language. If it has to run after the page has loaded then you must use Javascript as this is the only scripting language supported by all web browsers that support client side scripting.

Does the Javascript go in the same file as the HTML?

It can but your scripts will be more easily reused on multiple pages of your site if you place them in separate files (using a .js extension helps identify them as Javascript). You then just link the Javascript to your HTML by inserting a <script> tag. The same Javascript can then be added to several pages just by adding the appropriate tag into each of the pages to set up the link.

Are Javascript and Java Interchangeable?

Are Javascript and Java Interchangeable? No, they are two completely different computer languages. Only their names are similar.

Javascript Reserved Words

The following table contains some Javascript Reserved Words.
abstract boolean byte break
case catch char class
const continue debugger default
delete do double else
enum export extends false
final finally float for
function goto if implements
import in instanceof int
interface label long native
new null package private
protected public return short
static super switch synchronized
this throw throws transient
true typeof try var
void volitile while with










HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript ]


To contact us

© 2002 - 2014 All Rights Reserved Total Application Works