660 likes | 768 Views
JAVASCRIPT. Session 1. Suggested Text. Learning JavaScript 2nd Shelley Powers 978-0-596-52187-5 Full text can be viewed online via DePaul Library. Search for Safari books database. Skillset. Familiar with Web Technology CSS, HTML, Client, Server Programming Concepts. Overview.
E N D
JAVASCRIPT Session 1
Suggested Text • Learning JavaScript 2nd • Shelley Powers • 978-0-596-52187-5 • Full text can be viewed online via DePaul Library. Search for Safari books database.
Skillset • Familiar with Web Technology • CSS, HTML, Client, Server • Programming Concepts
Overview • Lecture #1: Introduction, Data Types, Operators and Statements • Lecture #2: JavaScript Objects, Functions • Lecture #3: The Browser, The DOM, Dynamic pages, Debugging • Lecture #4: JavaScript and Custom Object creation, Storage • Lecture #5: XML - JSON, Introduction to Ajax
Popularity of JavaScript • Relatively easy to learn • No special applications to install • Easy to implement (e.g. embedding in web pages)
How to use it ? Simplest technique is to embed directly inside an HTML document: <script type=”text/javascript”> ... JS code goes here … </script>
Where to put it ? • Traditionally... • in the HTML head element • in the body element • in a separate document • Sometimes all of the above...
Where to put it: Best Practices • One suggested ‘best practice’ recommends placing your scripts just before the closing </body> tag. • Main reasons: • Speeds up downloading • Allows for direct manipulation of the DOM while page is loading • For purposes of teaching / clarity, we will typically keep scripts at the top (<head> section) or inline.
Example 1 <html> <head> <title>Hello World Example</title> </head> <body> <script type="text/javascript"> alert("Hello World !"); </script> </body> </html>
Example 1 <html> <head> <title>Hello World Example</title> </head> <body> <script type="text/javascript"> alert("Hello World !"); </script> </body> </html>
Example 2 <html> <head> <title>Hello World Example</title> <script type="text/javascript"> function hello() { var msg = "Hello World !"; document.open(); document.write(msg); document.close(); } </script> </head> <body onload="hello()"> </body> </html>
Example 2 <html> <head> <title>Hello World Example</title> <script type="text/javascript"> function hello() { var msg = "Hello World !"; document.open(); document.write(msg); document.close(); } </script> </head> <body onload="hello()"> </body> </html>
script Element • JavaScript lives within the context of another language. (HTML, XHTML) • When browser sees the <script> tag, it turns the process over to its scripting engine.
script Elementthe 'type' attribute <script type="text/javascript" > • Not all script embedding is JavaScript. (text/javascript) • text/ecmascript • text/jscript • text/vbscript • text/vbs • All these ‘type’ values describe the MIME type of the content. This is to provide a way to allow non-compatible browsers to ignore, if they can not handle it.
Browser Compatibility • Current popular bowsers • Firefox • Internet Explorer • Chrome • Opera • Safari • All interpret JavaScript in their own way. Dealing with cross-browser incompatibilities and behavioral nuances can be a major issue in JS coding.
script Location <head></head> • It is most common to add the ‘script’ tag in the head section. Easier to maintain, as the scripts are located in one common area. <body></body> • Performance. When a script is added in the ‘head’ section, the rest of the document can be held back from downloading until the script is loaded. Some have suggested placing scripts at the bottom of the ‘body’ section. External File • Discussed later.
Intro to Functions <html> <head> <title>Hello World Example</title> <script type="text/javascript"> function hello() { var msg = "Hello World !"; document.open(); document.write(msg); document.close(); } </script> </head> <body onload="hello()"> </body> </html>
Intro to Functions • Syntax: function nameOfFunction(parameter1, parameter 2, …,. parameter n) { Body of the JS function goes inside the braces } • The function is invoked by an “event handler”: <body onload="nameOfFunction()">
Event Handlers Example: <body onload = "nameOfFunction()" > Some Other Event Handlers • onload - fired when something loads (body, img) • onclick - fired when the mouse is clicked • onmousover - fired when mouse is over the element • onmouseout - fired when the mouse is no longer over element • onfocus - fired when element gains focus via mouse or keyboard (e.g. a textfield in a form) • onblur - fires when the element no longer has focus
Event Handlers • The onload function is a property of another built-in browser object: the ‘window’ object. <script type="text/javascript"> window.onload=hello(); function hello() { var msg="Hello World"; document.open(); document.writeln(msg); document.close(); } </script>
document Object • When an HTML document gets loaded into the browser, it becomes a 'document' object. • This document object is a representation of the actual page including all the elements in it including: • collections mapped to page elements such as images, form elements, etc • web page modifiers • Methods: open, write, writeln • The document object and the window objects are part of the “Document Object Model” (a.k.a. DOM)
property Operator • The property operator is represented by the ‘.’ • data elements, event handlers and object methods are all properties of objects within JavaScript. • They are all accessed via the property operator. • document.title = "Title of My Page"; • var firstName = document.getElementById(“txtFirstName").value;
Method Chaining Consider the statement: document.getElementById("txtFirstName"); To this statement we can add: document.getElementById("txtFirstName").style.backgroundColor="#fff000"; • Here the page element with an id of “txtFirstName” is accessed using an important method available to all objects present in the document object. This method is called getElementById() . • The style object of this particular element (“txtFirstName”) is accessed in order to set the background color
Method Chaining document.getElementById("txtFirstName").style.backgroundColor="red"; • getElementById() is a method of the document object • the page element “txtFirstName” is accessed via this getElementById() method • style - property of the page element • backgroundColor - property of the style object • Ajax and JQuery, make extensive use of method chaining.
var Keyword • to declare a variable: • var msg = ... • Variables are versatile. They can store: • string • number • boolean • function reference • array • another object
Scope • Local Variables: When you declare a variable inside of a function, its scope is local to that function. • Global Variables: A global variable is one that is declared outside of any function. In general, avoid using global variables! • If you need to have a value outside the current function, pass it as a parameter.
Scope • When you declare a variable with the ‘var’ keyword in a function, the variable is local to that area. • If you declare a variable locally without using ‘var’, it automatically becomes a global variable! • If you use a variable without declaring it via the var keyword, and a global variable with the same name exists, the local variable is assumed to be the global variable.
Lifetime of a Variable • The variable comes into existence when it is first delcared. • If a variable is declared inside a function, the variable is deleted when the function ends. • If a variable is global, the variable is deleted when the page is closed.
Statements • Like any other language JavaScript has an assortment of statements • assignment • for loops • if...else • switch • Semicolons: JavaScript provides “automatic semicolon insertion (ASI). Therefore, while the semicolon is not absolutely required (except if you were going to put a number of statements on the same line), it is good practice.
Comments • There are 2 types of comments • single line - // • block - /*...*/ <html> <head> <title>Hello World Example</title> <script type="text/javascript"> function hello() { /* This is a multi-line block of comments */ var msg = "Hello World !"; document.open(); document.write(msg); document.close(); } </script> </head> <body onload="hello()"> </body> </html> <html> <head> <title>Hello World Example</title> <script type="text/javascript"> function hello() { // This is single line comment var msg = "Hello World !"; document.open(); document.write(msg); document.close(); } </script> </head> <body onload="hello()"> </body> </html>
Hiding script • For browsers that could not process JavaScript, the script code would be displayed as text on the web page. In the past, the recommended practice was to hide it inside HTML comments: <!-- JS CODE --> • It has more currently been recommended that we use //<![CDATA[ JS CODE //]]> This particular technique has the added benefit of hiding the JS code from XHTML validators (which did not allow it). However, with the increased standardization of HTML-5 and the decreased adherence / concern with XHTML validity, even CDATA is not as widely used.
Hiding script with ‘cdata’ CDATA refers to text data that should not be parsed by an XML or XHTML parser. <script type="text/javascript"> // <![CDATA[ Your JS Script goes inside this block // ]]> </script> However, as XHTML is becoming less of a factor in current web coding, we will usually dispense with CDATA during our discussions for purposes of clarity.
Internal vs External • Remember CSS ? • inline • internal • external • JavaScript • internal - body • internal - head • external
External • Save your functions in an external terminated by .js • Link to the page via the src attribute: <script type="text/javascript" src="hello.js"></script> Note: The closing </script> is needed!
External JS File: hello.js /* function:hello author:me purpose: displays hello world on web page */ function hello() { // Initialize msg var msg = "Hello <em>World</em>"; document.open(); document.writeln(msg); document.close(); }
hello.html <html> <head> <title>Hello World Example</title> <script type="text/javascript" src="hello.js"> </script> //Yes, you should include this </script> tag… </head> <body onload="hello()"> </body> </html>
Guidlines • Remember, not everyone has JavaScript enabled • Design your pages accordingly
noscript <html> <head> <title>Hello World Example</title> <script type="text/javascript"> //<![CDATA[ function hello() { var msg = "Hello World !"; document.open(); document.write(msg); document.close(); } //]]> </script> </head> <body onload="hello()"> <p>H1</p> <noscript> <p>I'm able to be displayed</p> </noscript> </body> </html> The <noscript> tag displays only on browsers that do not have JavaScript enabled.
Data Types and Variables • “dynamic typing” The data type is the JavaScript scripting engine’s interpretation of the type of data that the variable is currently holding. • A given variable can hold a different type of data at different times depending on the context. • A variable can even hold an entire collection, such as a form (including all elements therein). This variable will then have access to all the elements on that form.
Dynamic Typing <html> <head> <title>Hello World Example</title> <script type="text/javascript"> function hello() { var x = "hello"; var typeX1 = typeof x; x = 3; var typeX2 = typeof x; alert(typeX1 + " and then " + typeX2); </script> </head> <body onload="hello()"> <p>H1</p> </body> </html>
Choosing Identifiers for Your Variables “Identifier” refers to the name we assign to a variable or a function name or a class or an object, etc, etc. It is extremely important that you choose your identifiers with some thought. Identifiers should give a pretty good idea of what the variable holds, or what the function is supposed to do, of the type of object being created, etc. Rules for choosing variable identifiers: • Must begin with a character, or dollar sign, or underscore • Are case sensitive • Cannot be JavaScript keywords (new, else, var, void, etc) • By convention, variables should begin with a lower-case letter
Naming Guidelines for Your Identifiers • Many of these guidelines are inherited from Java and other languages • Make your identifiers meaningful: ‘interestRate’ vs ‘ir’ • If naming an array, make your identifier plural: customerNames • If naming a variable, begin with lowercase letter: • var firstName = “Joe”; • Use “CamelCase”: • firstName, bankAccount, totalDailySales
“Primitive” Data Types • Primitive does not mean “old fashioned”. It typically means that it is the simplest form of variable that can hold only one value and can not “do” anything. • Programmers use primitive data types all the time. • Three primitive types • string • numeric • boolean • These primitive types have “Object wrappers” (discussed later) • String • Number • Boolean
Objects v.s. Primitive Data Types Primitive data types can hold only one value. Also, they can not “do” anything. That is, they do not have ‘functionality’. Objects do have functionality. For example, a String object (as opposed to a primitive string type) can invoke various methods and properties such as length, toUpperCase() and many others. var name = "Joe"; //name is a primitive string data type var objName = new String("Joe"); //objName is a String “object” alert( objName.length ); //outputs 3 alert( name.length ); // ‘name’ is not a String object // therefore,JS will temporarily create an object, invoke the property, // then destroy the object. This is resource intensive alert( objName.toUpperCase() ); //outputs JOE alert( name.toUpperCase() ); //Resource intensive
Should I create an object? var firstName = "Bob"; //firstName is primitive var firstName = new String("Bob"); //firstName is a String object IF you anticipate using various methods and properties of the String object, then YES, you should create an object. The reason is that if you create a primitive variable, every time you invoke a method or use a property, JS must (1)Create an object, (2)apply the properties/method, (3)Destroy the object. var uppCaseName = firstName.toUpperCase(); JS must do all 3 different step in order to invoke the toUpperCase() function! alert( firstName.length ); //JS must again create and destroy the object
String Object – Use of Quotes You can use single or double quotes around your strings. A somewhat common convention is to use single-quotes around JavaScript strings, and double quotes around the values of HTML attributes. All of the following are perfectly fine: • var firstString = "This has double quotes"; • var secondString = 'This has single quotes'; • var thirdString = 'This will "embed" double quotes'; • var fourthString = "This will 'embed' single quotes"; • var emptyString = ""; • var str = null; //A ‘null’ string is NOT the same as an empty string
Escape Sequences • Placing a ‘\’ before a “code” character (e.g. quoets, semicolon, parenthese, braces, etc) tells the JS interpreter to NOT treat that character as JS code. • Placing a ‘\’ before a non-code character, tells JS to look up that character, as it probably is a special instruction of some kind. • Basically, the ‘\’ tells JS to treat JS code as regular, and regular text as code!
Escape Sequences - Examples • \n says to add a new line: alert("This is line 1.\nThis is line 2."); • Output: alert("This is a \"string\" with quotes and a semicolon \;"); • Output: • This is a “string” with quotes and a semicolon ;
String Encoding – URIs • URI stands for “Uniform Resource Identifier”. It is an ISO standard. The very familiar ‘URL’ is one example of a URI. • URIs can only be sent over the Internet using the ASCII character-set. • Since URIs often contain characters outside the ASCII set, the URI has to be converted into a valid ASCII format. • URI encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. • Example: URIs cannot contain spaces. URI encoding normally replaces a space with a plus (+) sign or with %20. Other replacements: http://www.w3schools.com/tags/ref_urlencode.asp
String Encoding • Languages such as JS, PHP, etc include functions that allow you to easily “URI encode” a string. • In JavaScript: use either encodeURI() or encodeURIComponent() • encodeURI() - makes the assumption that the string is a URI such as http://www.abcd.com. However, does not encode the following ; , / ? : @ & = + $ and a few others • encodeURIComponent() - encodes all characters except the previous listed. It is typically used when the string being encoded is going to be used as a parameter to a URI.