lightweight programming language adds interactivity to html pages works in all major browsers ie,...

Download Lightweight programming language  Adds interactivity to HTML pages  Works in all major browsers  IE, Mozilla, Firefox, Netscape, Opera and Safari

If you can't read please download the document

Upload: garry-ryan

Post on 18-Jan-2018

212 views

Category:

Documents


0 download

DESCRIPTION

 Lightweight programming language  Adds interactivity to HTML pages  Works in all major browsers – IE, Mozilla, Firefox, Netscape, Opera and Safari  Is a complementary language – not used on own (embedded into HTML pages)  Primarily used for web-related programming  Consists of lines of executable code (statements)

TRANSCRIPT

Lightweight programming language Adds interactivity to HTML pages Works in all major browsers IE, Mozilla, Firefox, Netscape, Opera and Safari Is a complementary language not used on own (embedded into HTML pages) Primarily used for web-related programming Consists of lines of executable code (statements) Is an interpreted language (no preliminary compilation) No need to purchase a license Used on the client-side (browser) of web application Is the J in the acronym AJAX (Asynchronous JavaScript and XML) JavaScript is not related to Java (Sun Microsystems) Gives web designers a programming tool (code snippets) Dynamic effects on pages document.write( + name + ) Responds to user actions (event-driven) Reads and writes HTML elements Change page appearance text, background Pop-up windows alert, confirm and prompt Flashing grid of coloured squares Flashing grid of coloured squares How to change images on a web page How to affect web pages over time How to add randomness to web pages How to dynamically change whats happening on a web page based on a user action Fish Weight Calculator Fish Weight Calculator Image swaps and rollover effects Drop-down menus Performs calculations Opens new browser windows Form entry validation Create cookies Browser detection Developed by Brendan Eich (Netscape) Together with Sun Microsystems Appeared in all major browsers since then Microsoft developed its own version JScript Official name is ECMAScript (http://www.ecma- international.org)http://www.ecma- international.org ECMA-262 is the official JavaScript standard JavaScript is case sensitive myfunction is not the same as myFunction myvar is not the same as myVar JavaScript ignores white space name=Bedford; Break up code lines (within strings) document.write(Hello \ World!); JavaScript once required a semicolon (;) at the end of each statement Group statements together into blocks by enclosing within curly braces { and } Single line comments //This code will write Hello World to the page Multi-line comments /*This code will write one header and two paragraphs to the page */ JavaScript uses a model called OOP (object-orientated programming) Objects (for example, a window) Properties (for example, length) Methods or actions (for example, open) Events (for example, click) Note: Many programmers argue the notion that JavaScript uses the object-orientated model. JavaScript is an interpreted language Code is run on the fly - no need to compile Only need a text editor and browser Does not perform as efficiently as compiled code Easy to edit and embed in a web page Compiled code tends to be platform specific JavaScript is not var smallNumber = 4; Reserved Word IdentifierOperatorLiteral JavaScript cant be forced on a client JavaScript may be disabled in browser JavaScript is not supported in older browsers JavaScripts fancy features may not be accessible to all text-readers, text-only browsers, accessibility issues JavaScript cant cross domains JavaScript cant ensure data security JavaScript cant access server data or scripts When you develop pages containing JavaScript you have little control over the final appearance or functionality of your page. The script is parsed/interpreted by the browser and the page content displayed according to browser (User Agent) settings and other variables. TEST YOUR PAGES IN AS MANY BROWSERS (AND OTHER PLATFORMS) AS POSSIBLE Test in Mozilla Firefox (roots in Netscape), IE and Apples Safari DONT MAKE NAVIGATION OF YOUR WEBSITE DEPENDENT ON JAVASCRIPT!!! ACCESSIBILITY IS A BIG ISSUE!!! Simplest is NotePad or MAC version Better to use a slightly more complex editor Free downloads from Look for Freeware or Shareware Small total file size Provide colour coding Assist in entering code Code indentation Validate syntax Numbered lines Code snippets Debugging tools Code and design views Integrate with other languages JavaScript, HTML, CSS, Java, ASP, PHP Using JavaScript with HTML pages Where to put your code Commenting your code Special Characters and Escape Sequences Reserved words Variables and Constants Types of Data Naming Conventions Operators Statements and Expressions Functions Global Functions User-Defined Functions Objects Properties, Methods, Event Handlers Control Structures Information used in JavaScript falls into one of two categories: Variables: Items that can contain different values at different times during script execution. Start with the keyword var followed by name. Constants: Contain the same value throughout the execution of the script. Data TypeNameDescriptionExamples BooleanboolEither TRUE or FALSE and is not case sensitive but commonly uppercase TRUE, FALSE Numeric/Floatin g point numbers floatA fractional number with a decimal. May be negative and may use scientific notation 7.34, , 2.31e3 Numeric/Integer s IntA whole number without a decimal. May be negative 43, 928, -4 Numeric/NullnullThe absence of any valueNULL StringstringA series of characters (one of 256 letters, numbers and special characters) enclosed in either single or double quotation marks Mike, Seattle, 1495 W. 18 th St. UndefinedA named variable that has not been assigned a value See later Beware use of predefined or reserved words when naming variables and constants. Their use will cause errors in the code. See later Having created a variable or a constant, you are going to want to give it a value by assignment, calculation or comparison. JavaScript has defined a number of operators of various types: OperatorExplanation ArithmeticPerforms arithmetic calculations on two operands which can be variables, numbers or a number and a variable AssignmentReplace a value with another BitwiseLogical consequences turn specific bits in an integer on or off ComparisonCompare two values and return TRUE or FALSE LogicalLogical consequences Other A statement is a line of code that is complete and correct in its syntax and performs a task. Typically, a statement ends with a semi-colon Often a single line of code ending with a semicolon Can have many statement on a single line Can have a statement spread over many lines Statements contain one or more expressions Expressions are anything that has a value! Values are anything that can be assigned to a variable! A function is a piece of script that does something and can be repeatedly called from a larger script Global functions already exist User-defined functions you need to write Some functions require you to pass them values or arguments Other functions simply return a value These are predefined functions that are not object- specific JavaScript does not have a large library of global functions JavaScript has a large library of methods which are functions related to objects Global functions include: escape(); eval(); isFinite(); isNAN(); parseFloat(); parseInt(); unescape() Allows you to repeatedly use the same code Allows economical use of code dont have to copy to different parts of the page Easy editing Simply create a function containing the code you want to repeat and call that function from everywhere you want to use it Putting function in the header means that it wont be run until it is called User-defined functions can also have one or more arguments that are passed to them,and may return a value after they are executed Objects are the visual elements of a web page windows, buttons, check boxes and dates Can also be more abstract elements such as math calculations and arrays There are many predefined objects You can create your own custom objects as well Identified by a keyword name for example, window You can have several instances of an object in a web page each identified by a unique name Each object can have properties (characteristics) Each object can have methods (the things it can do) for example, alert (), write() Each object can have events (which effect it) for example, mouse click The relationship of an object to its constituents is shown by the use of the dot syntax Objects have properties that allow you to describe them distinguishing different occurrences of the same object from one another For example you can modify a window by outer height and width, or inner display area Some objects have only one property - for example, the string object has only one property length. Properties are applied to an object using the dot statement syntax: objectname.propertyname = value Methods are actions that objects can perform They can be considered predefined functions for objects For example, to return the square root of three, use: math.sqrt(3); Another example: window.alert(Hello World); Event handlers allow you to take advantage of events (or triggers) performed by the user for example, mouse click or page load The event handler recognises the event taking place and then performs one or more tasks adding interactivity to the web page Common event handlers are shown in the next slide: Event HandlerEvent Trigger onAbortAn images loading is interrupted onBlurFocus is removed from an element onChangeContents of a form are changed onClickAn element is single-clicked onDblClickAn element is double-clicked onDragDropAn object is dragged-and-dropped into a window onErrorAn error occurs when loading a web page or picture onFocusThe user places the focus on an element onKeyDownThe user presses a defined key onKeyPressThe user presses and holds down a defined key onKeyUpThe user releases a defined pressed key onLoadA web page completes loading in a browser Event HandlerEvent Trigger onMouseDownThe user presses a mouse button onMouseMoveThe user moves the mouse pointer onMouseOutThe user moves the mouse pointer from a link onMouseOverThe user moves the mouse pointer to a link onMouseUpThe user releases a mouse buton onMoveA window or frame is moved onOpenA web page opens in a browser onResetA form is reset onResizeA window or frame is resized onSelectA field in a form is selected onSubmitA user submits a form onUnloadA user opens another web page Simple scripts are executed from the first statement to the last statement without interruption Often you will want the script to go one way or another or re-execute a particular piece of code This is the purpose of control structures: if/else while do-while for switch A Web Page Title // JavaScript goes here // JavaScript can go here too A Web Page Title // JavaScript in external file // JavaScript can go here too A Web Page Title // JavaScript Goes Here document.write("hello"); document.write(" world"); document.write("Hello World!"); document.write(" This is a header "); My First Page function yetAnotherAlert(textToAlert) { alert(textToAlert); } yetAnotherAlert("This is my first JavaScript!"); My First Page function yetAnotherAlert(textToAlert) { alert(textToAlert); } yetAnotherAlert("This is my first JavaScript!"); yetAnotherAlert("This function has been called from the body of the page!"); My First Page yetAnotherAlert("This function has been called from the body of the page!"); JavaScript code consists of lines (or statements) Use the HTML to embed code in HTML page Every line (statement) ends with ; (semi-colon) Code on HTML page is read/interpreted line by line from the top of the page Can be embedded using the tag in either the An external JavaScript file can also be linked to a web page (.js extension). Dont use the HTML tag in the external.js file Statements can be grouped together as functions which are created and named by the developer function yetAnotherAlert(textToAlert) { alert(textToAlert); } JavaScript is case-sensitive Keywords for example, function are in lowercase Indentation is used to help readability! Use curly braces { } to group statements into blocks Code in functions is only run when functions are called Functions can be called from the or (more usually) the yetAnotherAlert("This is my first JavaScript!"); yetAnotherAlert("This function has been called from the body of the page!"); The function name is always followed by () Arguments (or parameters) can be passed into a function: function yetAnotherAlert(textToAlert) { alert(textToAlert); } yetAnotherAlert("This is my first JavaScript!"); Note the use of " " around literal strings. There are also pre-defined functions (or methods): alert(My name is Sue); or alert(textToAlert); or window.alert(My name is Sue) or window.alert(textToAlert); What is the purpose of using functions? Variables are containers for storing values (literals) Can be used and re-used Rules for naming Begin with [az], [AZ], or _ All subsequent characters [az], [AZ], [19] or _ Variables are case sensitive Should not use JavaScript keywords or reserved words var bedfordvar1 = Bedford1"; var Bedfordvar2 = Bedford2"; var Bedford_var3 = Bedford3"; var _Bedfordvar4 = Bedford4"; var 1Bedfordvar = Bedford5"; var Bedford var2 = Bedford6"; var var = Bedford7"; JavaScript is weakly typed You do not have to declare a datatype You do not even have to declare the variable before use However, it is good practice to declare variable first Arrays are indexes of similar items. Items must have the same datatype. Powerful when used with loops. Datatypes: Null Integer (Decimal, Hexadecimal, Octal) Float (Decimal integer, decimal point, numbers to right of decimal point, and possibly, exponent) Boolean (datatype with two states only) String collection of characters surrounded by double or single quotes var myVariable; myVariable = "some value"; or var myVariable = "some value"; var myVariable = "Hello"; We created a variable in the header. document.write(The variable contains: + myVariable); Outputting a variable var firstname; firstname="Fred"; document.write(firstname); document.write(" "); firstname="Tom"; document.write(firstname); The script above declares a variable, assigns a value to it, displays the value, changes the value, and displays the value again. Changing the value in a variable Any sequence of characters and can contain numbers, letters or other symbols Surrounded by double or single quotes Valid: "Hello there" 'My Phone number is Non-valid: "Hello' What is your name? Combines two text strings into one longer text string: var myVariable = "ab" + "cd"; or var thisVar = cd; var myVariable = "ab" + thisVar; Concatenating strings Three ways of outputting strings \ is the escape operator \ will literally place a quotation mark in a string \n is the new line character Addition: For instance, Subtraction: For instance, 20 10 Multiplication: For instance, 10 * 20 Division: For instance, 20 / 10 Can use complex expressions: 100 / 5 / (5 10) var myVariable = 100 / 5; var myVariable = 100 / thisVar; The assignment operator = is used to assign values to JavaScript variables. The arithmetic operator + is used to add values together. y=5; z=2; x=y+z; What value does x contain? OperatorDescriptionExampleResult + Addition x=y+2 - Subtraction x=y-2 * Multiplication x=y*2 / Division x=y/2 % Modulus (division remainder) x=y%2 ++ Increment x=++y -- Decrement x=--y Given that y=5, the table below explains the arithmetic operators: OperatorDescriptionExampleResult + Addition x=y+2x=7 - Subtraction x=y-2x=3 * Multiplication x=y*2x=10 / Division x=y/2x=2.5 % Modulus (division remainder) x=y%2x=1 ++ Increment x=++yx=6 -- Decrement x=--yx=4 Given that y=5, the table below explains the arithmetic operators: OperatorExampleSame AsResult =x=y +=x+=yx=x+y -=x-=yx=x-y *=x*=yx=x*y /=x/=yx=x/y %=x%=yx=x%y Given that x=10 and y=5, the table below explains the assignment operators: OperatorExampleSame AsResult =x=y x=5 +=x+=yx=x+yx=15 -=x-=yx=x-yx=5 *=x*=yx=x*yx=50 /=x/=yx=x/yx=2 %=x%=yx=x%yx=0 Given that x=10 and y=5, the table below explains the assignment operators: txt1="What a very"; txt2="nice day"; txt3=txt1+" "+txt2; x=5+5; document.write(x); document.write(" "); x="5"+"5"; document.write(x); document.write(" "); x=5+"5"; document.write(x); document.write(" "); x="5"+5; document.write(x); document.write(" "); The common rule is: If you add a number and a string, the result will be a string. Comparison and logical operators are used to test for true or false. Comparison operators are used in logical statements to determine equality or difference between variables or values. Logical operators are used in determine the logic between variables or values. OperatorDescriptionExample == is equal to x==8 is false === is exactly equal to (value and type) x===5 is true x==="5" is false != is not equal x!=8 is true > is greater than x>8 is false < is less than x= is greater than or equal to x>=8 is false