Javascript Introduction

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

description

Javascript Introduction. Norman White Material is from w3schools.com Go there to run examples interactively. Javascript overview. JS is the primary scripting language for browsers. Supported by virtually all browsers - PowerPoint PPT Presentation

Transcript of Javascript Introduction

Page 1: Javascript Introduction

Javascript Introduction

Norman WhiteMaterial is from w3schools.com

Go there to run examples interactively

Page 2: Javascript Introduction

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

Page 3: Javascript Introduction

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.

Page 4: Javascript Introduction

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.

Page 5: Javascript Introduction

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

Page 6: Javascript Introduction

How to insert dynamic content into html

<html><body>

<h1>My First Web Page</h1>

<script type="text/javascript">document.write("<p>" + Date() + "</p>");</script>

</body></html>

Page 7: Javascript Introduction

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

<html><body><script type="text/javascript"><!--document.getElementById("demo").innerHTML=Date();//--></script></body></html>

Page 8: Javascript Introduction

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• …

Page 9: Javascript Introduction

Better is to just change the <p> elementAvoids rewriting complete document

<html><body>

<h1>My First Web Page</h1>

<p id="demo"></p>

<script type="text/javascript">document.getElementById("demo").innerHTML=Date();</script>

</body></html>

Page 10: Javascript Introduction

JS Functions• <html><head>

<script type="text/javascript">function displayDate(){document.getElementById("demo").innerHTML=Date();}</script></head>

• <body>• <h1>My First Web Page</h1>• <p id="demo"></p>• <button type="button" onclick="displayDate()“ >Display Date</button>• </body>

</html>

Page 11: Javascript Introduction

JS can be in external files<html>

<head><script type="text/javascript" src="xxx.js"></script></head><body></body></html>

Page 12: Javascript Introduction

JS BlocksCode can be grouped into blocks with { }

<script type="text/javascript">{document.write("<h1>This is a heading</h1>");document.write("<p>This is a paragraph.</p>");document.write("<p>This is another paragraph.</p>");}</script>

Page 13: Javascript Introduction

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 commentsSome more comments */

Page 14: Javascript Introduction

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”

Page 15: Javascript Introduction

Local and Global variablesLocal 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.

Page 16: Javascript Introduction

Arithmetic operators(assume y = 5)

Operator Description Example Result+ Addition x=y+2 x=7 y=5- Subtraction x=y-2 x=3 y=5* Multiplication x=y*2 x=10 y=5/ Division x=y/2 x=2.5 y=5% Modulus (division remainder) x=y%2 x=1 y=5++ Increment x=++y x=6 y=6

x=y++ x=5 y=6-- Decrement x=--y x=4 y=4

x=y-- x=5 y=4

Page 17: Javascript Introduction

Assignment operatorsassume x=10 and y=5

Operator Example Same As Result= x=y  x=5+= x+=y x=x+y x=15-= x-=y x=x-y x=5*= x*=y x=x*y x=50/= x/=y x=x/y x=2%= x%=y x=x%y x=0

Page 18: Javascript Introduction

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”

Page 19: Javascript Introduction

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

Page 20: Javascript Introduction

Comparison Operatorsx=5

Operator Description Example== 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 equal x!=8 is true> is greater than x>8 is false< is less than x<8 is true>= is greater than or equal to x>=8 is false<= is less than or equal to x<=8 is true

Use:If (age<18) document.write(“Too young”);

Page 21: Javascript Introduction

Logical Operatorsx=6 and y=3

Operator Description Example

&& and (x < 10 && y > 1) is true|| or (x==5 || y==5) is false! not !(x==y) is true

Conditional operator

Variablename= (condition)?value1:value2

<script type="text/javascript">

var visitor="PRES";var greeting=(visitor=="PRES")?"Dear President ":"Dear ";document.write(greeting);

</script>

Page 22: Javascript Introduction

Conditional Statements

ifif … elseIf .. else if … elseswitch

Page 23: Javascript Introduction

If Statementif (condition) { Code to be executed }

<script type="text/javascript">

//Write a "Good morning" greeting if//the time is less than 10

var d=new Date();var time=d.getHours();

if (time<10)  {  document.write("<b>Good morning</b>");  }</script>

Page 24: Javascript Introduction

If …elseif (condition)

  {  code to be executed if condition is true  }else  {  code to be executed if condition is not true  }

<script type="text/javascript">//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 < 10)  {  document.write("Good morning!");  }else  {  document.write("Good day!");  }</script>

Page 25: Javascript Introduction

IF…else if…elseif (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  }

Page 26: Javascript Introduction

Switch statementswitch(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}

Page 27: Javascript Introduction

Switch example<script type="text/javascript">

//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!");}</script>

Page 28: Javascript Introduction

Popup boxes

alert("sometext"); (user has to click ok)<html><head><script type="text/javascript">function show_alert(){alert("I am an alert box!");}</script></head><body>

