Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript Part 1. Slide 2 Lecture Overview JavaScript background The purpose of JavaScript JavaScript syntax.

Similar presentations


Presentation on theme: "JavaScript Part 1. Slide 2 Lecture Overview JavaScript background The purpose of JavaScript JavaScript syntax."— Presentation transcript:

1 JavaScript Part 1

2 Slide 2 Lecture Overview JavaScript background The purpose of JavaScript JavaScript syntax

3 Slide 3 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)

4 Slide 4 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

5 Slide 5 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

6 Slide 6 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

7 Slide 7 Creating a First Script tag appears in a or tag type argument denotes that it’s JavaScript Example: document.write(“hello”);

8 Slide 8 Creating a First Script document.write(“hello") script tag Script tag Script language

9 Slide 9 Script Placement (1) A document may have multiple blocks Scripts in a block Create procedures here Before or after the section is fine Scripts in a block Code executes as the page is rendered Importing external script files This is the recommended place to put generic functions

10 Slide 10 Script Placement (2) Scripts appearing in a 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 tag execute as they are encountered The placement has an effect on page rendering

11 Slide 11 Handling Java Incapable Browsers Include the directive to display a message when JavaScript is disabled document.write("Greetings") JavaScript is not enabled.

12 Slide 12 JavaScript IS CASE SENSITIVE

13 Slide 13 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

14 Slide 14 Creating a First Script (Example) See JavaScriptExample1.htm Pay particular attention to the order in which the script code executes

15 Slide 15 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

16 Slide 16 Adding Comments // This is a comment. /* This is a two line comment */ document.write("Greetings")

17 Slide 17 Variables (1) JavaScript is “loosely typed’ data types change dynamically as the program runs Declare variables with the var statement

18 Slide 18 Variables (2) Examples var x // Now x is undefined var x = 5; // Now x is a Number var x = "John"; // Now x is a String

19 Slide 19 Variables (3) Like VB, there are local and global variables Local variables are declared inside of a procedure Global variables are declared in a block but outside of a procedure

20 Slide 20 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

21 Slide 21 Declaring a Function function declarations typically appear in the section They are only executed when explicitly called Syntax: function name(parameter –list) { statements: }

22 Slide 22 Declaring a Function (Example) Declare a function named printMessage function printMessage(msg) { alert(msg); }

23 Slide 23 Calling a Function Functions execute when called Call functions explicitly from other JavaScript code Call functions implicitly from an event handler

24 Slide 24 Calling a Function (Exampple) From another function or from within another JavaScript block, call the function with it’s name an parameters Example: printMessage();

25 Slide 25 Returning a Value from a Function Call the return statement with an argument as in return 0;

26 Slide 26 Operators They are about the same as VB % is the modulus operator though http://www.w3schools.com/js/js_operators.asp

27 Slide 27 Comparisons Similar to VB == is the test for equality != is the test for inequality http://www.w3schools.com/js/js_comparisons.asp

28 Slide 28 Decision-Making Again, conceptually similar to VB {} mark blocks instead of EndIf http://www.w3schools.com/js/js_if_else.asp

29 Slide 29 Loops While VB we have for loops and while loops

30 Slide 30 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

31 Slide 31 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_eventattrib utes.asp http://www.w3schools.com/tags/ref_eventattrib utes.asp

32 Slide 32 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

33 Slide 33 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

34 Slide 34 Inline Event Handler (Example) The alert dialog appears when the user clicks the button

35 Slide 35 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:

36 Slide 36 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

37 Slide 37 What is the DOM (1)? The HTML DOM is a tree objects It permits access to the contents, structure, and style of an HTML 5 document An XML document too The DOM can communicate with multiple browser instances It’s formally defined by the W3C "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."

38 Slide 38 What is the Dom (2)?

39 Slide 39 What is the DOM (3)? Use the DOM to dynamically create new document elements move document elements and remove them too hide and make visible elements Change CSS styles

40 Slide 40 The Basic DOM Hierarchy

41 Slide 41 DOM Programming Model It’s an object model and a programming interface HTML elements are considered objects They have properties to store data They have methods that perform actions They respond to events

42 Slide 42 We will talk about navigator (the browser itself) window (a window in the browser) document (the currently loaded document in the browser)

43 Slide 43 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

44 Slide 44 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

45 Slide 45 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

46 Slide 46 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

47 Slide 47 The window Object (Introduction) It’s the root of the IE object hierarchy It refers to the IE Browser windows The document property contains a reference to the open document More about the document object in a moment window.open() creates a new browser window

48 Slide 48 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 name of the window Features allows browser window configuration It’s a comma-separated list of key=value pairs

49 Slide 49 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

50 Slide 50 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

51 Slide 51 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")

52 Slide 52 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

53 Slide 53 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

54 Slide 54 The window Object (Members 2) Display a prompt with a text entry field window.prompt(“message”, “Default”) Display a confirmation dialog if (window.confirm("Exit")) { window.close() } Display a message window.alert("Error")

55 Slide 55 The window Object (History 1) history – used for history navigation window.history.back() window.history.forward() Go back to pages and forward 2 pages window.history.go(-2) window.history.go(2)

56 Slide 56 The window Object (History 2) The history object also support the following properties: current – the URL of the current document length – the number of URLs in the history list next – the next URL in the history list previous – the previous URL in the history list

57 Slide 57 The window Object (Status bar) There are two properties to manage the status bar defaultStatus – this message always appears status – this message appears only temporarily such as when the mouse hovers over a button or link Display a status bar message window.status("appears in the status bar")

58 Slide 58 The document Object The object represents your running HTML document We can find elements change elements add and delete elements

59 Slide 59 The document Object (Finding Elements) MethodDescription document.getElementById()Find an element by element id document.getElementsByTagName()Find elements by tag name document.getElementsByClassName()Find elements by class name

60 Slide 60 The document Object (Changing Elements) MethodDescription element.innerHTML=Change the inner HTML of an element element.attribute=Change the attribute of an HTML element element.setAttribute(attribute,value)Change the attribute of an HTML element element.style.property=Change the style of an HTML element

61 Slide 61 The document Object (Adding / Deleting Elements) MethodDescription document.createElement()Create an HTML element document.removeChild()Remove an HTML element document.appendChild()Add an HTML element document.replaceChild()Replace an HTML element document.write(text)Write into the HTML output stream

62 Slide 62 The document Object (A Canonical List) Refer to W3Schools http://www.w3schools.com/js/js_htmldom_d ocument.asp http://www.w3schools.com/js/js_htmldom_d ocument.asp

63 Slide 63 Referencing Elements by ID Remember each HTML element has an ID attribute This attribute is special – it’s the unique identifier for the node It’s value should begin with a letter for compatibility with all browsers Use the GetElementByID method to get a reference to the node The method applies to the document object

64 Slide 64 Referencing Elements by ID (Example) Get and change the text in the paragraph named First function ShowTree() { x=document.getElementById("First"); x.innerHTML = "Changed"; } The paragraph declaration Hello world!

65 Slide 65 Getting Elements by Tag Name getElementsByTagName gets a list (array) of elements having a particular tag name The length property of the array tells us how many item are in the array Each element can be references via an array subscript

66 Slide 66 Getting Elements by Tag Name (Example) Collapse (hide) all paragraph elements

67 Slide 67 Getting Elements by Query Selector The querySelectorAll() method selects objects (elements) based on a CSS query selector These are the same query selectors that you have used before

68 Slide 68 Getting Elements by Query Selector Collapse all tags in a

69 Slide 69 Changing the value of an Attribute You can change the value of an attribute by specifying the attribute name to an element Change the src attribute of an image

70 Slide 70 JavaScript Events JavaScript has several events These operate similarly to Visual Basic events Events can be roughly categorized as Mouse events Keyboard events Form events The canonical list http://www.w3schools.com/jsref/dom_obj_even t.asp http://www.w3schools.com/jsref/dom_obj_even t.asp

71 Slide 71 JavaScript Mouse Events onMouseDown : User has pressed the mouse button but has not released it onMouseUp : User has released the mouse button onClick : User has pressed and released the mouse button onMouseMove : User has moved the mouse onMouseOver : Mouse has entered the region of a control onMouseOut : Mouse has left the region of a control

72 Slide 72 JavaScript Keyboard Events onKeyDown : keyboard key is pressed onKeyUp : keyboard key is released onKeyPressed : keyboard key is pressed and released http://localhost:49811/IS360/IS360JavaScript Events.html http://localhost:49811/IS360/IS360JavaScript Events.html

73 Slide 73 JavaScript Form Events onBlur : when an element loses focus onFocus : when an element gets focus onInvalid : when an element input is not valid onReset : when a form is reset onSubmit : when the form is submitted to the server


Download ppt "JavaScript Part 1. Slide 2 Lecture Overview JavaScript background The purpose of JavaScript JavaScript syntax."

Similar presentations


Ads by Google