Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introducing JavaScript 2020 Edition

Similar presentations


Presentation on theme: "Introducing JavaScript 2020 Edition"— Presentation transcript:

1 Introducing JavaScript 2020 Edition
Last Revised: Jan 2, 2020 Author: Prof. Leon King, Humber College

2 In many ways JavaScript is like not
With a bit of thrown in!

3 ECMAScript Dec 1995: JavaScript released by Netscape & Sun
Nov 1996: Netscape hands JavaScript standard over to the European Computer Manuf. Assoc to ensure platform neutrality. The standard is called ECMAScript. 2009: ECMAScript 5 standard is released. 2015/16: ECMAScript6/ES6 announced ECMA Next - new revisions to ECMAScript are happening on a yearly basis. To see which browser versions support newer features, the web site is an excellent resource!

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 */ You can also use a quoted string as a comment “Hi! This is a comment”;

6 The Simplest Program </script> <!- - HTML Comment: - ->
<script> console.log(“Hello World”); </script> Warning – do not copy the code you see in these slides directly. Windows uses non-ascii values for single and double quotes “quote”, ‘single quote’ which JavaScript does not understand. ASCII quotes look like this "double", 'single’. Changing this was too much effort. Type your code directly in vim or another IDE.

7 Debugging

8 Writing values to the Console
console.log(“Your message: “ + yourVariable); console.log(“C style format allowed: %s, %d, $%8.2f”, myString, age, cost); //But not %x or %o console.debug(fmt, arg1, arg2, ...) // console.info(fmt, arg1, arg2, ...) //neutral background console.warn(fmt, arg1, arg2, ...) //yellow background console.error(fmt, arg1, arg2, ...) //pink background to alert you console.log(“%c Hello %s”, “background:rgb(0,255,255)”,yourVariable) %c is a format code for CSS (not characters) – this is really neat! console.memory //how much memory do you have left?

9 Data Types Number (both integer and floating point) String Boolean
Object (includes arrays, JSON, Dates, regular expression and more) Function There is no char datatype. Even single characters are strings.

10 Global Variable Declarations
var counter, pi= , name=‘Fred’, name2=“Janna”, completed=true, approved=false; Javascript is a weakly typed language We don’t have to declare a data type, nor can you You can just use a variable w/o declaring it (most of the time) 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 as are JavaScript keywords like var You can use single or double quotes – just be consistent. A variable declared with var is global to the web page – but only after it appears

11 Local Variable Declarations
{ let counter, pi= , name=‘Fred’, name2=“Janna”, completed=true, approved=false; … } A variable declared using let is local to the block of code or function in which it appears. A variable declared with let can temporarily override another definition of a variable.

12 Declarations and Scope
The keywords let or var are optionally used to declare a variable. The is no data type specified. A variable declared within { } is local to that block of code. Avoid reusing variable names for different purposes in different blocks – it’s a common source of error The top level of scope is between <script> and </script> let i=10,j=70; if(true) ; let i=3; //This is a 2nd version of i, local to the if stmt j++; //The outside version of j is incremented } console.log(“i: %d j: %d”,i,j); //Result: i: 10 j: 71

13 Constants 0b01010101 - binary constants are new to JavaScript
0o octal constants are new too 12, 12.5, 1.2E5 - same as C 0xFFFFFF, 0x02fe “Hello World” or ‘Hello World’ - single and double quotes are interchangeable – just be consistent. `Sum: ${x+y}` - Backquotes create strings where you can use $ to substitute variables or expressions – similar to the bash shell. These are called template strings.

14 Special Constants true, false undefined Null NaN Infinity

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

16 JavaScript Reserved Keywords
Don’t use these for variable names abstract continue extends implements native static try as const false import new super typeof boolean debugger final in null switch use break default finally instanceof package synchronized var byte do float int private this void case double for interface protected throw volatile catch else function is public throws while char enum goto long return transient with class export if namespace short true of You should know this from C or Java New to JavaScript - we’ll cover these Proposed but not standard

17 Defining Arrays empty=[]; 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; Array subscripts start at [0]. 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!

18 Subscripts Don’t Need to Be Integers
Item[]; item[‘n1234’]=“bob”; item[12.35]=“Twelve dollars and 35 cents”; item[new Date()]=“Do laundry”; Arrays in JavaScript are called associative arrays. This is because we can associate any value as a key (index) with a value.

