Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to JavaScript Jaime Ruiz. Short History of JavaScript Released in 1996 with Netscape 2 Originally called LiveScript MS releases Jscript with IE.

Similar presentations


Presentation on theme: "Intro to JavaScript Jaime Ruiz. Short History of JavaScript Released in 1996 with Netscape 2 Originally called LiveScript MS releases Jscript with IE."— Presentation transcript:

1 Intro to JavaScript Jaime Ruiz

2 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.

3 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

4 Common Uses of JavaScript Client Side Image Rollovers (most common) Form Validation http://www.papiowines.com/contactus.asp http://www.papiowines.com/contactus.asp Dynamic Form Generation http://www.robertmondavi.com/Wheretobuy/ http://www.robertmondavi.com/Wheretobuy/ DHTML http://www.bart.gov http://www.bart.gov Browser Detection Server-Side Microsoft ASP pages

5 Bad Uses of JavaScript Just because you can doesn’t mean you should

6 Strengths and Weaknesses Strengths Easy to learn Powerful? Close to being cross-platform Weaknesses Promotes bad programming Makes websites less usable

7 Overview

8 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?

9 Adding JavaScript to HTML Inline External File

10 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

11 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

12 Scope Is the following code valid? for(var i = 0; i < 10;i++){ document.write(i); } alert(i);

13 Scope Is the following code valid? for(var i = 0; i < 10;i++){ document.write(i); } alert(i); YES! Scopes only happens within functions

14 Scope var myInt = 0 //Global Var function foo(){ var i = 10; //local variable myInt += i; } document.write(i); //will cause error

15 Operators Arithmetic (the usual suspects) +,-,*,/,%,--,++ Comparison ==, !=, >, >=, <, <= Boolean &&, ||, !

16 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; }

17 Statements Loops for(var i =0; i < myArray.length;i++){ document.write(i); } do { statements;} while (condition) while(condition){ statements; }

18 Statements Object Manipulation for …in (can be object or array) for(var prop in document){ document.write(prop + " = " + document[prop] +" "); } Ouput namespaces = [object] lastModified = 03/14/2005 18:45:05 parentNode = null nodeType = 9 fileCreatedDate = 03/14/2005 onbeforeeditfocus = null bgColor = #ffffff …

19 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; }

20 Functions Example: function foo(myString){ document.write(myString); } foo(“Computers are fun”); foo(); //will this work?

21 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.

22 JavaScript Objects To declare an object var myObj = new Object(); To set properties myObj.name = “blah” Setting methods myObj.foo = foo;

23 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);

24 Real Life Examples Swap Images Steps Preload images On mouse over event swap the image On mouse out event restore the image

25 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

26 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

27 Real Life Examples Form Validation Create function to run on form’s onSubmit event

28 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; }

29 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[“elemen tName”]

30 Real Life Examples Dynamically build a select box The Form Select One Robert Mondavi Private Selection Robert Mondavi Winery Woodbridge First, Select a Winery------------------------ __________________________________________

31 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; }

32 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

33 Real Life Examples The HTML Trip planner Find a stop/station Bus & rail maps

34 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; }

35 Real Life Examples The JavaScript /* * Dummy function that prevents errors while page is loading */ function nada(){}; this.SwapImageOn = nada; this.SwapImageOff = nada; this.TurnSubOn = nada this.TurnSubOff = nada; this.TurnOffLevel2 = nada; this.TurnOnLevel2 = nada;

36 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; }

37 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(); }

38 Real Life Examples The JavaScript function 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"; }

39 Real Life Examples Browser Detection function 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] );

40 Real Life Examples is.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 ) ) );

41 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 );

42 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) ); */

43 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) );

44 Real Life Examples is.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; }

45 Real Life Examples So finally to use var browser = getBrowserSpecs();

46 Debugging your script Most common way alert(); Better way Use Firefox, Netscape type javascript: in the location bar and you will go to JavaScript console Real Debugging Go to Microsoft and download script debugger. User Beware….

47 Patient.txt Apponit.txt Patient.txt Apponit.txt


Download ppt "Intro to JavaScript Jaime Ruiz. Short History of JavaScript Released in 1996 with Netscape 2 Originally called LiveScript MS releases Jscript with IE."

Similar presentations


Ads by Google