Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to JavaScript & DOM. JavaScript Outline Introduction Variables & data types Control statements Arrays Functions Objects.

Similar presentations


Presentation on theme: "Intro to JavaScript & DOM. JavaScript Outline Introduction Variables & data types Control statements Arrays Functions Objects."— Presentation transcript:

1 Intro to JavaScript & DOM

2 JavaScript Outline Introduction Variables & data types Control statements Arrays Functions Objects

3 JavaScript Quick facts Netscape was battling with IE and wanted a lightweight component to compete with Microsoft VB. Created by Brendan Eich (creator of Mozilla Foundation) in 1995 while at Netscape. CSE 33453

4 JavaScript Quick facts JavaScript was described by Brendan as, “something that had to ‘look like Java’ only less so and be Java’s dumb kid brother or boy- hostage sidekick.” Had to be created in 10 days, or something worse would have been developed. CSE 33454

5 JavaScript Disclaimer A lot of people hate JavaScript! A lot of the people that hate JavaScript really just don’t understand it. There are good parts and bad parts. CSE 33455

6 3 Ways Use JS Inline Embedded External CSE 33456

7 Inline Example Click me CSE 33457

8 Embedded Example window.onload = function() { alert('window loaded'); }; CSE 33458

9 External Example index.html tag; else your script might not load --> test.js window.onload = function() { alert('window loaded'); }; CSE 33459

10 Same as CSS Reasons to use each method are the same as CSS. External is preferred! CSE 334510

11 JS characteristics It is a dynamic and weakly typed language. Dynamic type means that there are no compile time checks to deduce variable type and type conversions. Weakly typed mean the language will figure out for itself how to convert variables of different type. CSE 334511

