580 likes | 895 Views
JavaScript Part 1. Lecture Overview. JavaScript background The purpose of JavaScript JavaScript syntax. History Lesson. JavaScript is NOT Java Started at Netscape in 1995 Microsoft released its own version ' JScript " in 1996
E N D
Lecture Overview • JavaScript background • The purpose of JavaScript • JavaScript syntax
History Lesson • JavaScript is NOT Java • Started at Netscape in 1995 • Microsoft released its own version 'JScript" in 1996 • JavaScript is the default scripting language in .NET (VBScript has pretty much faded away)
What do we do with JavaScript? • A starter list • Adds sizzle to pages (Animation) • Dynamic HTML (DHTML) • Client side data entry validation • Client side CGI • Reduce the load on overburdened servers • Process and manage cookies • Some servers are beginning to support JavaScript • AJAX to load parts of Web pages
What is JavaScript? (1) • It’s a programming language that ‘closely’ resembles Java • Implementations • European Computer Manufacturers Association created ECMAScript to standardize different scripting versions See ECMA-262 • I’ll try to conform • There are others • It’s a “C ish” language
What is JavaScript (2) • Most of what we do is access the object model supported by the underlying browser • The W3C defines the Document Object Model (DOM) • Differences do exist between browsers • I will try, where possible, to point out these differences • Most support the common ECMA standards though
Creating a First Script • <script> tag appears in a <head> or <body> tag • type argument denotes that it’s JavaScript • Example: <script type=“text/javascript”> document.write(“hello”); </script>
Creating a First Script script tag Script language <html> <body> <script type=“text/javascript"> document.write(“hello") </script> </body> </html> Script tag
Script Placement (1) • A document may have multiple <script>blocks • Scripts in a <head> block • Create procedures here • Before or after the <style> section is fine • Scripts in a <body> block • Code executes as the page is rendered • Importing external script files • This is the recommended place to put generic functions
Script Placement (2) • Scripts appearing in a <head> tag but outside a procedure execute first in the order they appear • More about procedures later • Code in a procedure is not executed unless explicitly called • Scripts appearing in a <body> tag execute as they are encountered • The placement has an effect on page rendering
Handling Java Incapable Browsers • Include the <noscript>directive to display a message when JavaScript is disabled <html> <body> <script language="javascript"> document.write("Greetings") </script> <noscript> <p>JavaScript is not enabled.</p> </noscript> </body> </html>
JavaScript Semantics • Semicolons need not terminate statements although they do no harm • Unless two statements are placed on the same line • Variables • var data type is generic • JavaScript is not strongly typed like Java • Type conversion happens on the fly • Other types • number, boolean, string, function, object
Creating a First Script (Example) • See JavaScriptExample1.htm • Pay particular attention to the order in which the script code executes
Comments • Comments appear differently inside of JavaScript block that outside of a JavaScript block • The characters // on a line mark the line as a comment • The strings /* and */ mark the begin and end of a multi-line comment
Adding Comments <html> <body> <script language="javascript"> // This is a comment. /* This is a two line comment */ document.write("Greetings") </script> </body> </html>
Variables (1) • JavaScript is “loosely typed’ • data types change dynamically as the program runs • Declare variables with the var statement
Variables (2) • Examples varx // Now x is undefinedvar x = 5; // Now x is a Numbervar x = "John"; // Now x is a String
Variables (3) • Like VB, there are local and global variables • Local variables are declared inside of a procedure • Global variables are declared in a <script> block but outside of a procedure
Functions (Introduction) • They are the same thing as a VB function or any other programming language function • Functions execute • When called by another procedure • When implemented as an event handler • Event handlers are discussed later
Declaring a Function • function declarations typically appear in the <head> section • They are only executed when explicitly called • Syntax: function name(parameter –list) { statements: }
Declaring a Function (Example) • Declare a function named printMessage <head> <script type="text/javascript"> function printMessage(msg) { alert(msg); } </script> </head>
Calling a Function • Functions execute when called • Call functions explicitly from other JavaScript code • Call functions implicitly from an event handler
Calling a Function (Exampple) • From another function or from within another JavaScript block, call the function with it’s name an parameters • Example: <script type="text/javascript"> printMessage(); </script>
Returning a Value from a Function • Call the return statement with an argument as inreturn 0;
Operators • They are about the same as VB • % is the modulus operator though • http://www.w3schools.com/js/js_operators.asp
Comparisons • Similar to VB • == is the test for equality • != is the test for inequality • http://www.w3schools.com/js/js_comparisons.asp
Decision-Making • Again, conceptually similar to VB • {} mark blocks instead of EndIf • http://www.w3schools.com/js/js_if_else.asp
Loops • While VB we have for loops and while loops
JavaScript Events (Introduction) • Conceptually, Java Script events work just like .NET (VB) events • They fire as a result of some user or other action • Code that executes in response to an event is called an event handler • The syntax and event names differ between VB and JavaScript
Common Events (1) • Mouse Motion • mouseover – mouse enters the region of an element • mouseout – mouse leaves the region of an element • focus – an element becomes active • blur – an element because inactive • http://www.w3schools.com/tags/ref_eventattributes.asp
Common Events (2) • Document related events • load – document loads • unload – fires just before the document is unloaded • Button related • click – user clocks a button (or other element) • submit
Creating Event Handlers • There are two ways to create event handlers • Inline event handlers have code in the event argument • Create functions and wire them to the event
Inline Event Handler (Example) • The alert dialog appears when the user clicks the button <body> <input type="button" value="Click Me" onclick= "alert('you clicked me');" /> </body>
Calling a Function from an Event handler • Event handlers are functions with some special characteristics • The following statement calls the procedure btnShowEventClick when the button is clicked: <input id="btnShowEvent" type="button" value="Execute event handler" onclick="btnShowEventClick()" />
The Document Object Model • There really is not that much to the JavaScript language itself • It’s just a subset of Java • JavaScript uses the Document Object Model (DOM) objects to get at the browser and its windows • This is where the real power comes in • Standard defined by W3C and European Computer Manufactures Association (ECMA) hence ECMAScript • I’ll introduce the DOM here and go into more detail later
What is the DOM? • It permits access to the contents, structure, and style of an XHTML document • An XML document too • The DOM can communicate with multiple browser instances • It’s formally defined by the W3C • Use the DOM to dynamically create new document elements • Use the DOM to move document elements and remove them too
We will talk about • navigator (the browser itself) • window (a window in the browser) • document (the currently loaded document in the browser)
The write() and writeln() Methods • Both write their argument to the output stream (HTML document) • Both apply to the document object • More in a moment • write() does not write a terminating carriage return • writeln()does write a carriage return
Determining the Browser • Use the navigator object to get info about the browser • appVersion gets the major version • Netscape • Microsoft Internet Explorer • appMinorVersion gets the minor version • Supported by IE only • appPlatform gets the OS version • cookieEnabled gets cookie status
Determining the Browser (Example) document.write(navigator.appName)document.write(navigator.appVersion)document.write(navigator.appMinorVersion)document.write(navigator.platform)document.write(navigator.cookieEnabled) See JavaScriptNavigatorExample.htm
The window object • The window object provides a reference to the open browser window • Through the window object, you can • Reference the elements on the page through the DOM • Create new windows and destroy them
The window Object (Introduction) • It’s the root of the IE object hierarchy • It refers to the IE Browser windows • The documentproperty contains a reference to the open document • More about the document object in a moment • window.open() creates a new browser window
window.open (Semantics) • window – refers to the browser window • We can also use the keyword self • window.open (url, name, features) • url contains URI or file name • Second argument contains the nameof the window • Features allows browser window configuration • It’s a comma-separated list of key=valuepairs
The window Object (Attributes 1) • fullscreen - defines whether window fills the desktop • toolbar – enable or disable the toolbar • menubar – enable or disable the menu bar • resizable – allow or disallow window resizing
The window Object (Attributes 2) • alwaysRaised – browser floats on top of other windows regardless of whether it is active • height and width define the window size • scrollbars defines whether scroll bars appear when necessary • Unspecified attributes will have false values
The window Object (Attributes – Example) • Create a blank Web page without a toolbar or a menu bar • Note attributes appear as a comma separated list • 1 and yes are equivalent • 0 and no are equivalent newWindow = window.open("","foo", "toolbar=no,menubar=no") newWindow = window.open("","foo", "toolbar=no,menubar=no")
The window Object (Best practices) • Do not use to create those dreaded banner ads • Do not use to trap the user by handling onClose and displaying the window again • Do not hide the title bar
The window Object (Example) • Display a very annoying window that’s hard to get rid of window1 = window.open("","Annoy", "height=300,width=300,titlebar=no") window1.document.write("Annoying") See JavaScriptWindowMaker.htm