JavaScript - Basics & Introductory Concepts

Good JavaScript Tutorial Website:
http://www.netkontoret.dk/javascript.htm

TAGS | SCRIPT COMPARISON | BASICS | OPERATORS & EXPRESSIONS | FUNCTIONS | OBJECTS & METHODS |
EVENTS | FORMS | FRAMES | ARRAYS | CODE SAMPLES

bullet

Developed from a joint venture between Sun & Netscape

bullet

JavaScript is an open language - no license is required

bullet

Simpler than Java -

bullet

no applets;

bullet

no standalone programs

bullet

JavaScript statements are interpreted, 1-line-at-a-time, by a JavaScript interpreter that is embedded within a browser

TAGS

<SCRIPT LANGUAGE="JAVASCRIPT">
<!--- DISABLE FOR OLD BROWSERS
JavaScript code goes here
//-->
</SCRIPT>

SCRIPT COMPARISON

bullet

JavaScript is like C++

bullet

uses { }

bullet

functions

bullet

VBScript is like Visual Basic

bullet

uses sub and end sub

bullet

standard subroutines

BASICS

bulletVariables:  first char must equal a-z, A-Z, or underscore ( _ )
bulletNo explicit data typing on variable declarations:

var width = 3
var browserType = "Netscape"

bulletUse \x to include special character x in a string:
\" \' \\ \t \r \b \f \n
" ' \ tab return backspace form feed newline


OPERATORS & EXPRESSIONS

bulletArithmetic Operators:  +, -, *, /, % (mod), ++ (increment), -- (decrement)

average = totalValue / Count

bulletConcatenation Operator:  +

var Msg1 = "cat"
var Msg2 = "dog"
var Msg3 = Msg1 + Msg2  //catdog

bulletConditionals:  ==, !=, >, >=, <, <=, &&, ||
bulletif  statements:
var tDate = new Date()
var numHours = tDate.getHours()
if (numHours > 12) {
    document.write("Good Afternoon")
}
else {
    document.write("Good Morning")
}

 

bulletwhile statement:
while (condition) {
//put your statements here
}


FUNCTIONS

// within the calling portion of your code:
messageStr = "customized string"

// define the function between the <HEAD> and </HEAD> statements ...

function Greetings(messageStr) {
  alert ( messageStr)
}


OBJECTS & METHODS & DOCUMENT.WRITE

bulletMany objects are part of JavaScript
bulletObjects have both properties and methods - USE THEM
bulletExample using DOCUMENT.WRITE (the way to write messages to the screen) - Note, you can mix standard HTML tags within the string you're trying to write to the screen for additional format control:
document.write("<CENTER><B>Read This!</B></CENTER>")

EVENTS

This is NOT a complete set of possible events to trap ... but it should be enough to get you going!

onfocus insertion point moved to this object onreset RESET button clicked
onblur insertion point moves off object ondragdrop when an object is dragged then dropped
onselect highlighting of text onkeydown key going down
onchange change value & move off onkeypress key kept down
onclick any button clicked onkeyup key going up
onmouseover mouse is moved over something onmousedown mouse button pressed
onmouseout mouse is moved off onmousemove mouse being moved
onload when page is loaded onmouseup mouse button released
onunload when leaving a page onmove window/frame is moved
onabort stop button clicked to interrupt a page load onresize widown/frame size changed
onerror script problem


FORMS

The following places a button reading "White" on the screen, and when this button is clicked, the background color of the entire screen will turn white.

<INPUT TYPE = "Button"
             VALUE = "White"
             ONCLICK = document.bgColor = "White" >

 


FRAMES

The following code will split the screen into 2 columns; the first to hold a table of contents webpage, will occupy the leftmost 25% of the screen, and the second will hold the actual contents of a webpage referenced, and will occupy the rightmost75% of the screen.

<FRAMESET COLS="25%,75%">
<FRAME SRC="TOC.HTM">
<FRAME SRC="MAINPAGE.HTM>
</FRAMESET>


