Intro to JavaScript Jaime Ruiz. Short History of JavaScript Released in 1996 with Netscape 2...

47
Intro to JavaScript Jaime Ruiz
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    230
  • download

    0

Transcript of Intro to JavaScript Jaime Ruiz. Short History of JavaScript Released in 1996 with Netscape 2...

Intro to JavaScript

Jaime Ruiz

Short History of JavaScript Released in 1996 with Netscape 2 Originally called LiveScript MS releases Jscript with IE 3.0

Unreliable and buggy 1997 dHTML is born with Version 4.0

browsers. Web Programmers strike it rich.

Short History of JavaScript 1999 begin to see versions of W3C Dom

guidelines implemented in versions of JavaScript and Jscript

Netscape and Open Source Community drop old Netscape core to develop first browser to meet W3C DOM guidelines

Most new browsers now support W3C Dom

Common Uses of JavaScript Client Side

Image Rollovers (most common) Form Validation

http://www.papiowines.com/contactus.asp Dynamic Form Generation

http://www.robertmondavi.com/Wheretobuy/ DHTML

http://www.bart.gov

Browser Detection Server-Side

Microsoft ASP pages

Bad Uses of JavaScript

Just because you can doesn’t mean you should

Strengths and Weaknesses Strengths

Easy to learn Powerful? Close to being cross-platform

Weaknesses Promotes bad programming Makes websites less usable

Overview

What is DOM? Document Object Model (DOM)

“The Document Object Model is a platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents.” – from w3c.org

Why is it important?

Adding JavaScript to HTML Inline

<script language=“JavaScript”><!—Hides script from old browsers

Code goes here//<script>

External File<script language=“JavaScript” src=“file.js” ></script>

Variables and Data Types JavaScript is a loosely typed language

Data types are converted during execution as needed

Data typing only matters during operations

“6” + “67” = “667” String 6 + 67 = 73

Variables and Data Types Numbers

Integer and floating-point numbers. Booleans

True or false. Can not use as 1 or 0 but 0 = false; Strings

Anything surrounded by “” or ‘’ex. “My String” = ‘My String’

Object myObj = new Object();

Null Not the same as zero - no value at all.

Undefined The Variable has been created but no value has been

assigned to it

Scope Is the following code valid?

for(var i = 0; i < 10;i++){document.write(i);

}alert(i);

Scope Is the following code valid?

for(var i = 0; i < 10;i++){document.write(i);

}alert(i);

YES! Scopes only happens within functions

Scope var myInt = 0 //Global Var

function foo(){var i = 10; //local variablemyInt += i;

}document.write(i); //will cause error

Operators Arithmetic (the usual suspects)

+,-,*,/,%,--,++ Comparison

==, !=, >, >=, <, <= Boolean

&&, ||, !

Statements Conditionals

if(x < 0){alert(“x is negative”);

}else{alert(“x is positive”);

} switch(favoriteProf){

case “Yoon”: statements;

break; case “Lank”: statements; break; default: statement;}

Statements Loops

for(var i =0; i < myArray.length;i++){document.write(i);

} do

{ statements;} while (condition)

while(condition){statements;

}

Statements Object Manipulation

for …in (can be object or array)for(var prop in document){

document.write(prop + " = " + document[prop] +"<br />");}

Ouputnamespaces = [object]lastModified = 03/14/2005 18:45:05parentNode = nullnodeType = 9fileCreatedDate = 03/14/2005onbeforeeditfocus = nullbgColor = #ffffff …

Functions The function definition is a statement

which describes the function: its name, any values (known as "arguments") which it accepts incoming, and the statements of which the function is comprised.

function funcName(argument1,argument2,etc) { statements;

}

Functions Example:

function foo(myString){document.write(myString);

}

foo(“Computers are fun”);foo(); //will this work?

Functions When calling functions, JavaScript will

try to match the function with same number of arguments

Previous example would work but the argument myString would be undefined.

JavaScript Objects To declare an object

var myObj = new Object(); To set properties

myObj.name = “blah” Setting methods

myObj.foo = foo;

JavaScript Objects Prototype an object

function petDog(name,breed,year){this.name = name;this.breed = breed;this.year = year;

}var myDog = new petDog(“rusty”,”mutt”,1990);

Real Life Examples Swap Images

Steps Preload images On mouse over event swap the image On mouse out event restore the image

Real Life Examples Preload images

if(document.images){ menu1img = new Image();menu1img.src = '/images/nav1_stations.gif';

menu1imgOn = new Image();menu1imgOn.src = '/images/nav1_stations_on.gif';

} Swap Image function

function swapImage(imageName, newImage){if(document.images[imageName]){

document.images[imageName].src = newImage.src;

}}

The Html <a href=“#” onmouseover=“swapImage(menu1,menu1imgOn)”

onmouseout=“swapImage(menu1,menu1img)”><img src=“/images/nav1_sations.gif” id=“menu1” name=“menu1” alt=“” width=“130” height=“15” /></a>

Real Life Examples Things to watch out for

