Presentation is loading. Please wait.

Presentation is loading. Please wait.

Javascript Introduction Norman White Material is from Go there to run examples interactively.

Similar presentations

Presentation on theme: "Javascript Introduction Norman White Material is from Go there to run examples interactively."— Presentation transcript:

1 Javascript Introduction Norman White Material is from Go there to run examples interactively

2 Javascript overview JS is the primary scripting language for browsers. –Supported by virtually all browsers –It is code that that is embedded in the html and allows logic to be added that runs on the client instead of the server. –JS can dynamically change the content of the web page after it is downloaded –Official standard is ECMAScript-262

3 Javascript Advantages JS runs on then browser, not the server. –Can dramatically reduce network traffic back to the server. –Move processing from the server to the browser, reduces/eliminates processing on the server. –If running on a mobile device, Javascript allows access to native mobile device capabilities through the Phone gap library. –Javascript, CSS 3 and HTML 5 will allow us to develop web pages that automatically display correctly on different devices, including mobile. Many JS Libraries available, especially JQUERY and JQUERY Mobile.

4 How do we use Javascript Insert JS code directly into the html document, or include it from a file or the web. The browser will execute the JS code when it sees it in the document. IMPORTANT –JS is running on the browser NOT the server! –JS may need to retrieve information from a server. We will talk about that later.

5 Things JS can do React to events –Mouse over –Mouse click –Page load –Form submit –… Change the html code dynamically depending on events Detect users browser Manage Cookies

6 How to insert dynamic content into html My First Web Page document.write(" " + Date() + " ");

7 Hiding JS on browsers that don’t support it Surround it in comments

8 Controlling when JS executes We may not want to execute it when/as the page loads, but after some event. –Like: User does something Page is completely loaded …

9 Better is to just change the element Avoids rewriting complete document My First Web Page document.getElementById("demo").innerHTML=Date();

10 JS Functions function displayDate() { document.getElementById("demo").innerHTML=Date(); } My First Web Page Display Date

11 JS can be in external files

12 JS Blocks Code can be grouped into blocks with { } { document.write(" This is a heading "); document.write(" This is a paragraph. "); document.write(" This is another paragraph. "); }

13 Comments Single line comments start with // –// this is a single line comment Or Some code // comment at the end of the line Multiline comments start with /* and end with */ –This is a multi-line comment /* Some comments Some more comments */

14 Variables Variables can take on different values at different times Variable names are case sensitive Names have to start with a letter, a $ or an underscore Variables that hold text have to have the text in quotes,i.e. Myvar=“Hello”

15 Local and Global variables Local variables are declared in a function with the var declaration, i.e. var x; These variables only exist inside the function. i.e. created when the function is entered and deleted when it exits Global variables are declared outside a function, or without the “var” keyword in a function Global variables can be used anywhere on the web page, not just in the function they were created.

16 Arithmetic operators (assume y = 5) OperatorDescriptionExampleResult +Additionx=y+2x=7y=5 -Subtractionx=y-2x=3y=5 *Multiplicationx=y*2x=10y=5 /Divisionx=y/2x=2.5y=5 % Modulus (division remainder) x=y%2x=1y=5 ++Incrementx=++yx=6y=6 x=y++x=5y=6 --Decrementx=--yx=4y=4 x=y--x=5y=4

17 Assignment operators assume x=10 and y=5 OperatorExampleSame AsResult =x=y x=5 +=x+=yx=x+yx=15 -=x-=yx=x-yx=5 *=x*=yx=x*yx=50 /=x/=yx=x/yx=2 %=x%=yx=x%yx=0

18 Strings + = concatenation txt1="What a very"; txt2="nice day"; txt3=txt1+txt2; txt3 will be “What a verynice day” txt1="What a very"; txt2="nice day"; txt3=txt1+" "+txt2; txt3 will be “What a very nice day”

19 Strings and numbers Result of adding strings and numbers is a string…. x=5+5; document.write(x); x="5"+"5"; document.write(x); x=5+"5"; document.write(x); x="5"+5; document.write(x);

20 Comparison Operators x=5 OperatorDescriptionExample ==is equal to x==8 is false x==5 is true ===is exactly equal to (value and type) x ===5 is true x==="5" is false !=is not equalx!=8 is true >is greater thanx>8 is false =is greater than or equal tox>=8 is false <=is less than or equal tox<=8 is true Use: If (age<18) document.write(“Too young”);

21 Logical Operators x=6 and y=3 OperatorDescriptionExample &&and(x 1) is true ||or(x==5 || y==5) is false !not!(x==y) is true Conditional operator Variablename= (condition)?value1:value2 var visitor="PRES"; var greeting=(visitor=="PRES")?"Dear President ":"Dear "; document.write(greeting);

22 Conditional Statements if if … else If.. else if … else switch

23 If Statement if (condition) { Code to be executed } //Write a "Good morning" greeting if //the time is less than 10 var d=new Date(); var time=d.getHours(); if (time Good morning "); }