ARRAYS

var currMonth = new Array(13)
// 13 array elements allocated indexed 0 thru 12
currMonth[1] = "Jan"
currMonth[2] = "Feb"
   ...
currMonth[12] = "Dec"

CODE SAMPLES

Example 1 - Time Sensitive Message -
This page will display a company graphic and customized horizontal line, and will issue an appropriate greeting to website visitors based on the time of day that they're visiting.   Click HERE to see it run.

<html>

<head>

<title>SHOWING OFF COMPLEX IF STATEMENTS</title>

</head>

<body>

<p align="center"><img src="CarbonCopy.jpg" width="294" height="121"></p>

<p align="center"><img src="wavygraybar.jpg" width="756" height="16"></p>

<p align="center">Welcome to Carbon Copy Printers. We are open 24 hours a day. No job is

too big or too small.</p>

<script language="JavaScript">

<!--- Hide from old browsers

today = new Date()

if ((today.getHours()>=4) && (today.getHours()<=12)){

    document.write("Good Morning Have a rush job for the afternoon? We can handle it")

    }

if ((today.getHours() > 12) && (today.getHours() <=18)) {

    document.write("Good Afternoon! We can get your print job ready by tomorrow morning.")

    }

if ((today.getHours() > 18) && (today.getHours() <=23)) {

    document.write("Good Evening! We will be here all night if you need us!")

    }

if ((today.getHours() >=0) && (today.getHours() < 4)) {

    document.write("Yes, we\'re working this late!")

    }

// -->

</script>

Example 2 - Web Page has moved -
This sample illustrates several different concepts - Click HERE to see it run

bullet

we define a function ( chngSite() ) used to change the location (URL) of the page that the browser displays

bullet

as the page is first loaded, the background color is rapidly changed so as to get the attention of the viewer using document.bgColor

bullet

a Date object is allocated (tNow), it's value is converted to a long string ( tlocDate = tNow.toLocaleString() ), and then the substring function is used to extract MM/DD/YYYY 

bulletWe generate a welcome message that contains the date, as well as a message containing embedded HTML tags indicating that this web site has moved, and that we will be automatically moved there in 15 seconds
bulletWe use the document.lastModified method to generate a message indicating the time when this page was last changed
bulletFinally, we use the setTimeout JavaScript method to set up calling the function we wrote ( chngSite() ) in 15 seconds

<html>

<head>

<title>Fun with Phonics</title>

<script language="javascript">

<!--Hide from old browsers

function chngSite(){

alert("Taking off to the new location ...")

location="http://domanski.cs.csi.cuny.edu"

}

//-->

</script>

</head>

<body>

<p align="center"><img SRC="fun.jpg" HSPACE="5" VSPACE="5" HEIGHT="64" WIDTH="129"> </p>

<hr Width="75%" align="center">

<script language="javascript">

<!-- Hide from old browsers

document.bgColor="red"

document.bgColor="white"

document.bgColor="blue"

document.bgColor="white"

document.bgColor="green"

document.bgColor="white"

document.bgColor="black"

document.bgColor="white"

document.bgColor="blanchedalmond"

var tNow = new Date()

var tlocDate = tNow.toLocaleString()

var tDate = tlocDate.substring(0,10)

document.write("<H2><CENTER>Welcome, today is "+tDate+"</CENTER></H2>")

var intro1 = "Hi. Our web site has moved. Click "

var intro2 = "<A HREF='http://domanski.cs.csi.cuny.edu'> here </A> or"

var intro3 = " wait 15 seconds to be moved automatically"

var intromsg = intro1 + intro2 + intro3

document.write("<H4><FONT Color='firebrick'>"+intromsg+"</H4></FONT>")

document.write("<CENTER><H4>This page was last modified on "+document.lastModified+"</CENTER><H4>")

setTimeout("chngSite()",15000);

//-->

</script>

</body>

</html>


Designed and written by DrB.  Last modified on  Wednesday, February 18, 2009