19 JSON Objects JSON stands for JavaScript Object Notation json1={ name : “Bob”, age: 21, sex: ‘M’} json1[‘name’] //value is “Bob” json1.name //value is also “Bob” json1.age=22 //changes Bob’s age json1.major=“CENG” //adds a new field delete json1.age //removes a field

20 Complex JSON Objects JSON stands for JavaScript Object Notation json1={ n1234: {name : “Bob”, age: 21, sex: ‘M’}, n1235: {name: “Sandy”, age:22}, …. }; json1.n1234.name; //value is “Bob” Json1[‘n1235’].name; //value “Sandy” json1.age=22; //changes Bob json1.major=“CENG”; //adds a new field delete json1.age; //removes a field

21 Operators

22 Assignment = works as you’d expect it to: a=7; if(a=9) { console.log( “Ooops. Use a==9”;}; b=(a+c=11); //assignment as a side effect in expr This is interesting and new…. [a,b,c]=[12,a+b,a*c];

23 Arithmetic 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 problems result=‘Hello ’+’world!’; 2**7 (exponentiation - this is new to ECMAScript 6 – it comes from FORTRAN)

24 Some Math Functions Math.abs(value) Absolute integer or float
Math.sin(value), Math.cos(value) Math.tan(value) All the trig functions you’d expect. value is measured in radians. Math.ceil(value) Math.floor(value) Math.round(value) Rounding functions – note that round only rounds to the nearest integer. Math.random() Random number between 0 and 1 Math.sqrt(n) Math.pow(n,m) nm Math.min(a,b) Math.max(a,b) lesser of two values greater of two values Math.log(num) Math.PI The value of P Type in Math. in the Chrome Dev environment to see what’s available

25 JavaScript Relational Operators
Standard C relational operators will work too > < == >= <= != === !== matches data type and value 5==“5” is true. 5===“5” is false * false == 0 is true true==1 is also true false==“” is true – as JavaScript coerces “” to a number – 0 You don’t need a strcmp. >,<,== etc work!

26 JavaScript Logical Operators
These are just like C as well! && || !

27 String Operator: + firstName=“Bob”; lastName=“Smith”; fullName=firstName+ “ “ + lastName;

28 String Functions “one,two,three”.split(‘,’)
Creates the array: [“one”,”two”,”three”] myString.length length of string x=myString.toUpperCase() x=myString.toLowerCase() x will be all upper case x will be all lower case “George”.substring(2,4) Value is “org” - we start counting at 0 “Bananana”.indexOf(“nan”) “Bananana”.lastIndexOf(“nan”) returns location ? “George”.charAt(0) result is “G” x=escape(“<br/> This & That?”)) y=unescape(string) Generates: %3CBR/%3E%20%26%20This%20%26%20That%3F%20 the inverse function These make a string portable to send over a network. Type in “hello”. in the Chrome console and a full list will pop up.

29 Bitwise Operators >> shift left << shift right
>>> shift left and don’t propagate the sign bit <<< - this operator doesn’t exist… why?

30 More JavaScript Operators
in delete instanceof new typeof Void … aka the “spread” operator

31 in The in operator can be used to test for the presence of an index in an array or an element in a JSON dictionary list=[1, 7, 12, 8, 13] if(3 in list) { … } if(‘Maria’ in classList) { … } in can also be used in a foreach loop. It will assume the value of each index or key for(index in list) { … } for(key in classList) { …. }

32 delete The delete operator can be used to undefine a variable x= new Date(); delete x; //x no longer exists. Its ‘value’ is undefined delete will also remove an element of an array by it’s index list=[1,2,57,12,3]; delete list[3]; //removes ’12’ which is at position 3 delete will remove an element from a JSON dictionary delete classList[‘Sam’].midterm; delete classList[‘Sam’][‘midterm’]; delete classList[‘Emily’];

33 The typeof Operator Make believe that it’s a function x=17 alert(typeof(x)); //’Number’ x=‘17’; alert(typeof(x)); //’String’ x=new Date(); alert(typeof(x)); //’Object’ x=true; alert(typeof x); //’Boolean’ typeof always returns a string

34 [] . [] and . are called the member of operators. In JavaScript they do the same thing myList[‘Sam’]= {midterm: 68, ‘final’: 79 } myList.Raina={midterm: 68, ‘final’ : 82 } We tend not to think of [] and . as operators, but they are and it is useful to consider them as such.

35 , The comma is an operator too. It separates items in a list. If used in an assignment it returns the last value x= myFunction1(),myFunction2(),7+9,i++,18; //x will be 18 This secondary use of , is rare – but it also works in C and Java too

