Presentation is loading. Please wait.

Presentation is loading. Please wait.

MIT GSL 2018 week 1 | day 2 JavaScript II.

Similar presentations


Presentation on theme: "MIT GSL 2018 week 1 | day 2 JavaScript II."— Presentation transcript:

1 MIT GSL 2018 week 1 | day 2 JavaScript II

2 Today’s Agenda Overview of Today’s Content
Review of Previous Day’s Content Lecture Topic JavaScript 2 Activity Review of Day 1 Exercises Day 2 Exercises Wrap-Up

3 JavaScript II

4 Web Development “Behavior” “Content” “Style”

5 JavaScript Topics for Today
Variables Functions Objects this Loop & Conditions Scope Arrays, String and Number Methods Event Handling Dates & Times Class - constructor, extends jQuery, AJAX & JSON

6 Any Questions So Far?

7 Loops let i = 3; while (i) { // when i becomes 0, the condition becomes false, and the loop stops alert( i ); i--; }

8 Loops - In class example
Create a while loop that adds all the numbers from 1 to 10

9 Loops let i = 0; do { alert( i ); i++; } while (i < 3);

10 Loops - In class example
Create a do_while loop that adds all the odd numbers from 1 to 10

11 Loops for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2 alert(i); }

12 Loops let i = 3; while (i) { // when i becomes 0, the condition becomes false, and the loop stops alert( i ); i--; } ****************************************************************** let i = 0; do { alert( i ); i++; } while (i < 3); for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2 alert(i); }

13 Loops - What does this function do?
let sum = 0; while (true) { let value = +prompt("Enter a number", ''); if (!value) break; // (*) sum += value; } alert( 'Sum: ' + sum );

14 Loops - What does this function do?
for (let i = 0; i < 10; i++) { if (i % 2 == 0) continue; alert(i); }

15 Arrays let arr = new Array(); let arr = [];
let fruits = ["Apple", "Orange", "Plum"];

16 Arrays let fruits = ["Apple", "Orange", "Plum"];
alert( fruits[0] ); // Apple alert( fruits[1] ); // Orange alert( fruits[2] ); // Plum fruits[2] = 'Pear'; // now ["Apple", "Orange", "Pear"] fruits[3] = 'Lemon'; // now ["Apple", "Orange", "Pear", "Lemon"] alert( fruits.length ); // 4

17 Arrays let arr = [ 'Apple', { name: 'John' }, true, function() { alert('hello'); } ];// mix of values // get the object at index 1 and then show its name alert( arr[1].name ); // John // get the function at index 3 and run it arr[3](); // hello

18 Arrays let fruits = ["Apple", "Orange", "Plum"]; for (let fruit of fruits) {// iterates over array elements alert( fruit ); } \\for (let i=0; i<arr.length; i++) - could also use this method

19 Arrays let matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; alert( matrix[1][1] ); // the central element //Arrays can have be multi dimensional

20 Arrays Can be treated as a queue(an ordered list of elements) using two sets methods (pop/push & shift/unshift) Stacks - LIFO(Last-In-First-Out) Queues - FIFO(First-In-First-Out) arr.push(...items) – adds items to the end, arr.pop() – extracts an item from the end, arr.shift() – extracts an item from the beginning, arr.unshift(...items) – adds items to the beginning

21 Array Methods let arr = [1, 2, 3]; alert( arr ); // 1,2,3
alert( String(arr) === '1,2,3' ); // true - arrays have their own toString function

22 Array Methods \\ arr.splice(str) method is a swiss army knife for arrays. It can do everything: add, remove and insert elements let arr = ["I", "study", "JavaScript"]; arr.splice(1, 1); // from index 1 remove 1 element alert( arr ); // ["I", "JavaScript"] ************************************************************* let arr = ["I", "study", "JavaScript", "right", "now"]; // remove 3 first elements and replace them with another arr.splice(0, 3, "Let's", "dance"); alert( arr ) // now ["Let's", "dance", "right", "now"]

23 Array Methods - What does this block of code do?
let arr = ["I", "study", "JavaScript"]; arr.splice(2, 0, "complex", "language"); alert( arr );

24 Array Methods - What does this block of code do?
let arr = ["I", "study", "JavaScript"]; // from index 2, delete 0 // then insert "complex" and "language" arr.splice(2, 0, "complex", "language"); alert( arr ); // "I", "study", "complex", "language", "JavaScript"

25 Array Methods slice(start, end) – creates a new array, copies elements from position start till end (not inclusive) into it. concat(...items) – returns a new array: copies all members of the current one and adds items to it. If any of items is an array, then its elements are taken. To search among elements: indexOf/lastIndexOf(item, pos) – look for item starting from position pos, return the index or -1 if not found. includes(value) – returns true if the array has value, otherwise false. find/filter(func) – filter elements through the function, return first/all values that make it return true. findIndex is like find, but returns the index instead of a value.

26 Array Methods To transform the array: map(func) – creates a new array from results of calling func for every element. sort(func) – sorts the array in-place, then returns it. reverse() – reverses the array in-place, then returns it. split/join – convert a string to array and back. reduce(func, initial) – calculate a single value over the array by calling func for each element and passing an intermediate result between the calls. To iterate over elements: forEach(func) – calls func for every element, does not return anything. Additionally: Array.isArray(arr) checks arr for being an array

27 Array - In class exercise
Let’s try 5 array operations. Create an array styles with items “Jazz” and “Blues”. Append “Rock-n-Roll” to the end. Replace the value in the middle by “Classics”. Your code for finding the middle value should work for any arrays with odd length. Strip off the first value of the array and show it. Prepend Rap and Reggae to the array. The array in the process: Jazz, Blues Jazz, Bues, Rock-n-Roll Jazz, Classics, Rock-n-Roll Classics, Rock-n-Roll Rap, Reggae, Classics, Rock-n-Roll

28 Array - In class exercise
Let’s try 5 array operations. Create an array styles with items “Jazz” and “Blues”.

29 Array - In class exercise
Let’s try 5 array operations. Create an array styles with items “Jazz” and “Blues”. styles = ["Jazz", "Blues"]; Append “Rock-n-Roll” to the end.

30 Array - In class exercise
Let’s try 5 array operations. Create an array styles with items “Jazz” and “Blues”. styles = ["Jazz", "Blues"]; Append “Rock-n-Roll” to the end. styles.push("Rock-n-Roll"); Replace the value in the middle by “Classics”. Your code for finding the middle value should work for any arrays with odd length.

31 Array - In class exercise
Let’s try 5 array operations. Create an array styles with items “Jazz” and “Blues”. styles = ["Jazz", "Blues"]; Append “Rock-n-Roll” to the end. styles.push("Rock-n-Roll"); Replace the value in the middle by “Classics”. Your code for finding the middle value should work for any arrays with odd length. styles[Math.floor((styles.length - 1) / 2)] = "Classics"; Strip off the first value of the array and show it.

32 Array - In class exercise
Let’s try 5 array operations. Create an array styles with items “Jazz” and “Blues”. styles = ["Jazz", "Blues"]; Append “Rock-n-Roll” to the end. styles.push("Rock-n-Roll"); Replace the value in the middle by “Classics”. Your code for finding the middle value should work for any arrays with odd length. styles[Math.floor((styles.length - 1) / 2)] = "Classics"; Strip off the first value of the array and show it. alert( styles.shift() ); Prepend Rap and Reggae to the array.

33 Array - In class exercise
Let’s try 5 array operations. Create an array styles with items “Jazz” and “Blues”. styles = ["Jazz", "Blues"]; Append “Rock-n-Roll” to the end. styles.push("Rock-n-Roll"); Replace the value in the middle by “Classics”. Your code for finding the middle value should work for any arrays with odd length. styles[Math.floor((styles.length - 1) / 2)] = "Classics"; Strip off the first value of the array and show it. alert( styles.shift() ); Prepend Rap and Reggae to the array. styles.unshift("Rap", "Reggie");

34 String Methods alert( "Hello\nWorld" ); // two lines using a "newline symbol" // two lines using a normal newline and backticks alert( `Hello World` ); ******************************************************************** alert( `The backslash: \\` ); // The backslash: \ alert( `I'm the Walrus!` ); // I'm the Walrus! alert( `My\n`.length ); // 3

35 String Methods let str = `Hello`; // the first character alert( str[0] ); // H alert( str.charAt(0) ); // H // the last character alert( str[str.length - 1] ); // o ******************************************************************** let str = `Hello`; alert( str[1000] ); // undefined alert( str.charAt(1000) ); // '' (an empty string)

36 String Methods for (let char of "Hello") { alert(char); // H,e,l,l,o (char becomes "H", then "e", then "l" etc) } ******************************************************************** let str = 'Hi';//Strings are immutable str = 'h' + str[1]; // replace the string alert( str ); // hi

37 String Methods To get a character, use: [].
To get a substring, use: slice(start [, end]) or substring(start [, end]). To lowercase/uppercase a string, use: toLowerCase/toUpperCase. To look for a substring, use: indexOf, or includes/startsWith/endsWith for simple checks. To compare strings according to the language, use: localeCompare, otherwise they are compared by character codes str.trim() – removes (“trims”) spaces from the beginning and end of the string. str.repeat(n) – repeats the string n times.

38 Number Methods alert( 0xff ); // 255
let a = 0b ; // binary form of 255 let b = 0o377; // octal form of 255 alert( a == b ); // true, the same number 255 at both sides ********************************************************************************** alert( isNaN(NaN) ); // true alert( isNaN("str") ); // true alert( NaN === NaN ); // false alert( isFinite("15") ); // true alert( isFinite("str") ); // false, because a special value: NaN alert( isFinite(Infinity) ); // false, because a special value: Infinity

39 Number Methods parseInt(str, base) - parses an integer from any numeral system with base: 2 ≤ base ≤ 36. num.toString(base) - converts a number to a string in the numeral system with the given base. Round using Math.floor, Math.ceil, Math.trunc, Math.round or num.toFixed(precision) Use parseInt/parseFloat for the “soft” conversion, which reads a number from a string and then returns the value they could read before the error Math.random() - Returns a random number from 0 to 1 (not including 1) Math.max(a, b, c...) / Math.min(a, b, c...) Math.pow(n, power) - Returns n raised the given power

40 Dates and time now = new Date(); alert( now ); // shows current date/time ********************************************************************************** new Date(milliseconds) - Create a Date object with the time equal to number of milliseconds (1/1000 of a second) passed after the Jan 1st of 1970 UTC+0 let date = new Date(" "); alert(date); // Tue June … **********************************************************************************new Date(year, month, date, hours, minutes, seconds, ms) - Create the date with the given components in the local time zone. Only two first arguments are obligatory.

41 Dates and time getFullYear() - Get the year (4 digits) getMonth() - Get the month, from 0 to 11. getDate() - Get the day of month, from 1 to 31, the name of the method does look a little bit strange. getHours(), getMinutes(), getSeconds(), getMilliseconds() - Get the corresponding time components. getDay() - Get the day of week, from 0 (Sunday) to 6 (Saturday) All of the above in local time, but can make UTC, just insert the "UTC" right after "get" getTime() - Returns the timestamp for the date – a number of milliseconds passed from the January 1st of 1970 UTC+0. getTimezoneOffset() - Returns the difference between the local time zone and UTC, in minutes

42 Dates and time - Exercise
Create a Date object for the date: Feb 20, 2012, 3:12am. The time zone is local. Show it using alert

43 Dates and time - Exercise
The new Date constructor uses the local time zone by default. So the only important thing to remember is that months start from zero. So February has number 1. d = new Date(2012, 1, 20, 3, 12); alert( d );

44 Dates and time - Exercise
Write a function getLastDayOfMonth(year, month) that returns the last day of month. Sometimes it is 30th, 31st or even 28/29th for Feb. Parameters: year – four-digits year, for instance 2012. month – month, from 0 to 11. For instance, getLastDayOfMonth(2012, 1) = 29 (leap year, Feb).

45 Dates and time - Exercise
Let’s create a date using the next month, but pass zero as the day: function getLastDayOfMonth(year, month) { let date = new Date(year, month + 1, 0); return date.getDate(); } alert( getLastDayOfMonth(2012, 0) ); // 31 alert( getLastDayOfMonth(2012, 1) ); // 29 alert( getLastDayOfMonth(2013, 1) ); // 28 Normally, dates start from 1, but technically we can pass any number, the date will auto adjust itself. So when we pass 0, then it means “one day before 1st day of the month”, in other words: “the last day of the previous month”.

46 Dates and time *Advanced*
setFullYear(year [, month, date]) setMonth(month [, date]) setDate(date) setHours(hour [, min, sec, ms]) setMinutes(min [, sec, ms]) setSeconds(sec [, ms]) setMilliseconds(ms) setTime(milliseconds) Every one of them except setTime() has a UTC-variant, for instance: setUTCHours() *Advanced*

47 this It’s common that an object method needs to access the information stored in the object to do its job. The value of this is evaluated during the run-time. And it can be anything

48 Dates and time *Advanced* Autocorrection
let date = new Date(2013, 0, 32); // 32 Jan 2013 ?!? alert(date); // ...is 1st Feb 2013! ********************************************************************************** Timestamp : Date.parse(str), str = ‘ YYYY-MM-DDTHH:mm:ss.sssZ’, where: YYYY-MM-DD – is the date: year-month-day. The character "T" is used as the delimiter. HH:mm:ss.sss – is the time: hours, minutes, seconds and milliseconds. The optional 'Z' part denotes the time zone in the format +-hh:mm. A single letter Z that would mean UTC+0 let ms = Date.parse(' T13:51: :00'); alert(ms); // (timestamp) *Advanced*

49 this var user = { name: "John", age: 30, sayHi() { alert(this.name); } }; user.sayHi(); // John var user = { name: "John", age: 30, sayHi() { alert( user.name ); // leads to an error } }; var admin = user; user = null; // overwrite to make things obvious admin.sayHi(); // Whoops! inside sayHi(), the old name is used! error!

50 Scope Each function creates a new scope. Scope determines the accessibility (visibility) of these variables. Variables defined inside a function are not accessible (visible) from outside the function - Local vs Global Scope myFunction(); // code here can use carName as a global variable //If you assign a value to a variable that has not been declared, it will become a GLOBAL variable document.getElementById("demo").innerHTML = "I can display " + carName; function myFunction() { carName = "Volvo"; }

51 Scope Each function creates a new scope. Scope determines the accessibility (visibility) of these variables. Variables defined inside a function are not accessible (visible) from outside the function - Local vs Global Scope myFunction(); document.getElementById("demo").innerHTML ="The type of carName is " + typeof carName; function myFunction() { //var makes carName undefined outside the function var carName = "Volvo"; }

52 Scope function showMessage() { let message = "Hello, I'm JavaScript!"; // local variable alert( message ); } showMessage(); // Hello, I'm JavaScript! alert( message ); // <-- Error! The variable is local to the function

53 Scope let userName = 'John'; function showMessage() { userName = "Bob"; // (1) changed the outer variable let message = 'Hello, ' + userName; alert(message); } alert( userName ); // John before the function call showMessage(); alert( userName ); // Bob, the value was modified by the function

54 Class In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods). Two main type of classes - functional class pattern or the prototypal pattern. The prototypal pattern is more powerful and memory-efficient, so it’s recommended to stick to it

55 Class function User(name, birthday) { // only visible from other methods inside User function calcAge() { return new Date().getFullYear() - birthday.getFullYear(); } this.sayHi = function() { alert(`${name}, age:${calcAge()}`); }; } let user = new User("John", new Date(2000, 0, 1)); user.sayHi(); // John, age:17 Functional class pattern In the functional pattern, each object has its own copy of every method. We assign a separate copy of this.sayHi = function() {...} and other methods in the constructor. *Advanced*

56 Class *Advanced* function User(name, birthday) { this._name = name; this._birthday = birthday; } User.prototype._calcAge = function() { return new Date().getFullYear() - this._birthday.getFullYear(); }; User.prototype.sayHi = function() { alert(`${this._name}, age:${this._calcAge()}`); }; let user = new User("John", new Date(2000, 0, 1)); user.sayHi(); // John, age:17 prototype class pattern In the prototypal pattern, all methods are in User.prototype that is shared between all user objects. An object itself only stores the data. The prototypal pattern is more memory-efficient and also allows us to setup the inheritance in a really efficient way. Built-in JavaScript objects all use prototypes.

57 Class - Syntax, Getters and Setters
class User { constructor(name, birthday) { // invokes the setter this.name = name; this.birthday = birthday } get name() { return this._name; } set name(value) { if (value.length < 4) { alert("Name is too short."); return; } this._name = value; } } let user = new User("John"); alert(user.name); // John user = new User(""); // Name too short Why do we use getters and setters?

58 Class - inheritance It is a mechanism where you can to derive a class from another class for a hierarchy of classes that share a set of attributes and methods Each class can only be derived from one other class. That class is called a superclass, or parent class. The derived class is called subclass, or child class

59 Class - inheritance Too much inheritance can be difficult to keep track of Useful for large projects when there is a need to create multiple objects of similar type

60 Class - inheritance In class example
If you wanted to create the objects: ice cream, coke, rolex, burger, spaghetti, sprite, fries, how could you use inheritance to help arrange these objects and reduce the amount of work you need to do?

61 Class - extends Used by the subclass or child class to define its relationship to its parent class

62 Class - extends class Animal { constructor(name) { this.speed = 0; this.name = name; } run(speed) { this.speed += speed; alert(`${this.name} runs with speed ${this.speed}.`); } stop() { this.speed = 0; alert(`${this.name} stopped.`); } }//********************************************* // Inherit from Animal class Rabbit extends Animal { hide() { alert(`${this.name} hides!`); } } let rabbit = new Rabbit("White Rabbit"); rabbit.run(5); // White Rabbit runs with speed 5. rabbit.hide(); // White Rabbit hides!

63 Class - super Used to access the methods or variables of the parent class

64 Class - super super.method(...) to call a parent method.
class Animal { constructor(name) { this.speed = 0; this.name = name; } run(speed) { this.speed += speed; alert(`${this.name} runs with speed ${this.speed}.`); } stop() { this.speed = 0; alert(`${this.name} stopped.`); } } class Rabbit extends Animal { hide() { alert(`${this.name} hides!`); } stop() { super.stop(); // call parent stop this.hide(); // and then hide } } let rabbit = new Rabbit("White Rabbit"); rabbit.run(5); // White Rabbit runs with speed 5. rabbit.stop(); // White Rabbit stopped. White rabbit hides! super.method(...) to call a parent method. super(...) to call a parent constructor (inside child constructor only).

65 Class - constructor Previous example did not have its own constructor
class Rabbit extends Animal { // generated for extending classes without own constructors constructor(...args) { super(...args); } } class Animal { constructor(name) { this.speed = 0; this.name = name; } run(speed) { this.speed += speed; alert(`${this.name} runs with speed ${this.speed}.`); } stop() { this.speed = 0; alert(`${this.name} stopped.`); } }//********************************* // Inherit from Animal class Rabbit extends Animal { hide() { alert(`${this.name} hides!`); } } let rabbit = new Rabbit("White Rabbit"); rabbit.run(5); // White Rabbit runs with speed 5. rabbit.hide(); // White Rabbit hides!

66 Class - constructor Does this work?
class Animal { constructor(name) { this.speed = 0; this.name = name; } // ... } class Rabbit extends Animal { constructor(name, earLength) { this.speed = 0; this.name = name; this.earLength = earLength; } // ... } let rabbit = new Rabbit("White Rabbit", 10); Does this work?

67 Class - constructor class Animal { constructor(name) { this.speed = 0; this.name = name; } // ... } class Rabbit extends Animal { constructor(name, earLength) { this.speed = 0; this.name = name; this.earLength = earLength; } // ... } let rabbit = new Rabbit("White Rabbit", 10); constructors in inheriting classes must call super(...), and (!) do it before using this

68 Class - constructor Now, does this work?
class Animal { constructor(name) { this.speed = 0; this.name = name; } // ... } class Rabbit extends Animal { constructor(name, earLength) { super(name); this.speed = 0; this.name = name; this.earLength = earLength; } // ... } let rabbit = new Rabbit("White Rabbit", 10); Now, does this work?

69 Class - In class example
class Person(first, last, age, gender, interests) { constructor(first, last, age, gender, interests){ this.name = { first, last }; this.age = age; this.gender = gender; this.interests = interests; } function greeting() { alert('Hi! I\'m ' + this.name.first + '.'); function farewell(){ alert(this.name.first + ' has left the building. Bye for now!'); } } var person1 = new Person('Tammi', 'Smith', 17, 'female', ['music', 'skiing', 'kickboxing']);

70 Class - In class example
We want to create a Teacher class, which inherits all the members from Person, but also includes: A new property, subject — this will contain the subject the teacher teaches. An updated greeting() method, which sounds a bit more formal than the standard greeting() method — more suitable for a teacher addressing some students at school.

71 Map, Set, WeakMap and WeakSet
Objects for storing keyed collections. Arrays for storing ordered collections. Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type A Set is a collection of values, where each value may occur only once WeakSet is a special kind of Set that does not prevent JavaScript from removing its items from memory. WeakMap is the same thing for Map *Advanced*

72 Map, Set, WeakMap and WeakSet
new Map() – creates the map. map.set(key, value) – stores the value by the key. map.get(key) – returns the value by the key, undefined if key doesn’t exist in map. map.has(key) – returns true if the key exists, false otherwise. map.delete(key) – removes the value by the key. map.clear() – clears the map map.size – returns the current element count map.entries() – returns an iterable for entries [key, value], it’s used by default in for..of *Advanced*

73 Map, Set, WeakMap and WeakSet
map = new Map(); map.set('1', 'str1'); // a string key map.set(1, 'num1'); // a numeric key map.set(true, 'bool1'); // a boolean key // remember the regular Object? it would convert keys to string // Map keeps the type, so these two are different: alert( map.get(1) ); // 'num1' alert( map.get('1') ); // 'str1' alert( map.size ); // 3 *Advanced*

74 Map, Set, WeakMap and WeakSet
map.keys() – returns an iterable for keys, map.values() – returns an iterable for values, map.entries() – returns an iterable for entries [key, value], it’s used by default in for..of *Advanced*

75 Map, Set, WeakMap and WeakSet
new Set(iterable) – creates the set, optionally from an array of values (any iterable will do). set.add(value) – adds a value, returns the set itself. set.delete(value) – removes the value, returns true if value existed at the moment of the call, otherwise false. set.has(value) – returns true if the value exists in the set, otherwise false. set.clear() – removes everything from the set. set.size – is the elements count. *Advanced*

76 Map, Set, WeakMap and WeakSet
let set = new Set(); let john = { name: "John" }; let pete = { name: "Pete" }; let mary = { name: "Mary" }; set.add(john);// visits, some users come multiple times set.add(pete);set.add(mary);set.add(john);set.add(mary); alert( set.size ); // set keeps only unique values, 3 for (let user of set) { alert(user.name); // John (then Pete and Mary) } ********************************************************************************** set.keys() – returns an iterable object for values, set.values() – same as set.keys, for compatibility with Map, set.entries() – returns an iterable object for entries [value, value], exists for compatibility with Map *Advanced*

77 JSON JavaScript Object Notation is a syntax for storing and exchanging data -When exchanging data between a browser and a server, the data can only be text. -JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server. -We can also convert any JSON received from the server into JavaScript objects

78 JSON <!DOCTYPE html> <html> <body>
<h2>Convert a string written in JSON format, into a JavaScript object.</h2> <p id="demo"></p> <script> var myJSON = '{ "name":"John", "age":31, "city":"New York" }'; var myObj = JSON.parse(myJSON); document.getElementById("demo").innerHTML = myObj.name; </script> </body> </html> JSON Sending Data <!DOCTYPE html> <html> <body> <h2>Convert a JavaScript object into a JSON string, and send it to the server.</h2> <script> var myObj = { "name":"John", "age":31, "city":"New York" }; var myJSON = JSON.stringify(myObj); window.location = "demo_json.php?x=" + myJSON; </script> </body> </html> Receiving Data

79 AJAX AJAX = Asynchronous JavaScript And XML. AJAX is not a programming language. AJAX just uses a combination of: A browser built-in XMLHttpRequest object (to request data from a web server) JavaScript and HTML DOM (to display or use the data) Read data from a web server - after the page has loaded Update a web page without reloading the page Send data to a web server - in the background *Advanced*

80 jQuery jQuery is a JavaScript Library. Greatly simplifies JavaScript programming. jQuery is easy to learn HTML/DOM manipulation CSS manipulation HTML event methods Effects and animations AJAX Utilities $(document).ready(function(){ $("p").click(function(){ $(this).hide(); }); *Advanced*

81 jQuery *Advanced* $(document).ready(function(){
// jQuery methods go here... }); This is to prevent any jQuery code from running before the document is finished loading (is ready) ***************************************************************************************** $("button").click(function(){ $("#test").hide(); ********************************************************************************************************************* $("#btn1").click(function(){ alert("Text: " + $("#test").text()); $("#btn2").click(function(){ alert("HTML: " + $("#test").html()); *Advanced*

82 Lab Exercises

83 Wrap-Up Review of Lecture Overview of Next Steps Questions


Download ppt "MIT GSL 2018 week 1 | day 2 JavaScript II."

Similar presentations


Ads by Google