Make sure ID and Name are set correctly Each image must have a unique name/id Always make sure the image exists before

trying to swap

Real Life Examples Form Validation

Create function to run on form’s onSubmit event

<form name="myForm" id="myForm" action="#" method="get" onsubmit="return checkForm(this)">

<input type="text" name="firstName" id="firstName" value="" />

<input type="submit" />

</form>

Real Life Examples Form Validation

function checkForm(theForm){if(theForm["firstName"].value == ""){

alert("You must enter your first name");

theForm["firstName"].focus();return false;

}return true;

}

Real Life Examples Other ways to access a form

document.forms[0].elements[0]gets the first form and first element of the form

document.forms[“formName”].elements[“elementName”]

Real Life Examples Dynamically build a select box

The Form<form name="Choices" id="Choices" method="get" action="retailerresults.asp"

onsubmit="checkValid();"> <select name="BrandCode"

onchange="ChangeVarietal(window.document.Choices.BrandCode.options[selectedIndex].value);"><option value="">Select One</option><option value ="RC">Robert Mondavi Private Selection</option><option value ="OV">Robert Mondavi Winery</option><option value ="WB">Woodbridge</option>

</select><select name="VarietalCode" id="VarietalCode" size="1">

<option value="">First, Select a Winery------------------------</option><option value="">__________________________________________</option>

</select>

Real Life Examples Dynamically build a select box

The JavaScript (edited)function ChangeVarietal(labelcode){

var j = 0;if (!labelcode){

//code resets the select filed} else {

window.document.Choices.VarietalCode.options[0].text = "Select One";window.document.Choices.VarietalCode.options[0].value = "";j++;window.document.Choices.VarietalCode.length = 100;for (var i in bvArray[labelcode]){ window.document.Choices.VarietalCode.options[j].text = bvArray[labelcode]

[i].productdescription; window.document.Choices.VarietalCode.options[j].value = escape(bvArray[labelcode][i].productdescription);

j++; }}window.document.Choices.VarietalCode.length = j;

}

Real Life Examples Dynamic HTML - an integration of JavaScript,

Cascading Style Sheets, and the Document Object Model.

Most common type is drop down menus Created by accessing an html elements style sheet

and changing its visibility

Real Life Examples The HTML

<div id="navMapsSubDiv" ><img src="assets/images/glb_bullet.gif" width="8"

height="4" alt="" border="0" class="imageCenterAlign" id="l2maps1"/><a onmouseover="TurnOnLevel2(l2maps1)" onmouseout="TurnOffLevel2(l2maps1)" href="#">Trip planner</a><br />

<img src="assets/images/glb_bullet.gif" width="8" height="4" alt="" border="0" class="imageCenterAlign" id="l2maps2"/><a onmouseover="TurnOnLevel2(l2maps2)" onmouseout="TurnOffLevel2(l2maps2)" href="#">Find a stop/station</a><br />

<img src="assets/images/glb_bullet.gif" width="8" height="4" alt="" border="0" class="imageCenterAlign" id="l2maps3"/><a onmouseover="TurnOnLevel2(l2maps3)" onmouseout="TurnOffLevel2(l2maps3)"href="#">Bus &amp; rail maps</a><br /></div>

Real Life Examples The Style Sheet

/* Maps SubDiv */#navMapsSubDiv{

position:absolute;top: 86px;visibility : hidden;font-family : Arial, Helvetica, sans-serif;font-size : 11px;margin: 10px 10px 10px 10px;background: #D4C9BC;border : 1px solid #A3825D;padding : 5px 5px 5px;left:0px;z-index: 100;

}

Real Life Examples The JavaScript/** Dummy function that prevents errors while page is

loading*/function nada(){};

this.SwapImageOn = nada;this.SwapImageOff = nada;this.TurnSubOn = nadathis.TurnSubOff = nada;this.TurnOffLevel2 = nada;this.TurnOnLevel2 = nada;

Real Life Examples The JavaScript/** Determine what code to use*/

if( document.all ){this.init = IE_init;

}else if ( document.layers ) {this.init = NN_init;

}else if (document.getElementById) { this.init = std_init; }

Real Life Examples The JavaScript/** Init functions*/function IE_init(){

this.SwapImageOn = std_SwapImageOn;this.SwapImageOff = std_SwapImageOff;this.TurnSubOn = IE_TurnSubOn;this.TurnSubOff = IE_TurnSubOff;this.TurnOffLevel2 = std_TurnOffLevel2;this.TurnOnLevel2 = std_TurnOnLevel2;__windowLoaded();

}

Real Life Examples The JavaScriptfunction IE_TurnSubOn(sectionname) { if(eval(sectionname+"SubDiv")){ if(active_sub_div) TurnSubOff(active_sub_div); active_sub_div = sectionname; eval(sectionname+"SubDiv").style.visibility = "visible"; }}

function NN_TurnSubOn(sectionname) {if(eval(sectionname+"SubDiv")){ if(active_sub_div) TurnSubOff(active_sub_div); active_sub_div = sectionname; document.layers[sectionname+"SubDiv"].visibility = "visible"; }}

