1 / 59

Just Enough JavaScript

Just Enough JavaScript. Javascript code is triggered by “events”. New events proposed Jan 2010 in HTML5. In many ways JavaScript is just like but it’s not really like. Common Programming Language Features. Comments Data Types Variable Declarations Expressions Flow of Control Statements

Download Presentation

Just Enough JavaScript

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Just Enough JavaScript

  2. Javascript code is triggered by “events” New events proposed Jan 2010 in HTML5

  3. In many ways JavaScript is just likebut it’s not really like

  4. Common Programming Language Features • Comments • Data Types • Variable Declarations • Expressions • Flow of Control Statements • Functions and Subroutines • Macros and Preprocessor Commands • I/O Statements • Libraries • External Tools (Compiler, debugger etc)

  5. Comments //Single line comments /* Multiple line comments */

  6. The Simplest Program <!- - HTML Comment: - -> <script> //This shows a simple message box alert(‘Msg’); </script

  7. JavaScript inserted into HTML <body> <script type="text/javascript"> alert('Opening Page'); function myMsg(s){ alert('msg: '+s); } alert('After this the page is displayed'); </script> <input type=button value=‘Click Test’ onclick=“alert(‘alert1’); myAlert(‘alert2’);” /> </body> • Javascript outside of a function and inside <script> tags runs when the web page is loaded • JavaScript code and calls to JavaScript functions can be triggered using events such as onclick • When quoting strings use either single quote or double quote – be consistant

  8. Refering to an external file of functions <script type="text/javascript" language="javascript" src="hello.js">

  9. Built In Dialogs • alert(msg); //simple message box • confirm(msg); //shows yes/no. returns true/false • prompt(msg,default value); //input box IE supports additional dialog boxes – avoid!document.execCommand(‘SaveAs’);

  10. getElementByID(‘idvalue’) <button onclick='javascript:result=prompt("Enter your name","Default"); display=document.getElementById("disp"); display.innerHTML=result;'> <tag id=disp>Result will show here</tag>

  11. Note the purpose of these 3 attributes! <tag id=‘uniqueName’ name=‘groupName’ class=‘styleName’ /> id: a unique identifier in your page name: used for radio buttons and name/value pairs passed in query strings class: used to link a particular style with a tag

  12. Data Types • Number • String • Boolean • DateThere are 2 other “special” types • Undefined • Null

  13. Variable Declarations • var counter, pi=3.15159265, name=‘Fred’, name2=“Janna”, completed=true, approved=false;Javascript is a weakly typed language • We don’t have to declare a data type • The type of a variable depends on what we assign to it • The data type can change at any time. • Variables names are case sensitive. (So are JavaScript keywords like var)

  14. Declaring Arrays • var names=[‘Mary’,”Murray”,”Jim”];var nestedArray=[ [1,2,3], [4,5,6], [7,8,9]];var list=new Array(‘Martha’,’Muffin’,’Donut’,18); var myArray=new Array();for(i=1;i<10;i++) myArray[i]=i*i;myArray[100] = 42;We don’t have to say how big an array is in advance of its use!We can mix different data types in an array!

  15. Declaring Variables To indicate a constant: ALL_CAPS ie: var GRAVITATIONAL_CONST=6.67300 e-11; variables use camelCapsvar firstName=‘George’; datatypes use camel caps that start with a capital:class NetworkCard ....

  16. Scope var msg="I am a global variable"; var counter=1; //also gobal function display(msg) //This msg is local { var local; alert(msg+local+counter); counter++; } display("Local value of msg"); display(msg); //Use global value and insert into function

  17. Hungarian Notation The practice of putting a prefix to indicate the datatype of a variable, named after Charles SimonyisFirstName - its a stringbFound - its a booleanasNames - array of stringsdBirth - dateIt’s encouraged in Microsoft communities

  18. Operators Standard C arithmetic operators will work++ -- * / %+ - += -= *= /= %=? : (triadic operator)The + operator also concatenates Strings: 5+5 becomes 10, ‘5’+’5’ becomes ‘55’ - this could create problemsresult=‘Hello ’+’world!’;

  19. JavaScript Reserved Keywords You should know this from C or VB New to JavaScript - we’ll cover these Proposed but not standard We won’t cover these

  20. The typeof Operator Make believe that it’s a functionx=17 alert(typeof(x)); //Numberx=‘17’; alert(typeof(x)); //Stringx=new Date();alert(typeof(x)); //Objectx=true;alert(typeof x); //Booleantypeof always returns a string

  21. Javascript Relational Operators Standard C relational operators will work too> < =>= <= !==== !== matches data type and value5==“5” is true. 5===“5” is false

  22. JavaScript Logical Operators These are just like C as well! • && • || • !

  23. Flow of Control: if stmt price=18;if (age<18 || age>65){ total=price*taxRate*.80; }else total=price*taxRate;

  24. Flow of Control: Comparing Strings //This works likes C ought to have worked!if (sex==‘Female’){ alert(‘Hello Madam’); }if(password!=‘Swordfish’) alert(‘try again!’);

  25. switch statement n=prompt(‘Enter any value'); switch(n) //The switch statement will take any scalar data type! { case 1: document.write('We accept numbers'); break; case true: document.write('We accept boolean values'); break; case 4.7: document.write('we accept floating point numbers'); break; case 'Humber‘: case x: document.write('switch will take a String or match the value of a variable'); break; default: document.write('Default case'); }

  26. Looping – Just like C for(i=0; i<10;i++){ idName=‘checkbox’+i; document.write(‘<input id=“’ + idName + ‘”> ‘ + i + ‘</input>’); }

  27. A “for each” loop var students=['Bob','Mike','Rinky']; for(i in students) { alert(i+ ' ' +students[i]); }

  28. Associative Arrays var students=['Bob','Mike','Rinky']; for(i in students) { alert(i+ ' ' +students[i]); }

  29. Early Exit from a Loop sum=0;for(i=0; ;i++){ sum+=i; if(sum>20) break; } alert(‘The total is: ‘ + sum);

  30. Skipping to the End of a loop sum=0; for(i=0; i<7;i++) { if(i==5 || i==3) continue; sum+=i; } alert(sum);

  31. while loops var counter = 0; var newLine = ‘<br />’; document.write(newLine); while(counter < 10){ document.write(“counter = " + counter); document.write(newLine); counter++; } document.write(“Done!!");

  32. Functions and Subroutines function function1(arg1,arg2,arg2){ result=arg1+arg2+arg3; return result; } function subroutine1(arg1,arg2){ //Do something return; }

  33. Some Math Functions Also asin, acos, atan, atan2, log, exp and a few other items

  34. String Functions

  35. Date Functions Warnings: getMonth() returns a month as a number: 0-11 getDate() returns the day of the month: 1-31 getDay() returns the day of the week: 0-6 x=new Date(2010,12,1); //This is Jan 1, 2011! x=new Date(2012,2,0); //last day of Febuary, 2012 x=new Date(2012); //This is 2012 millisecs past the EPOCH

  36. Array Functions

  37. The Array slice Function var fruits = ["Banana", "Orange", "Apple", "Mango"];document.write(fruits.slice(0,1) + "<br />");document.write(fruits.slice(1) + "<br />");document.write(fruits.slice(-2) + "<br />");document.write(fruits);//OutputBananaOrange,Apple,MangoApple,MangoBanana,Orange,Apple,Mango Example taken from W3Schools.com

  38. The Array splice Function var fruits = ["Banana", "Orange", "Apple", "Mango"];document.write("Removed: " + fruits.splice(2,1,"Lemon") + "<br />");document.write(fruits); The function returns items removed and modifies the original array. Example taken from W3Schools.com

  39. Sorting an Array of Strings myArray.sort();

  40. Regular Expressions var str=‘Hello World. Have a nice day!’;str.replace(/World/,’Canada’);//result is: ‘Hello Canada. Have a nice day!’;result=str.replace(/[aeiou]/g,’*’); //result is ‘H*ll* C*n*d*. H*v* * n*c* d*y!’;//The original is unchangedresult= str.replace(/H/,’h’); //Only the first h affected Most of what you would have learned in “Unix and the Internet” about regularexpressions in vim can be applied here for doing complex search and replace.

  41. The match Function var str=‘Hello World. Have a nice day!’;str.match(/[aeiou].?/g);Returns the following array of matches[“el”, “o “, “o “, “av”,”a “, “ic”, “e “, “ay”] str="Monday Tuesday Wednesday Thursday Friday“; result=str.match(/(Mon|Fri)day/g);Returns: [“Monday”, “Friday”]

  42. Debugging

  43. Output to the Error Console You can send a message to the Error Console – however this stops the script: { .... //Code goes here if(value>10) throw new Error(“Your message goes here: “ + value); }

  44. You can also write to Firebug’s Console { console.log(“Your message: “ + yourVariable); console.log(“C style format allowed: %s, %d, $%8.2f”, myString, age, cost); console.debug(“ console.info(“ console.warn(“ console.error(

  45. DOM: The Document Object Model

  46. document as an Object(document Properties

  47. Window as an Object • To open a new window

  48. Navigator as an Object

  49. Cookies can be set with the Meta tag <META HTTP-EQUIV="Set-Cookie" CONTENT="cookievalue=myFirstCookie;expires=30"> <META HTTP-EQUIV="Set-Cookie" CONTENT="cookievalue3=my3rdCookie;expires=30"> setMessage('myList',document.cookie); //Result:cookievalue=myFirstCookie; cookievalue2=my2ndCookie; cookievalue3=my3rdCookie

  50. Retrieving a Cookie

More Related