350 likes | 494 Views
Javascript Introduction. Kenny Lam. What is Javascript ?. Client-side scripting language that can manipulate elements in the DOM Event-driven language that responds to activity on the webpage In the end, adds an interactive element to the page without having to load a new page. More about….
E N D
JavascriptIntroduction Kenny Lam
What is Javascript? • Client-side scripting language that can manipulate elements in the DOM • Event-driven language that responds to activity on the webpage • In the end, adds an interactive element to the page without having to load a new page
More about… • Dynamic typing • Interpreted language • Object Oriented • Protoypes for inheritance • May be different for different browsers • May be different for different versions of different browsers
JavascriptVariables and Basic Syntax Kenny Lam
Importing your Javascript • Two places to import your javascript • <head> element • End of <body> element OR <head> <script type=“text/javascript” src=“http://location.com/file.js” /> </head> … <body> … <script type=“text/javascript” src=“http://location.com/file.js” /> </body>
Variables • Only one prefix to remember, use var with all your variables when declaring them • Different variable types include (objects later) • Numbers • Booleans • String • Null • Undefined var x = 6.470; var y = ‘hello world’; var s = true;
Variables pt. 2 • Numbers – double precision, be careful of floating point errors • Null – for explicitly saying non-assigned value • Undefined – for never having assigned anything
Strings • Array of characters • Comes with a variety of built-in methods • length, indexOf, match, replace, search, split, substr, substring, toString var s = ‘hello world’; s[1]; // value of ‘e’ s.indexOf(‘\ ’); // value of 5 s.substr(8); // value of ‘rld’
Syntax • Be a clean coder when it comes to javascript, can lead to hazards if not careful • If-else statements. Use blocks • End appropriate lines with semicolons • Use either single or double quotes, but don’t mix and match if (expression) { //code } else { //code } var s = ‘string here’; var x = ‘we can have a “string” inside another!’
Objects • Same as a dictionary/hash table in other languages • Can use strings as keys, helps with disallowed characters • Values are any acceptable var’s • Can even use functions as values (later) var x = 6470; var obj1 = { //the braces create an object key1: x, //use commas to separate keys “key2”: “string” }; //ending my declaration var obj2 = { key: obj1 //can even have an object! };
Objects pt. 2 • Access using object.property • Access using array notation obj1.key1; //will give 6.470 obj1.y = 3; obj2[‘key’]
Special Objects • Two very special objects: window and document • The document object holds the DOM elements • Every window/tab houses everything inside of the window object document.body; //returns the <body> element window.location; //gives the URL for the window
Arrays • Special type of objects, using numbers as keys • Has many special methods • length, push, pop, concat, toString vartmpArray = [“string”, 6.470, obj1]; //different variable types are okay tmpArray[0]; //value “string” tmpArray[2].key1; //value 6.470
The console • Console logging • Shows visibility of object properties • Web page source code • Breakpoints console.log(obj1);//you can see all its properties console.log(“message”); console.log(array1); //can read all elements
JavascriptOperators and Functions Kenny Lam
Operators • All the common mathematical operators • +, -, *, /, % (mod) • Unary operators • Compound assignment • Overloaded + operator for strings • More operators in Math module for numbers (use Math.pow, not the carat) x++; ++x; x*=3; “string1” + “string2”; // gives “string1string2” “3” + 8 // gives “38” “1” + 2 + 3 // gives “123”
Operators pt. 2 • Comparison operators: • <, <=, >, >= • For non-strict equality comparisons, can use == • For strict equality comparisons, use === • Also non-equality comparisons: • !=, !==
Functions • Functions are objects, two ways of declaring • Just use number of parameters because of dynamic typing function fun(x,y) { //will take 2 parameters //code }; varfunFunc = function(a,b,c) { //uses 3 parameters //code }; fun(“string”, obj1); fun(obj1, obj2); //these two call the same function!
Functions pt. 2 • Lots of bad flexibility. Function calls don’t need to match signature! • If you need a variable number of arguments, use the arguments object fun(x,y); fun(x,y,z); //these will both call the same function function abc() { arguments.length; arguments[0]; //more code }
Functions pt. 3 • Object properties can be functions too(since functions are objects) • Functions return undefined by default, but can return any value • Recursive calls
Scope • Functions define scope of variables • The ‘this’ reference • Anonymous functions, closure, and inner functions are fun ways to play with this var x = 13; function scopeFun() { var x = 12; console.log(x); //value of 12 console.log(this.x); //value of 13 }; //helps to show why to use var!
Execution • Javascript is executed in the order written • To get asynchronous behavior, use setTimeoutor AJAX calls (more later)
JavascriptClasses and Inheritance Kenny Lam
Object Oriented • Can create classes in javascript, defined by functions (constructors) • The ‘new’ keyword makes a new object and sets up the constructor correctly function MITClass(course, semester){ this.course = course; this.semester = semester;} var web = MITClass(6.470, “IAP 2013”); web.course; //value 6.470 web.semester; //value “IAP 2013”
Prototypes • In javascript, you inherit from instances instead of classes • The ‘__proto__’ property of objects, and the ‘prototype’ property of functions var x = MITClass(6.470, “IAP 2013”); x.prototype; //undefined, x is an object! MITClass.__proto__; //bogus, MITClass is a function! x.__proto__; //some object MITClass.prototype; //same object x.__proto__ == MITClass.prototype; //true x.__proto__ === MITClass.prototype; //true
JavascriptConditionals and Loops Kenny Lam
Conditionals • If-else statements • Switch statements if (condition) { if(condition) { //code //code } else { else if(condition) { //code //code } } else { //code } switch(variable) { case 1: //code break; case 2: //code break; default: //code }
Looping • For loops • While loops • Do…while loops vari=0; for(vari=0; i<n; i++) { while(i<n) { //code //code } } for(var x in ObjectName) { ObjectName[x]; //code }
JavascriptjQuery Kenny Lam
About jQuery • Open source aid to writing effective javascript • Bundles all the power of javascript into more manageable API • Cross-browser support • Handles events, manipulates DOM, provides animations • Wait for DOM to load properly $(document).ready() $; //the dollar is shorthand for jQuery jQuery; //also jQuery (surprise) var x = jQuery.noConflict();
Selectors • Any CSS style selectors are valid • Most typical will be id, class, and element type selectors $(‘#id’) //select elements using the hash prefix $(‘.class’) //select elements using the dot prefix $(‘div’) //select elements by node type $(‘div:first’).parent() //select parent of first div
Events • Provides a great way to handle events • Read the documentation for all possible events • Common events • click, blur, keypress, focus, hover, submit, etc. $(‘#id’).click(function(event) { //code to execute on a click of #id element });
Extras • jQuery can also do loops that integrate well with selectors • The jQuery API is used for jQuery objects. Be careful of ‘this’ $(‘div’).each(function() { //code }); $(‘div’).click(function() { //you can reference ‘this’ in here and it will mean the clicked div //but you might really want $(this) });
JavascriptMore Reading Kenny Lam
Additional Topics • Console/debugging • Cookies • Closures • Regex • Storage • Anonymous/named anonymous functions • Other cool javascript libraries! (Raphael, lightbox, scriptaculous, jQuery UI, prototype, mooTools, etc.)