24 If …else if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true } //If the time is less than 10, you will get a "Good morning" greeting. //Otherwise you will get a "Good day" greeting. var d = new Date(); var time = d.getHours(); if (time

25 IF…else if…else if (condition1) { code to be executed if condition1 is true } else if (condition2) { code to be executed if condition2 is true } else { code to be executed if neither condition1 nor condition2 is true }

26 Switch statement switch(n) { case 1: execute code block 1 break; case 2: execute code block 2 break; default: code to be executed if n is different from case 1 and 2 }

27 Switch example //You will receive a different greeting based //on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc. var d=new Date(); var theDay=d.getDay(); switch (theDay) { case 5: document.write("Finally Friday"); break; case 6: document.write("Super Saturday"); break; case 0: document.write("Sleepy Sunday"); break; default: document.write("I'm looking forward to this weekend!"); }

28 Popup boxes alert("sometext"); (user has to click ok) function show_alert() { alert("I am an alert box!"); }

29 Confirm box user clicks OK or Cancel confirm("sometext"); function show_confirm() { var r=confirm("Press a button"); if (r==true) { alert("You pressed OK!"); } else { alert("You pressed Cancel!"); } }

30 Prompt box User can enter new value and click ok, or cancel prompt("sometext","defaultvalue"); function show_prompt() { var name=prompt("Please enter your name","Harry Potter"); if (name!=null && name!="") { document.write(" Hello " + name + "! How are you today? "); } }

31 Functions (usually defined in head section, so that they are defined before calling) function functionname(var1,var2,...,varX) { some code } function displaymessage() { alert("Hello World!"); }

32 Return statement Used to return values from functions function product(a,b) { return a*b; } document.write( product(4,3) );

33 For Loops for (variable=startvalue;variable<=endvalue;variable=variable+increment) { code to be executed } var i=0; for (i=0;i "); }

34 While loop while (variable<=endvalue) { code to be executed } var i=0; while (i "); i++; }

35 Do while (execute at least once) do { code to be executed } while (variable<=endvalue); var i=0; do { document.write("The number is " + i); document.write(" "); i++; } while (i

36 Break statement Breaks out of a loop var i=0; for (i=0;i "); }

37 Continue break current loop and continue with next value var i=0 for (i=0;i "); }

38 For … in Loops through values of an object for (variable in object) { code to be executed } var person={fname:"John",lname:"Doe",age:25}; var x; for (x in person) { document.write(person[x] + " "); } Result: John Doe 25

39 Events Actions that can be detected by JS function displayDate() { document.getElementById("demo").innerHTML=Date(); } My First Web Page Display Date

40 Events Many events, also functions that can cause events Some Examples: A mouse click A web page or an image loading Mousing over a hot spot on the web page Selecting an input field in an HTML form Submitting an HTML form A keystroke

41 onSubmit Event Used to check form input If checkForm returns “True” form will be submitted, otherwise it will be cancelled. This is how we would check form fields or compute the value of a hidden field like”fchar”

42 Catching Errors, Try … catch try { //Run some code here } catch(err) { //Handle errors here } var txt=""; function message() { try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page.\n\n"; txt+="Error description: " + err.message + "\n\n"; txt+="Click OK to continue.\n\n"; alert(txt); } }

43 Throw Statement Generate an error exception throw exception var x=prompt("Enter a number between 5 and 10:",""); try { if(x>10) { throw "Err1"; } else if(x

44 Special Characters Use the “\” to insert special characters var txt="We are the so-called "Vikings" from the north."; document.write(txt); INSTEAD use \ to escape the “ so it is interpreted as a regular character. var txt="We are the so-called \"Vikings\" from the north."; document.write(txt);

45 Other special characters CodeOutputs \‘single quote \“double quote \\backslash \nnew line \rcarriage return \ttab \bbackspace \fform feed

46 Misc JavaScript is Case Sensitive –A function named "myfunction" is not the same as "myFunction" and a variable named "myVar" is not the same as "myvar". –JavaScript is case sensitive - therefore watch your capitalization closely when you create or call variables, objects and functions. White Space –JavaScript ignores extra spaces. You can add white space to your script to make it more readable. The following lines are equivalent: var name="Hege"; var name = "Hege"; Break up a Code Line –You can break up a code line within a text string with a backslash. The example below will be displayed properly: document.write("Hello \ World!"); However, you cannot break up a code line like this: document.write \ ("Hello World!");

47 Takeaway Javascript is a large language, many features Very powerful Need to be an expert to do “fancy” things Allows us to move a lot of processing to the client, reducing communications with server, very important for mobile devices where we may have limited/no bandwidth. Would be nice if there were some preprogrammed functions to do useful things SOLUTION: The JQUERY library

48 JQUERY Javascript library that works on most browsers. Hides many details from developers. In use at over 50% of large web sites There is now a JQUERY MOBILE library, customized for mobile devices One statement allows you to use jquery – Next time, intro to JQUERY

Download ppt "Javascript Introduction Norman White Material is from Go there to run examples interactively."

Similar presentations

Ads by Google