<input type="button" onclick="show_alert()" value="Show alert box" />

</body></html>

Page 29: Javascript Introduction

Confirm boxuser clicks OK or Cancel

confirm("sometext"); <html><head><script type="text/javascript">function show_confirm(){var r=confirm("Press a button");if (r==true)  {  alert("You pressed OK!");  }else  {  alert("You pressed Cancel!");  }}</script></head><body>

<input type="button" onclick="show_confirm()" value="Show confirm box" />

</body></html>

Page 30: Javascript Introduction

Prompt boxUser can enter new value and click ok, or cancel

prompt("sometext","defaultvalue"); <html><head><script type="text/javascript">function show_prompt(){var name=prompt("Please enter your name","Harry Potter");if (name!=null && name!="")  {  document.write("<p>Hello " + name + "! How are you today?</p>");  }}</script></head><body>

<input type="button" onclick="show_prompt()" value="Show prompt box" />

</body></html>

Page 31: Javascript Introduction

Functions(usually defined in head section, so that they are defined before calling)

function functionname(var1,var2,...,varX){some code}

<html><head><script type="text/javascript">function displaymessage(){alert("Hello World!");}</script></head>

<body><form><input type="button" value="Click me!" onclick="displaymessage()" /></form></body></html>

Page 32: Javascript Introduction

Return statementUsed to return values from functions

<html><head><script type="text/javascript">function product(a,b){return a*b;}</script></head>

<body><script type="text/javascript">document.write( product(4,3) );</script>

</body></html>

Page 33: Javascript Introduction

For Loopsfor (variable=startvalue;variable<=endvalue;variable=variable+increment)

{code to be executed}

<html><body><script type="text/javascript">var i=0;for (i=0;i<=5;i++){document.write("The number is " + i);document.write("<br />");}</script></body></html>

Page 34: Javascript Introduction

While loopwhile (variable<=endvalue)

  {  code to be executed  }

<html><body><script type="text/javascript">var i=0;while (i<=5)  {  document.write("The number is " + i);  document.write("<br />");  i++;  }</script></body></html>

Page 35: Javascript Introduction

Do while(execute at least once)

do  {  code to be executed  }while (variable<=endvalue);

<html><body><script type="text/javascript">var i=0;do  {  document.write("The number is " + i);  document.write("<br />");  i++;  }while (i<=5);</script></body></html>

Page 36: Javascript Introduction

Break statementBreaks out of a loop

<html><body><script type="text/javascript">var i=0;for (i=0;i<=10;i++)  {  if (i==3)    {    break;    }  document.write("The number is " + i);  document.write("<br />");  }</script></body></html>

Page 37: Javascript Introduction

Continuebreak current loop and continue with next value

<html><body><script type="text/javascript">var i=0for (i=0;i<=10;i++)  {  if (i==3)    {    continue;    }  document.write("The number is " + i);  document.write("<br />");  }</script></body></html>

Page 38: Javascript Introduction

For … inLoops 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

Page 39: Javascript Introduction

EventsActions that can be detected by JS

<html>

<head><script type="text/javascript">function displayDate(){document.getElementById("demo").innerHTML=Date();}</script></head>

<body>

<h1>My First Web Page</h1>

<p id="demo"></p>

<button type="button" onclick="displayDate()">Display Date</button>

</body></html>

Page 40: Javascript Introduction

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

Page 41: Javascript Introduction

onSubmit EventUsed to check form input

<form method="post" action="xxx.htm" onsubmit="return checkForm()">

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”

Page 42: Javascript Introduction

Catching Errors, Try … catchtry

  {  //Run some code here  }catch(err)  {  //Handle errors here  }

<html><head><script type="text/javascript">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);  }}</script></head>

<body><input type="button" value="View message" onclick="message()" /></body>

</html>

Page 43: Javascript Introduction

Throw StatementGenerate an error exception

throw exception

<html><body><script type="text/javascript">var x=prompt("Enter a number between 5 and 10:","");try  {   if(x>10)    {    throw "Err1";    }  else if(x<5)    {    throw "Err2";    }  else if(isNaN(x))    {    throw "Err3";    }  }catch(err)  {  if(err=="Err1")    {    document.write("Error! The value is too high.");    }  if(err=="Err2")    {    document.write("Error! The value is too low.");    }  if(err=="Err3")    {    document.write("Error! The value is not a number.");    }  }</script></body></html>

Page 44: Javascript Introduction

Special CharactersUse 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);

Page 45: Javascript Introduction

Other special charactersCode Outputs\‘ single quote\“ double quote\\backslash\n new line\r carriage return\t tab\b backspace\f form feed

Page 46: Javascript Introduction

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!");

Page 47: Javascript Introduction

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

Page 48: Javascript Introduction

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

– <script type=“text/javascript” src=“jquery.js”></script>• Next time, intro to JQUERY