12 Strongly Typed Example Test.java: public class Test { public static void main(String args[]) { String x = "2"; int num = 7; num += x;// Integer.parseInt(x); System.out.println(num); } Test.java:6: error: inconvertible types num += x;// Integer.parseInt(x); ^ required: int found: String 1 error CSE 334512

13 Weakly Typed Example var x = "2"; var num = 7; num += x; console.log(num); //72 CSE 334513

14 Outputting text to the console The web console provides a heads up display for the web by letting users see error messages and other logged information. console.log() – Outputs a message to the web console. Extremely useful for debugging!

15 Outputting text to the console Print strings console.log(“Hello “ + “world!”); Print objects var foo = ‘hello’; var bar = 0x01; console.log(foo + “ “ + bar + “!”);

16 JavaScript Outline Introduction Variables & data types Control Statements Arrays Functions Objects

17 Declaring variables Variables are declared using the var keyword. JavaScript does not allow variables to be declared with a specific type (int, float, boolean, etc). JavaScript does have different data types

18 JavaScript types typeof 4; // number typeof 0xFF; // number typeof x; // undefined typeof true; // boolean typeof "String"; // string typeof {}; // object typeof [] ; // object typeof function() { alert("hi!"); }; // function

19 To var, or not to var? Any variable declared without the var keyword becomes a global variable. That means un-varred variables in methods automatically are global. CSE 334519

20 Truthy and falsy values Any value can be converted to a boolean according to the following rules: 1.false, 0, the empty string (“”), NaN, null, and undefined all become false. 2.All other values become true. CSE 334520

21 Truth and Falsy in Action var c = (false == 0); // true var d = (false == ""); // true var e = (0 == ""); // true //null and undefined are only equal to themselves and each other var f = (null == false); // false var g = (null == null); // true var h = (undefined == undefined); // true var i = (undefined == null); // true //NaN is not equivalent to anything var j = (NaN == null); // false var k = (NaN == NaN); // false CSE 334521

22 Comparing for equality The Equals operator is ==. Compares “truthy” and “falsy” values of variables. Strict equals operator is ===. Always returns false when the operands are of different types. CSE 334522

23 Always use === To avoid unintended results, always use the strict equals operator. CSE 334523

24 String operators Use the + operator to concatenate two strings together. var x = “hello” + “ world”; Use the += operators to append two existing strings. var x = “hello”; x += “ world”; CSE 334524

25 Converting strings to numbers parseInt() – parses a string object and returns an integer of the specified radix or base. You should always specify a base. – parseInt(“010”, 2); // 2 – parseInt(“010”, 10); // 10 parseFloat() – parses a string object and returns a floating point number. Always uses base 10. – parseFloat(“10.44”); //10.44 CSE 334525

26 Converting strings to numbers You can also prepend a string with a + to convert the string to a number. var string = "50"; console.log(string + 100); // 50100 console.log(+string + 100); // 150 CSE 334526

27 JavaScript Outline Introduction Variables & data types Control Statements Arrays Functions Objects

28 Control Statements JavaScript supports the typical list of control statements. 1.if, else, else if 2.while 3.do while 4.for 5.switch 6.break 7.continue CSE 334528

29 Control Statements In addition to that list, js has a “for in” statement. Use it to iterate over properties of an object. Be careful using “for in” for arrays. Sometimes an object will have properties that you’re unaware of and give weird output. CSE 334529

30 For in example // Initialize object. a = {"a" : "Athens", "b" : "Belgrade", "c" : "Cairo"} ; // Iterate over the properties. var s = "“; for (var key in a) { s += key + ": " + a[key]; s += " "; } document.write (s); // Output: // a: Athens // b: Belgrade // c: Cairo CSE 334530

31 Bad Part of JavaScript Always place an opening brace “{“ on the same line as the control statement or function. Undesired results can occur if you don’t follow this practice. See here for detailshere CSE 334531

32 JavaScript Outline Introduction Variables & data types Control Statements Arrays Functions Objects

33 Arrays Arrays are a special type of object that have a length property. Accessing a value that is outside of the array bounds returns undefined. The length property returns the length of the array. The length is also one more than the highest index. The length of an array isn’t always the number of items in the array. CSE 334533

34 Array Length Bad Part var x = ["dog", "cat", "monkey"]; x.length; //3 x[100] = "aligator"; x.length; //101 CSE 334534

35 Bad Array Initialization > var a = new Array(); > a[0] = "dog"; > a[1] = "cat"; > a[2] = "hen"; > a.length 3 > var a = new Array(); //bad CSE 334535

36 Good Array Initialization > var a = ["dog", "cat", "hen"]; > a.length 3 > var a = []; //good CSE 334536

37 Array Methods Method nameDescription a.toString() a.toLocaleString() a.concat(item[, itemN])Returns a new array with the items added on to it. a.join(sep) a.pop()Removes and returns the last item. a.push(item[, itemN])Push adds one or more items to the end. a.reverse() a.shift() a.slice(start, end)Returns a sub-array. a.sort([cmpfn])Takes an optional comparison function. a.splice(start, delcount[, itemN]) Lets you modify an array by deleting a section and replacing it with more items. a.unshift([item])Prepends items to the start of the array. CSE 334537

38 JavaScript Outline Introduction Variables & data types Control Statements Arrays Functions Objects

39 Functions Almost like typical C/C++ and Java functions, except you don’t specify a return type. function sayHello() { alert(“hello world!”); } CSE 334539

40 Function with parameters Once again similar to C/C++ and Java, but you don’t specify the data type of the parameters. You also don’t prefix the parameter name with the var keyword. function add(x, y) { return x + y; } CSE 334540

41 The arguments object The arguments object is a local variable available within all functions that contains an entry for each argument passed to a function. The arguments object will also hold values for parameters that are specified by the function. CSE 334541

42 Arguments object example function concat(parm1) { var str = parm1; for (var i = 0, len = arguments.length; i < len; i++) { str += " " + arguments[i]; } return str; } concat("1", "2", "3", "4"); // "1 1 2 3 4” CSE 334542

43 Anonymous Function You can create functions that are not bounded to an identifier. alert((function(){return "hello";})()); CSE 334543

44 Functions are first class objects This means that JavaScript functions are just a special type of object that can do all things regular objects can do. This allows 1.Functions to be stored as variables 2.Functions to be passed as a parameter to another function. 3.You can return a function from another function. CSE 334544

45 Functions stored as variables function sayHi() {console.log(“hi”); } var hi = sayHi; hi(); // hi Note that when assigning a function to a variable, you don’t place “()” after the function name. However, to execute the function with the variable name, you must use “()”. CSE 334545

46 Function as a parameter of another function function sayHi() { return "hi";} function salutation(greeting, name) { console.log(greeting() + " " + name); } var hi = sayHi; salutation(hi, "Fred"); // hi Fred CSE 334546

47 Function as a return value for another function function add(x,y) { return x + y; } function subtract(x,y) { return x - y; } function getOperation(x) { var operation = x % 2 === 0 ? add : subtract; return operation; } var operation = getOperation(2); operation(5,3); // 8 CSE 334547

48 JavaScript Outline Introduction Variables & data types Control Statements Arrays Functions Objects

49 Objects are a collection of name-value pairs The “name” part is a JavaScript string. The “value” part can be any JavaScript value. CSE 334549

50 Creating Objects var student = { name: "Wade Wilson", alias: "wwilson", id: 12345678, email: "wwilson@smu.edu", isPassing: true }; CSE 334550

51 Object member variables are public There are no access level modifiers (public, protected, private) to prevent access to an object’s variables. student.name; //"Wade Wilson" student.alias; //"wwilson" student.id; //12345678 student.email; //"wwilson@smu.edu" student.isPassing; //true CSE 334551

52 Object member variables are public Using the object literal syntax, we can access variables a second way. student["name"]; //"Wade Wilson" student["alias"]; //"wwilson" student["id"]; //12345678 student["email"]; //"wwilson@smu.edu" student["isPassing"]; //true This approach makes it possible to calculate the member variable at run-time with a dynamic string. CSE 334552

53 Object Methods var student = { name: "Wade Wilson", alias: "wwilson", id: 12345678, email: "wwilson@smu.edu", isPassing: true, sayHi: function() {console.log("hi");} }; student.sayHi(); //”hi” CSE 334553

54 Your turn Create a function to print each pattern * ********** CSE 334554

55 DOM

56 Intro to JavaScript DOM – About – Tree / nodes – Accessing elements – Creating elements – Deleting element

57 Quick facts DOM – document object model Is a cross-platform language agnostic convention for representing HTML, XHTML, and XML documents. Think of the DOM as a family tree which represents a document. The DOM represents the document as a structured group of nodes/objects that have properties and methods.

58 HTML to DOM Tree DOM Test I am some text. CSE 334558 HTML HEADBODY TITLE P style class: text color: red

59 HTML to DOM Tree CSE 334559 HTML HEADBODY TITLE P style class: text color: red document

60 Live DOM Viewer Visit the Live DOM Viewer to see the DOM in action.Live DOM Viewer CSE 334560

61 DOM API API – application programming interface Provides capabilities to change a document’s structure, style, and content. In the DOM, everything in the document becomes nodes (elements, text, attributes, comments, etc) and forms a node tree. CSE 334561

62 Getting access to the DOM from JS Each webpage loaded in the browser has its own document object. The document object serves as the entry point to the web page’s content aka the DOM tree. CSE 334562

63 How to access the DOM in js //JavaScript code //this returns an array of all the div elements in //the HTML document. var divs = document.getElementsByTagName("div"); CSE 334563

64 DOM API Allows developers to access nodes in the DOM Tree. Each node is actually a JavaScript object. Therefore, each object can have properties and methods CSE 334564

65 A few DOM traversing methods getElementByID(id) – get the element with the specified id or null if an element wasn’t found. getElementsByTagName(tag) – returns an array of all elements with the specified tag. getElementsByClassName(class) – returns an array of all elements which have the given class name. CSE 334565

66 Node Properties CSE 334566 HTML HEADBODY TITLE P style class: text color: red document

67 A few node Properties innerHTML – the textual value of the node nodeName – the name of the node nodeValue – the value of the node parentNode - the parent node of the node childNodes – the child nodes of the node attributes – the attributes of the node firstChild – the first child of the node nextSibling- the next sibling of the node CSE 334567

68 nodeValue nodeValue can return different things depending on what the node is Attribute – the value will be the value of the attribute. Text – the value will be the text content Element – the value will be null CSE 334568

69 Node Trees All nodes in the tree can be accessed and their contents can be modified or deleted. New nodes can be created and inserted into the tree. CSE 334569

70 DOM manipulation methods removeChild(node) – remove a child node from the current node. createElement(element) – create an element node of the specified type. appendChild(node) – insert a child node to the current node. setAttribute(name, value) – set a new attribute with the specified name and value to this node. CSE 334570

71 Using the DOM API We can navigate to any section of the DOM tree by using properties. – firstChild – lastChild – nextSibling – previousSibling Once we’ve found the node we want, we can set almost any HTML attribute or data attribute and CSS property. CSE 334571

72 Using DOM to change HTML Use the properties of each node to change specific things – innerHTML – setAttribute() CSE 334572

73 Using DOM to change CSS Each element node has a style property. Using style, you change specific CSS properties for the element’s inline style. Note this will not fetch CSS from embedded or external declarations. CSE 334573

74 DOM CSS Example //changes the body element's inline color style to be red document.body.style.color = "red"; CSE 334574

75 DOM References Sitepoint Use the intellisense feature of Chrome Web Inspector to find available methods and properties. CSE 334575

76 DOM Example http://cssdeck.com/labs/collab/knejnp4j/0 http://jsfiddle.net/blinkmacalahan/vfVM6/6/ CSE 334576


Download ppt "Intro to JavaScript & DOM. JavaScript Outline Introduction Variables & data types Control statements Arrays Functions Objects."

Similar presentations


Ads by Google