function std_TurnSubOn(sectionname) { if(document.getElementById( sectionname+"SubDiv" ) != null){ if(active_sub_div) TurnSubOff(active_sub_div); active_sub_div = sectionname; document.getElementById( sectionname+"SubDiv" ).style.visibility = "visible"; }}

Real Life Examples Browser Detectionfunction getBrowserSpecs() {

var is = new Object();

var agt = navigator.userAgent.toLowerCase().toLowerCase();

// *** BROWSER VERSION ***

// Note: On IE5, these return 4, so use is.ie5up to detect IE5.

var reNumber = new RegExp( "[0-9\.]+" ); // assume the version is the first number in the USER AGENT

is.major = parseInt( reNumber.exec( agt )[0] );

is.minor = parseFloat( reNumber.exec( agt )[0] );

Real Life Examplesis.nav = ( (agt.indexOf('mozilla')!=-1)

&& (agt.indexOf('spoofer')==-1)

&& (agt.indexOf('compatible') == -1)

&& (agt.indexOf('opera')==-1)

&& (agt.indexOf('webtv')==-1) );

is.nav4 = ( is.nav && ( is.major == 4 ) );

is.nav4up = ( is.nav && ( is.major >= 4 ) );

is.navonly = (is.nav && ( ( agt.indexOf(";nav") != -1 ) || ( agt.indexOf("; nav") != -1 ) ) );

Real Life Examples

is.nav6up = ( is.nav && (is.major >= 6 ) );

is.ie = ( agt.indexOf("msie") != -1 );

is.ie3 = ( is.ie && ( is.major < 4 ) );

is.ie4 = ( is.ie && ( is.major == 4 ) && ( agt.indexOf("msie 5") == -1 ) ); // what about 6.0?

is.ie4up = ( is.ie && ( is.major >= 4 ) );

is.ie5 = ( is.ie && ( is.major == 4 ) && ( agt.indexOf("msie 5" ) != -1) );

is.ie5up = ( is.ie && !is.ie3 && !is.ie4 ); // this will assume 5up if it isn't 3 or 4

is.opera = ( agt.indexOf("opera") != -1 );

is.safari = ( agt.indexOf("safari") != -1 );

is.webtv = ( agt.indexOf("webtv") != -1 );

Real Life Examples// *** PLATFORM ***

is.win = ( ( agt.indexOf("win")!=-1 ) || ( agt.indexOf("16bit" ) !=-1 ) );

// NOTE: On Opera 3.0, the userAgent string includes "Windows 95/NT4" on all

// Win32, so you can't distinguish between Win95 and WinNT.

is.win95 = ( (agt.indexOf("win95")!=-1 ) || ( agt.indexOf("windows 95") != -1 ) );

// is this a 16 bit compiled version?

/*

is.win16 = (( agt.indexOf("win16") != -1 ) ||

( agt.indexOf("16bit") != -1) ||

( agt.indexOf("windows 3.1") != -1 ) ||

( agt.indexOf("windows 16-bit")!=-1 ) );

is.win31 = (( agt.indexOf("windows 3.1")!=-1 ) ||

(agt.indexOf("win16")!=-1) ||

(agt.indexOf("windows 16-bit")!=-1) );

*/

Real Life Examples// NOTE: Reliable detection of Win98 may not be possible. It appears that:

// - On Nav 4.x and before you'll get plain "Windows" in userAgent.

// - On Mercury client, the 32-bit version will return "Win98", but

// the 16-bit version running on Win98 will still return "Win95".

is.win98 = ( (agt.indexOf("win98")!=-1 ) || ( agt.indexOf("windows 98")!=-1) );

is.winnt = ( (agt.indexOf("winnt")!=-1) || (agt.indexOf("windows nt")!=-1) );

is.win32 = ( is.win95 || is.winnt || is.win98 ||

( agt.indexOf("win32")!=-1 ) || ( agt.indexOf("32bit")!=-1 ) );

is.os2 = ( (agt.indexOf("os/2")!=-1 ) || ( agt.indexOf("ibm-webexplorer")!=-1) );

Real Life Examplesis.mac = ( agt.indexOf("mac")!=-1 );

is.mac68k = ( is.mac && ( (agt.indexOf("68k")!=-1 ) || ( agt.indexOf("68000")!=-1) ) );

is.macppc = ( is.mac && ( (agt.indexOf("ppc")!=-1 ) || (agt.indexOf("powerpc")!=-1) ) );

is.linux = (agt.indexOf("inux")!=-1);

is.unix = (agt.indexOf("x11")!=-1);

return is;

}

Real Life ExamplesSo finally to use

var browser = getBrowserSpecs();

Debugging your script Most common way

alert(); Better way

Use Firefox, Netscapetype javascript: in the location bar and you will go to JavaScript console

Real Debugging Go to Microsoft and download script

debugger. User Beware….

Patient.txt

Apponit.txt

Patient.txt

Apponit.txt

Apponit.txtApponit.txt