36 numbers=[4,5,6]; newList= [1,2,3, …numbers, 7,8,9];A newList becomes: [1,2,3,4,5,6,7,8,9] The spread operator can also be used in function definitions

37 Functions

38 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’); compare to VB

39 All Variables in JavaScript Behave Like Objects
x=42; bin=x.toString(2); //Convert x to a binary string oct=x.toString(8); //convert x to an octal string hex=x.toString(16); //convert x to hex x= ; x5=x.toPrecision(5); //x5 is

40 Date Functions Warnings: getMonth() returns a month as a number: getDate() returns the day of the month: getDay() returns the day of the week: x=new Date(2020,12,1); //This is Jan 1, 2020! x=new Date(2020,2,0); //last day of February, x=new Date(2020); //This is 2020 millisecs past the EPOCH x=new Date(); //current timestamp

41 Array Functions [“one”,”two”,”three”].join(“;”)
Creates a string: one;two;three (it’s the opposite of split) myArray.length highest subscript in myArray+1 myArray.reverse() Reverses the order of elements in the array. myArray.slice(2,5) Creates a new array using elements 2 thru 5 of the old array myArray.map(function) Creates a new array by applying the function to each of the elements of the array.

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

43 Writing Your Own Function
function myFun(name, age, sex) { console.log(“Name: %s age: %d sex: %s”, name, age, sex; return {name: name, age : age, sex: sex } } A function can return any data type, or nothing!

44 Writing Your Own Function (2)
myFun=function(name, age, sex) { console.log(“Name: %s age: %d sex: %s”, name, age, sex; return {name: name, age : age, sex: sex } } aliasForFunction=myFun; aliasForFunction(“bob”, 22, ‘M’); A function name can behave like a variable

45 Arrow Notation for Functions (2)
myFun=(name, age, sex) => { console.log(“Name: %s age: %d sex: %s”, name, age, sex; return {name: name, age : age, sex: sex } } myFun(“bob”, 22, ‘M’); This is a form of syntactic sugar. It’s useful for “anonymous” functions that are passed as arguments.

46 Functions, arguments & the spread operator
function allArgs(x,y, …rest) { console.log(arguments.length); console.log(rest.length); console.log(arguments[0]); console.log(rest[0]): } allArgs(1,2,3,4,5,6); Results: 7, 5, 1, 3

47 setTimeout(anyFunct, msecs, args…)
JavaScript does not have a sleep function – that would freeze the browser!!!! setTimeout postpones the execution of a function until later, but carries on to the next statement immediately. setTimeout(doSomething,3000,1,2,”hello”); console.log(“Timed operation launched); //… 3 seconds later, doSomething(1,2,”hello”) is // called

48 Flow of Control Statements

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

50 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!’);

51 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'); case 4.7: document.write('we accept floating point numbers'); case 'Humber‘: case x: document.write('switch will take a String or match the value of a variable'); default: document.write('Default case'); }

52 throw, try {} catch(e) { }
let exceptionCount=0; var condition; try { if(condition===undefined) throw Error("Condition ain't got a valu"); console.log("We don't execute this statement"); } catch(exception) { exceptionCount++; console.log("Exception handler 1"); console.log(exception, exceptionCount); } try { thisFunctionDoesNotExist(); } catch(exception) { exceptionCount++; console.log("Exception handler 2") ; console.log(exception,exceptionCount); }

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

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

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

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

57 A “for each” loop var students=['Bob','Mike','Rinky'];
for(i in students) { console.log(“index: %d value: %s”, i, students[i]); } for returns the indices of the array: , 1, 2

58 New in ECMA 6: “for of” loop
var students=['Bob','Mike','Rinky']; for(student of students) { console.log(“value: %s”, student) } for returns the values of the array: ‘Bob’, ‘Mike’, ‘Rinky’

59 JSON and for each loops lookup={ ‘CENG 251’ : ‘Unix Internals’, ‘CENG 252’ : ‘Embedded Systems’, ‘CENG254’ : ‘Database with Java’, ‘CENG256’ : ‘Internet Scripting’ } for(key in lookup) console.log(“code: %s name: %s“, key, lookup[key]); for/of loops do not currently work with JSON objects

60 map with Arrays result3=list.map( x => x*x*x ); [1,8, 27, 64]
result1=list.map(Math.sqrt); [ 1, , , 2 ] result2=list.map(function(x) { return x*x;}); [ 1, 4, 9, 16 ] result3=list.map( x => x*x*x ); [1,8, 27, 64] map is a method associated with any array. map’s argument is a function. You can use a built in function or one that you wrote. The mapped function is then automatically applied to elements of the list.

61 list.filter(predicateFunction)
function isOdd(n) { return n%2;} list.filter(isOdd); [1, 57, 3, 9] Alternatively: list.filter(function(n) { return n%s; } Or: list.filter( x => x%2); filter selects a those items in a list that matches the predicate function.

62 list.reduce(function n, initialValue)
list=[1,2,3,4,5,8]; function sum(previous, current, index, originalList) { return previous + current; } list.reduce(sum,0); result: 23 Or: list.reduce( (prev, current) => previous+current); reduce reduces a list to a single value. The arguments in blue are optional and can be used to trace execution.

63 Fetch – a special case of Promise
The fetch method was introduced in It allows JavaScript to read a remote file asynchronously. (Reading local files is not allowed for security reasons.) fetch is implemented using promises. function getData(response) { return response.text(); } function handleResult(text) { //do something with the text } fetch(url).then(getData).then(handleResult);

64 Promises (asynchronous execution)
myPromise = Promise.resolve(aSlowFunction(x,y,z))

65 JavaScript Classes Prior to ECMAScript 6 classes were implemented in JavaScript by declaring a function and embedding other functions inside of them. Creating static class methods involved using the keyword prototype. The notation was confusing and time consuming to learn, so we never covered it in CENG256. The new syntax using the keyword “class” is simpler and closer to Java.

66 JavaScript Classes class Person { constructor(name, age) { this.name=name; this.age=age; } toString() { return name+’ is ‘ + age + ‘ years old’; } get name() { return name; } set name(name) { this.name=name;} } bob=new Person(“Robert”,22);

67 Another Class class Clown { var memberVariable; static classVariable; constructor(name,noseColor=red) { this.name=name; this.noseColor=noseColor; } funny(a,b,c) { var counter; … } get nose() { return this.nose; } set nose(clownNose) { this.nose=clownNose; } bobo=new Clown(“Bobo Fett”); The above notation is new to ECMAScript 6. The syntax for classes in JavaScript 5 was very different and difficult to learn. Because this is very similar to Java I’m including this slide – we may or may not use it.

68 instanceof instanceof is used to test if a variable belongs to a particular class of object if(bob instanceof Person) { …} if(myDate instanceof Date) { ….}

69 Regular Expressions

70 Regular Expressions Regular expressions are directly part of the language regExpr=/([a-z]+)/gi; //Match all runs of at least //1 alphabetic character “The rain, in Spain!”.match(regExpr) [“The”, “rain”, “in”, “Spain”] anyString.test(/regular expr/modifiers) Returns true or false anyString.search(/regular expr/modifiers) Returns the position of the 1st match

71 What you learned in “Unix and the Internet” about regular expressions can be applied in JavaScript for doing complex search and replace. You can practice in any browser console string=‘Hello World. Have a nice day, world!’; string.replace(/World/ig,’Canada’); ‘Hello Canada. Have a nice day, Canada!’; result=str.replace(/[aeiou]/g,’*’); //result is ‘H*ll* C*n*d*. H*v* * n*c* d*y!’;

72 DOM: The Document Object Model

73 window as an Object (document Properties
window.document The current document window.history The history object window.innerHeight, window.innerWidth The current window’s size Window.navigator Information about the browser Window.console Gives one a handle on the console object Window.location The current URL (can be reset) Window.screenX, window.screenY Position on the screen. Also methods moveTo and moveBy window.frames Used with framesets where the window can have multiple frames

74 document as an Object (document Properties
document.cookie A list of all cookies sent to the document as name/value pairs document.links An array of all links in the document document.anchors An array of all images in the document document.forms An array of all forms in the document document.images

75 Javascript code is triggered by “events”
Document Events onload, onunload Mouse Events onclick, ondblclick onmousedown, onmouseup onmousemove, onmouseover, onmouseout Key Events onkeypress, onkeydown, onkeyup Form Events onfocus, onblur, onselect, onchange onsubmit, onreset New events proposed Jan 2010 in HTML5

76 In 2010 HTML5 Introduced More Events
Clipboard Events oncopy, oncut, onpaste Mouse Events oncontextmenu, onwheel Touch Events ontouchcancel, ontouchstart, ontouchmove, ontouchend Drag Events (drag and drop) ondrag, ondrop, ... (more) Print Events onbeforeprint, onafterprint Form Events oninput, oninvalid, onsearch Animation Events animationstart, animationend, animationiteration Media Events onpause, onplay, onseeking, onsuspend, onvolumechange.... (and many more) for a complete list and reference:

77 getElementByID(‘idvalue’) (retrieves a single node)
<button onclick='javascript: result=prompt("Enter your name","Default"); display=document.getElementById("disp"); display.innerHTML=result;'> <tag id=disp>Result will show here</tag> the assigned innerHTML can include new HTML tags – they get added to your document this is a fundamental technique for manipulating the DOM.

78 document.getElementById(id)
DOM: The Document Object Model We’ll use this function a lot to get a handle on a specific tag. But to make it more readable we’ll put it into functions that reflect it’s use: function setMessage(id,msg) { element=document.getElementById(id); element.innerHTML=msg; } function getMessage(id,msg) { element=document.getElementById(id); return element.innerHTML; } <p id='when' onclick='setMessage("when",Date())' onmouseout='alert(getMessage("when"));' > Click for time</p>

79 document.getElementsByTagName(tag)
Returns an HTMLCollection that you can loop through, ie: tags=document.getElementsByTagName(‘A’); for(i=0;i<tags.length;i++) console.log(tags[i],tags[i].href);

80 document.getElementsByClassName(class)
Returns an HTMLCollection that you can loop through, ie: elem=document.getElementsByClassName(‘Humber’); for(i=0;i<elem.length;i++) console.log(elem[i],elem[i].id);

81 document.getElementsByName(name)
Returns a NodeList that you can loop through. In this case you select by the name field, usually of a form input. Unlike IDs, names are not unique, ie radiobuttons share the same name. NodeLists and HTMLCollections are very similar. nodes=document.getElementsByName(‘student’); for(i=0;i<nodes.length;i++) console.log(nodes[i],nodes[i].nodes);

82 Querying By Selector Selectors can not only be used to apply CSS properties, they can also be used to acquire either a single node or a NodeList. Examples of selectors are: Tag names: A IMG INPUT DIV NAV * (every tag) Tag ids: #empNam #sensor5 Class names: .Humber .Advisory Attributes IMG[width=50][height=75] A list of selectors: A, #emNam, .Advisory A hierarchy of selectors: OL LI B (bold text in a LI in an ordered list) A mix of the above

83 document.querySelector(selector)
Returns a single node, the first one that matches your selector node=document.querySelector(‘#myID’); Node.onclick=function() {console.log(“Hi”);};

84 document.querySelectorAll(selector)
Returns an NodeList of all the tags that match the selector. nodes=document.querySelectorAll(‘A, img’); for(i=0;i<nodes.length;i++) console.log(nodes[i],nodes[i].tagName==“A” ? nodes[i].href: nodes[i].src); Grabs all anchor and image nodes, prints out the hyperlink to the tag.

85 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

86 JQuery

87 $ JQuery is a library of functions that all derive from a single function $. You can also write it as JQuery(), but no-one actually does. $(selector) returns a lists of elements that match the selector.

88 $ With JQuery you rarely have to write loops
$(selector).text(“new text”); Sets the innerText of all matching selectors. $(selector).text(); Retrieves innerText of the first item selected $(selector).html(‘<b><ol><li>one<li>two</ol></b>’); Sets all of the innerHTML $(selector).html() Retrieves innerHTML of the 1st item selected

89 $ Similarly $(selector).css(‘text-color’, ‘red’); $(selector).text();
Sets the innerText of all matching selectors. $(selector).text(); Retrieves innerText of the first item selected $(selector).html(‘<b><ol><li>one<li>two</ol></b>’); Sets all of the innerHTML $(selector).html() Retrieves innerHTML of the 1st item selected

90 $ JQuery is a library of functions that all derive from a single function $. You can also write it as JQuery(), but no-one actually does. $(selector) returns a lists of elements that match the selector.

91 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

92 Element.attributes <p id='when' onclick=“setMessage(‘when’,Date())” onmouseout='alert(getMessage("when"));' name=Fred > Click for time</p> element=document.getElementById(‘when’); attribs=element.attributes;

93 For this course use <script type="text/javascript" src="utilities.js"> (this is available from the directory:

94 Modifiable Tag Properties
innerHTML <tag id=‘t1’>This can be modified</tag> change text contents value <input id=‘t1’ type=‘text’ value=‘Fred’ /> change a form value src <img id=‘t1’ src=‘myImage.jpg’ /> replace or set an image href <a href=‘ibm.com’> </a> alter a hypertext link checked <input type=checkbox checked=checked> alter/check checkbox or radio button style <h1 style=“color:red” > .... alter/retrieve style info className <h1 class=‘Humber’ id=‘tagID’ name=‘fieldName’ > alter/retrieve class, id or name info name retrieve/alter element name element=document.getElementById(name); element.innerHTML=‘<b>any text can be inserted’; element.src=‘otherImage.jpg’ element.href=newLocation element.checked=true; element.style=‘color:green’; element.className=‘Seneca’; //Note: not class, className!

95 Modifiable style Properties
CSS Name JavaScript Name Purpose color e.style.color=“red” background-color backgroundColor e.style.backgroundColor=“rgb(0,100,200)” font-size fontSize e.style.fontSize=32 margin-left marginLeft e.style.marginLeft=“20%” List-style-image listStyleImage e.style.listStyleImage=“url(‘bsdemon.jpg’)” The full list is huge. Generally one takes the style name and uses it in camelCaps. If the style name has an embedded dash – remove it as JavaScript would see it as a subtraction symbol. See:

96 Retrieve All Tags of a Given Type
function displayPictureNames() { images=document.getElementsByTagName("img"); for(id in images) if(images[id].alt==undefined) continue; alert(id + ' ' + images[id].src); images } }

97 Manipulating DOM Structure

98 document.createElement
This function creates a new node which can then be inserted into the document: newList=createElement(“ol”); newPara=createElement(“li”);

99 document.createAttribute
This creates a new attribute which we can then add to our element. If we had to do a lot of them this could take some time…..

100 So…… Wait for next week….

101 The Console helps debug code

102 Advanced Features

103 The with statement with (Math) { a = PI * r*r; y = r*sin(theta); x = r*cos(theta) b = a + y/x; } with (myCar) { setModel(‘Escape’); display(); } The idea is similar to with in VBA

104 try/catch block try { badFunctionCall(); or other code that fails or throw “Oops! I did something stupid!”; } catch(mistake) { console.log(mistake.message); }

105 More on this this can also be used to refer to the current tag in an inline script <input id=myTag name=Bob ondrag=“alert(this.id+”:”+this.name);” type=input width=10 >

106 void void is used to ensure that an expression doesn’t return a value: void i++; //i is incremented, but the line does //not return a value void is often used to signify that an event doesn’t propagate <input type=button onclick=“javascript:void(0)” value=‘Do Nothing’>

107 Extra Slides These are slides that I intend to reposition in the presentation. Or I could eventually delete them.

108 Refering to an external file of functions
<script type="text/javascript" language="javascript" src="hello.js"> <script type=="text/javascript" language="javascript" src=“jquery min.js"> "double", 'single'

109 Dictionaries (JSON) lookup={'John' : '27 Queen Street',
'Harry Potter' : '18 Privet Drive', 'Sherlock Holmes' : '221 Baker Street'}; console.log(lookup); the above javascript object notation dictionary will be output console.log(lookup.John) Queen Street console.log(lookup['Harry Potter']); Privet Drive //Array notation must be used if the key contains special chars //If key’s string follows the rules for a variable name, dot notation will work "double", 'single'

110 A Dictionary can Contain Anything!
classList= {'Sam' : {course: 'CENG256', midterm: 79, exam: 83, assignments: [18.25,undefined,27,18.5,21.25]}, 'Raina' : {course: 'CENG255', midterm: 63, exam: 77, assignments: [24.5, 21, 18, 29, 25.5]} } console.log("Midterm Test: %5.2f%%", classList['Raina'].midterm) Console.log(“Assignment 1 %6.2f”, classList[‘Sam’].assignments[0]) JSON encoded strings are a popular way to send structured data between applications. JSON is also used to encode NOSQL style databases such as CouchDB and MongoDB.

111 JSON stringify and parse
myString=JSON.stringify(anyDictionary); myDictionary=JSON.parse(myString) The stringify function converts a dictionary into a readable string. The parse function converts a quoted string (in the right format) into a dictionary. This is used to move date between client and server.

112 Scope Rules 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

113 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); //Output Banana Orange,Apple,Mango Apple,Mango Banana,Orange,Apple,Mango Example taken from W3Schools.com

114 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

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


Download ppt "Introducing JavaScript 2020 Edition"

Similar presentations


Ads by Google