JavaScript. Why JavaScript? Registration form. Online calculator. IT Engineering I Instructor: Ali B. Hashemi. Interaction

Size: px
Start display at page:

Download "JavaScript. Why JavaScript? Registration form. Online calculator. IT Engineering I Instructor: Ali B. Hashemi. Interaction"

Transcription

1 JavaScript Why JavaScript? HTML role on the Web Purpose tell the browser how a document should appear Static can view or print (no interaction) IT Engineering I Instructor: Ali B. Hashemi JavaScript s role on the Web Purpose make web pages more dynamic and interactive Change contents of document, provide forms and controls, animation, control web browser window, etc. Developed by Netscape for use in Navigator Web Browsers 1 2 Online calculator Registration form Interaction So Scripting What is needed? 3 4 1

2 Overview Relationship of client-side and server-side Javascript Originally called LiveScript when introduced in Netscape Navigator In Navigator 2.0, name changed to JavaScript Current version 1.5 JScript MS version of JavaScript Current version 5.5 Two formats: Client-side Program runs on client (browser) Server-side Program runs on server Proprietary to web server platform 5 6 Overview (cont.) A "scripting" language for HTML pages Embed code in HTML pages so they are downloaded directly to browser The browser interprets and executes the script (it is not compiled) Do not declare data types for variables (loose typing) Dynamic binding object references checked at runtime Overview (cont.) Scripts can manipulate browser objects : HTML form elements Images Frames etc. For security cannot write to disk (when run on a client) 7 8 2

3 JavaScript's abilities Generating HTML content dynamically Monitoring and responding to user events Validate forms before submission Manipulate HTTP cookies Interact with the frames and windows of the browser Customize pages to suit users JavaScript is not Java Java : compilation required (not a script) can create stand alone application object-oriented Why is it called Javascript then? purely a marketing trick JavaScript was originally called LiveScript Its name was changed to JavaScript at the last minute 9 10 Java (platform independent) You Your Computer Java Source Code Java Compiler (Mac) Java Compiler (PC) Java Compiler (Unix) Java Byte Code Byte Code Placed on Web Server for Download Java Byte Code Web Server Web Architecture for JavaScript "CLIENT" Desktop access Web browser HTML Page: <SCRIPT> code.. </SCRIPT> HTML/HTTP TCP/IP Internet HTML/HTTP TCP/IP "SERVER" Remote host Web (HTTP) Server Java Interpreter (Mac) Java Interpreter (PC) Java Interpreter (Unix) Client Using Web Browser 11 built-in JavaScript interpreter HTML pages w/ embedded script 12 3

4 JavaScript Versions A First JavaScript Program JavaScript 1.0 The original version of the language. It was buggy and is now essentially obsolete. Implemented by Netscape 2. JavaScript 1.1 Introduced a true Array object; most serious bugs resolved. Implemented by Netscape 3. JavaScript 1.2 Introduced the switch statement, regular expressions, and a number of other features. Almost compliant with ECMA v1, but has some incompatibilities. Implemented by Netscape 4. JavaScript 1.3 Fixed incompatibilities of JavaScript 1.2. Compliant with ECMA v1. Implemented by Netscape 4.5. JavaScript 1.4 Implemented only in Netscape server products. JavaScript 1.5 Introduced exception handling. Compliant with ECMA v3. Implemented by Mozilla and Netscape 6. How to create a JavaScript source file How to add comments to a JavaScript Program How to hide JavaScript from incompatible browsers About placing JavaScript in <head> or <body> sections of HTML documents A First JavaScript Program The <script> Tag JavaScript programs are run from within an HTML document <script> and </script> Used to notify the browser that JavaScript statements are contained within A First JavaScript Program The <script> Tag language attribute Denotes the scripting language being used Default JavaScript Other languages (e.g., VBScript) may be used Can also specify script language version No space between name and version Checked by browser, scripts ignored if browser doesn t support version For ECMAScript compatible browsers, omit version

5 A First JavaScript Program Object-based language Object Programming code and data that can be treated as an individual unit or component Statements Individual lines in a programming language Methods Groups of statements related to a particular object A First JavaScript Program Document object Represents the content of a browser s window write() & writeln() methods of Document object Creates new text on a web page Called by appending method to object with a period Methods accept arguments Information passed to a method A First JavaScript Program Preformatted text <pre> and </pre> tags To indicate text that shouldn't be formatted by the browser. The text enclosed within a <pre> tag retains all spacing and returns, and doesn't reflow when the browser is resized. Scrollbars and horizontal scrolling are required if the lines are longer than the width of the window. Translates literal text to presentation area Required to get carriage return in writeln() method to be sent to presentation area JavaScript: Hello world

6 JavaScript: Hello world (output!) Document object Document object Considered a top-level object Naming convention Capitalize first letter of object Unlike HTML, JavaScript is case sensitive JavaScript Source File JavaScript programs can be used in two ways: Incorporated directly into an HTML file Using <script> tag Placed in an external (source) file Has file extension.js Contains only JavaScript statements

7 JavaScript Source File (cont.) Creating a JavaScript Source File JavaScript source files Use src attribute of <script> tag to denote source of JavaScript statements Browser will ignore any JavaScript statements inside <script> and </script> if src attribute is used Cannot include HTML tags in source file Advantages of JavaScript source files Makes HTML document neater (less confusing) JavaScript can be shared among multiple HTML files Hides JavaScript code from incompatible browsers <script language= JavaScript JavaScript src= c: c:\source.js > </script> JavaScript: Source File & embedded Can use a combination of embedded and non embedded code Allows finer granularity in coding functionality JavaScript sections executed in order of location within HTML document Example of JavaScript: Source File & embedded

8 Comments in JavaScript Comments in JavaScript (example) Makes it easier to understand the code operation Two types Line comments // ignore all text to the end of the line Block comments /* ignore all text between these symbols */ Hiding JavaScript from Incompatible Browsers Hiding JavaScript from Incompatible Browsers (example) Two methods Place JavaScript in external source file Enclose the code within HTML comments <!-- beginning of HTML block comment end of HTML block comments -->

9 Hiding JavaScript from Incompatible Browsers (example) Hiding JavaScript from Incompatible Browsers (example) Hiding JavaScript from Incompatible Browsers Hiding JavaScript from Incompatible Browsers (example) Alternate message display If browser doesn t support JavaScript Use <noscript> & </noscript> to place alternate message to users of back-level browsers

10 Placing JavaScript in <head> or <body> sections JavaScript keywords Script statements interpreted in order of document rendering <head> section rendered before <body> section Good practice to place as much code as possible in <head> section JavaScript keywords (cont.) Working with Variables, Functions, and Objects Variables (or identifiers) Values stored in computer memory locations Value can vary over time Cannot use reserved words as variables Reserved Words or Keywords are part of the JavaScript language syntax Variable Example: employeename

11 Working with Variables, Functions, and Objects Variables To create: Use keyword var to declare the variable Use the assignment operator to assign the variable a value Declare, then assign value (initialize) var employeename; employeename = Ric ; Declare and assign variable in a single statement var employeename = Ric ; Variables Once created: May be changed at any point in the program Use variable name and assignment operator employeename = Althea ; Variables Syntax rules Cannot use: Reserved words & spaces Must begin with one of the following: Uppercase or lowercase ASCII letter Dollar sign ($) or underscore (_) Can use numbers, but not as first character Variables are case-sensitive Variables Conventions Use underscore or capitalization to separate words of an identifier employee_first_name employeefirstname My_variable $my_variable _my_variable

12 Illegal variable names Operators (I) Arithmetic operators (all numbers are floating-point): + - * / % Comparison operators: < <= ==!= >= > Logical operators: &&! (&& and are short-circuit operators) Bitwise operators: & ^ ~ << >> >>> Assignment operators: += -= *= /= %= <<= >>= >>>= &= ^= = Operators (II) Object literals String operator: + The conditional operator: condition? value_if_true : value_if_false Special equality tests: == and!= try to convert their operands to the same type before performing the test === and!== consider their operands unequal if they are of different types Additional operators (to be discussed): new You don t declare the types of variables in JavaScript JavaScript has object literals, written with this syntax: { name1 : value1,..., namen : valuen } Example (from Netscape s documentation): car = {mycar: "Saturn", getcar: CarTypes("Honda"), special: Sales} The fields are mycar, getcar, and special "Saturn" and "Mazda" are Strings CarTypes is a function call Sales is a variable you defined earlier Example use: document.write("i own a " + car.mycar);

13 Three ways to create an object You can use an object literal: var course = { number: "CIT597", teacher: "Dr. Dave" } You can use new to create a blank object, and add fields to it later: var course = new Object(); course.number = "CIT597"; course.teacher = "Dr. Dave"; You can write and use a constructor: function Course(n, t) { // best placed in <head> this.number = n; // keyword "this" is required, not optional this.teacher = t; } var course = new Course("CIT597", "Dr. Dave"); Array literals JavaScript has array literals, written with brackets and commas Example: color = ["red", "yellow", "green", "blue"]; Arrays are zero-based: color[0] is "red If you put two commas in a row, the array has an empty element in that location Example: color = ["red",,, "green", "blue"]; color has 5 elements However, a single comma at the end is ignored Example: color = ["red",,, "green", "blue,]; still has 5 elements Four ways to create an array The length of an array You can use an array literal: var colors = ["red", "green", "blue"]; You can use new Array() to create an empty array: var colors = new Array(); You can add elements to the array later: colors[0] = "red"; colors[2] = "blue"; colors[1]="green"; You can use new Array(n) with a single numeric argument to create an array of that size var colors = new Array(3); You can use new Array( ) with two or more arguments to create an array containing those values: var colors = new Array("red","green", "blue"); If myarray is an array, its length is given by myarray.length Array length can be changed by assignment beyond the current length Example: var myarray = new Array(5); myarray[10] = 3; Arrays are sparse, that is, space is only allocated for elements that have been assigned a value Example: myarray[50000] = 3; is perfectly OK But indices must be between 0 and Just array of arrays: var a = [ ["red", 255], ["green", 128] ]; var b = a[1][0]; // b is now "green"

14 Arrays and objects Array functions Arrays are objects car = { mycar: "Saturn", 7: "Mazda" } car[7] is the same as car.7 car.mycar is the same as car["mycar"] If you know the name of a property, you can use dot notation: car.mycar If you don t know the name of a property, but you have it in a variable (or can compute it), you must use array notation: car["my" + "Car"] If myarray is an array, myarray.sort() sorts the array alphabetically myarray.sort(function(a, b) { return a - b; }) sorts numerically myarray.reverse() reverses the array elements myarray.push( ) adds any number of new elements to the end of the array, and increases the array s length myarray.pop() removes and returns the last element of the array, and decrements the array s length myarray.tostring() returns a string containing the values of the array elements, separated by commas The for in statement The with statement You can loop through all the properties of an object with for (variable in object) statement; for (var prop in course) { document.write(prop + ": " + course[prop]); } Possible output: teacher: Dr. Dave number: CIT597 The properties are accessed in an undefined order If you add or delete properties of the object within the loop, it is undefined whether the loop will visit those properties Arrays are objects; applied to an array, for in will visit the properties 0, 1, 2, course["teacher"] is equivalent to course.teacher You must use brackets if the property name is in a variable 55 with (object) statement ; uses the object as the default prefix for variables in the statement For example, the following are equivalent: with (document.myform) { result.value = compute(myinput.value) ; } document.myform.result.value = compute(document.myform.myinput.value); 56 14

15 Regular expressions Defining Custom Functions A regular expression can be written in either of two ways: Within slashes, such as re = /ab+c/ With a constructor, such as re = new RegExp("ab+c") Regular expressions are almost the same as in Perl or Java (only a few unusual features are missing) string.match(regexp) searches string for an occurrence of regexp It returns null if nothing is found If regexp has the g (global search) flag set, match returns an array of matched substrings If g is not set, match returns an array whose 0 th element is the matched text, extra elements are the parenthesized subexpressions, and the index property is the start position of the matched substring Function: Individual statements grouped together to form a specific procedure Allows you to treat the group of statements as a single unit Must be contained between <script> and </script> tags Must be formally composed (function definition) Defining Custom Functions (cont.) Custom Function example A function definition consists of three parts: Reserved word function followed by the function name (identifier) Parameters required by the function, contained within parentheses following the name Parameters variables used within the function Zero or more may be used Function statements, delimited by curly braces { }

16 Returning a value from a Function A function can return nothing Just performing some task A function can return a value Perform a calculation and return the result Var returnvalue = functioncall(opone, optwo); A return statement must be added to function definition 61 Function call Function invocation or call Statement including function name followed by a list of arguments in parentheses Parameter of function definition takes on value of argument passed to function in function call Code placement Functions must be created (defined) before called <head> rendered by browser before <body> Function definition Place in <head> section Function call Place in <body> section 62 Built-in JavaScript Functions Built-in JavaScript Functions (cont.) Functions defined as part of the JavaScript language Function call identical to the custom functions

17 Understanding JavaScript Objects In OO languages (Java, C++) Class structures contain associated variables, methods (functions) and statements Objects are instances of classes (i.e., objects are instantiated from classes) Classes can be inherited from other classes JavaScript is not truly object-oriented oriented Cannot create classes Custom JavaScript objects Based on constructor functions Instantiate a new object or extending an old object Objects inherit all variables and statements of constructor function Any JavaScript function can serve as a constructor Constructor function Has two types of elements Property (field) Variable within a constructor function Data of the object Method Function called from within an object Can be custom or built-in function Constructor function Identifier naming convention First word uppercase to differentiate from non-constructor functions BankEmployee The this keyword Used in constructor functions to refer to the current object that called the constructor function

18 The new keyword Built-in JavaScript objects Used to create new objects from constructor functions Example: Achmed = new BankEmployee(name, empnum); JavaScript includes 11 built-in objects Each object contains various methods and properties for performing a particular task Can be used directly in program without instantiating a new object Built-in JavaScript objects (cont.) Custom object inheritance and prototypes Objects inherit the properties and methods of their constructor function Constructor functions: Do not require parameters Do not require passed arguments Properties may set the value at a later time If used before set, will return an undefined value

19 Custom object inheritance and prototypes Adding properties after object is instantiated Properties can be added to objects using dot operator (.) These properties available only to that specific object Prototype properties Properties added using prototype keyword Available to all objects that extend the constructor function BankEmployee.prototype.department = ; Custom object inheritance and prototypes Object definitions can extend other object definitions Extend original definition and add new properties or function calls Custom object inheritance and prototypes (example) Custom object methods Functions associated with a particular object Define the function Use the this reference to refer to object properties Add it to the constructor function this.methodname = functionname Call the method using the dot operator (.)

20 Variable Scope Defines where in the program a declared variable can be used Global variable Declared outside a function and is available to all parts of the program var keyword optional Local variable Declared inside a function and is only available within the function it is declared Global and local variables can use same identifier Using Events Understanding Events A specific circumstance that is monitored by JavaScript or, A trigger that fires specific JavaScript code in response to a given situation e.g., an action that a user takes Two basic types of Events JavaScript events User-generated events e.g., mouse-click System-generated events e.g., load event triggered by web browser when HTML document finishes loading

21 Using Events HTML elements and associated events HTML Tags and Events HTML elements allow user to trigger events <input> tag Type attribute determines type of input field <input type= text name= first_name > creates a text field Name attribute assigns a unique name to the element that JavaScript can use to reference it HTML elements and associated events Event Handlers Code that executes in response to a specific event <HTMLtag eventhandler= JavaScript-code > Event handler naming convention Event name with a prefix of on E.g., onclick <input type= button onclick= alert( You clicked the button! ) >

22 Built-in JavaScript utility methods alert() method Displays a pop-up dialog box with an OK button javascript:alert("this is the result of an alert"); prompt() method Displays a pop-up dialog box with a message, a text box, an OK button, and a Cancel button javascript:prompt("this is the result of an Prompt","default value in text box"); Using Events (Links) Using Events (Links) Links Used to open files or navigate to other documents on the web Text or image used to represent a link in an HTML document is called an anchor Use anchor tag <a> to process a URL Two types of URL Absolute Refers to the specific location of the document C:\webpages\homepage.html Relative Refers to location of document according to the location of currently loaded document /subdirectory/otherpage.html Increases portability of web site

23 Using Events (Links) Onclick() example Primary event is the click event For default operation, no event handler is required Overriding the default click event Add onclick event handler that executes custom code Event handler must return true or false Can use built-in confirm() method to generate Boolean value Onclick() example Events and event handlers Event Applies to Occurs when Handler Load Document body User loads the page in a browser onload Unload Document body User exits the page onunload Error Images, window Error on loading an image or a window onerror 91 Abort Images User aborts the loading of an image onabort 92 23

24 Events and event handlers(cont.) Events and event handlers(cont.) Event KeyDown KeyUp KeyPress Change Applies to Documents, images, links, text areas Documents, images, links, text areas Documents, images, links, text areas Text fields, text areas, select lists Occurs when User depresses a key User releases a key User presses or holds down a key User changes the value of an element Handler onkeydown onkeyup onkeypress onchange 93 Event MouseDown MouseUp Click Applies to Documents, buttons, links Documents, buttons, links Buttons, radio buttons, checkboxes, submit buttons, reset buttons, links Occurs when User depresses a mouse button User releases a mouse button User clicks a form element or link Handler onmousedown onmouseup onclick 94 Events and event handlers(cont.) Events and event handlers(cont.) Event MouseOver MouseOut Select Applies to Links Areas, links Text fields, text areas Occurs when User moves cursor over a link User moves cursor out of an image map or link User selects form element s input field Handler onmouseover onmouseout onselect Event Move Resize DragDrop Applies to Windows Windows Windows Occurs when User or script moves a window User or script resizes a window User drops an object onto the browser window Handler onmove onresize ondragdrop

25 Events and event handlers(cont.) DOM Event Focus Blur Reset Applies to Windows and all form elements Windows and all form elements Forms Occurs when User gives element input focus User moves focus to some other element User clicks a Reset button Handler onfocus onblur onreset Document Object Model DOM hierarchy Submit Forms User clicks a Submit button onsubmit Fields of window, I Fields of window, II window The current window (not usually needed). self Same as window. parent If in a frame, the immediately enclosing window. top If in a frame, the outermost enclosing window. frames[ ] An array of frames (if any) within the current window. Frames are themselves windows. length The number of frames contained in this window. document The HTML document being displayed in this window. location The URL of the document being displayed in this window. If you set this property to a new URL, that URL will be loaded into this window. Calling location.reload() will refresh the window. navigator A reference to the Navigator (browser) object. Some properties of Navigator are: appname -- the name of the browser, such as "Netscape" platform -- the computer running the browser, such as "Win32" status A read/write string displayed in the status area of the browser window. Can be changed with a simple assignment statement

26 Methods of window, I alert(string) Displays an alert dialog box containing the string and an OK button. confirm(string) Displays a confirmation box containing the string along with Cancel and OK buttons. Returns true if OK is pressed, false if Cancel is pressed. prompt(string) Displays a confirmation box containing the string, a text field, and Cancel and OK buttons. Returns the string entered by the user if OK is pressed, null if Cancel is pressed. open(url) Opens a new window containing the document specified by the URL. close() Closes the given window (which should be a top-level window, not a frame) Fields of document, I You must prefix these fields with document. anchors[ ] An array of Anchor objects (objects representing <a name=...> tags) applets[ ] An array of Applet objects The properties are the public fields defined in the applet The methods are the public methods of the applet Cautions: You must supply values of the correct types for the fields and method parameters Changes and method calls are done in a separate Thread Fields of document, II forms[ ] An array of Form elements If the document contains only one form, it is forms[0] images[ ] An array of Image objects To change the image, assign a new URL to the src property links[ ] An array of Link objects A link has several properties, including href, which holds the complete URL

27 Fields of document, III bgcolor The background color of the document May be changed at any time Fields of the form object elements[ ] An array of form elements title A read-only string containing the title of the document URL A read-only string containing the URL of the document Creating an Image Map Creating an Image Map (coordination) An image divided into regions Each region associated with URL via the <a> tag Use <img>, <map>, and <area> tags to create an image map Areas are divided using pixel coordinates of image Picture elements

28 Creating an Image Map (cont.) Two basic types Client-side Part of an HTML document Server-side Code resides on a web server Creating an Image Map Process Place image in document using <img> tag Use usemap attribute to reference image map by name Define image map using <map> tag Use name attribute to give map a name Define image map regions using <area> tag Use shape attribute to specify shape of region rect, circle, poly Common <AREA> tag attributes

29 Try it! javascript: R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24; x4=300; y4=200; x5=300; y5=200; DI=document.images; DIL=DI.length; function A(){ for(i=0; i<dil; i++){ DIS=DI[ i ].style; DIS.position='absolute'; DIS.left=Math.sin(R*x1+i*x2+x3)*x4+x5; DIS.top=Math.cos(R*y1+i*y2+y3)*y4+y5 } R++ } setinterval('a()',5); void(0) 113 Debugging Mozilla/Netscape has much better debugging tools than IE Firefox Select Tools =>Error Console Mozilla Select Tools => Web Development => JavaScript console Netscape 6: Select Tasks => Tools => JavaScript console Any Mozilla or Netscape: Type javascript: in the location bar and press Enter Internet Explorer: Go to the Preferences... dialog and look for something like Web content => Show scripting error alerts After debugging, test your program in IE IE is the most popular browser 114 Warnings Numbers JavaScript is a big, complex language We ve only scratched the surface It s easy to get started in JavaScript, but if you need to use it heavily, plan to invest time in learning it well Write and test your programs a little bit at a time JavaScript is not totally platform independent Expect different browsers to behave differently Write and test your programs a little bit at a time Browsers aren t designed to report errors Don t expect to get any helpful error messages Write and test your programs a little bit at a time In JavaScript, all numbers are floating point Special predefined numbers: Infinity, Number.POSITIVE_INFINITY -- the result of dividing a positive number by zero Number.NEGATIVE_INFINITY -- the result of dividing a negative number by zero NaN, Number.NaN (Not a Number) -- the result of dividing 0/0 NaN is unequal to everything, even itself There is a global isnan() function Number.MAX_VALUE -- the largest representable number Number.MIN_VALUE -- the smallest (closest to zero) representable number

30 Strings and characters Some string methods Strings are surrounded by either single quotes or double quotes \0 NUL \b backspace \f form feed \n newline \r carriage return \t horizontal tab \v vertical tab \' single quote \" double quote \\ backslash \xdd Unicode hex DD \xdddd Unicode hex DDDD charat(n) Returns the nth character of a string concat(string1,..., stringn) Concatenates the string arguments to the recipient string indexof(substring) Returns the position of the first character of substring in the recipient string, or -1 if not found indexof(substring, start) Returns the position of the first character of substring in the given string that begins at or after position start, or -1 if not found lastindexof(substring), lastindexof(substring, start) Like indexof, but searching starts from the end of the recipient string More string methods boolean match(regexp regexp) Returns an array containing the results, or null if no match is found On a successful match: If g (global) is set, the array contains the matched substrings If g is not set: Array location 0 contains the matched text Locations 1... contain text matched by parenthesized groups The array index property gives the first matched position replace(regexp regexp, replacement) Returns a new string that has the matched substring replaced with the replacement search(regexp regexp) Returns the position of the first matched substring in the given string, or -1 if not found. 119 The boolean values are true and false When converted to a boolean, the following values are also false: 0 "0" and '0' The empty string, '' or "" undefined null NaN

31 undefined and null Wrappers and conversions There are special values undefined and null undefined is the only value of its type This is the value of a variable that has been declared but not defined, or an object property that does not exist void is an operator that, applied to any value, returns the value undefined null is an object with no properties null and undefined are == but not === JavaScript has wrapper objects for when a primitive value must be treated as an object var s = new String("Hello"); // s is now a String var n = new Number(5); // n is now a Number var b = new Boolean(true); // b is now a Boolean Because JavaScript does automatic conversions as needed, wrapper objects are hardly ever needed JavaScript has no casts, but conversions can be forced var s = x + ""; // s is now a string var n = x + 0; // n is now a number var b =!!x; // b is now a boolean Because JavaScript does automatic conversions as needed, explicit conversions are hardly ever needed HTML names in JavaScript In HTML the window is the global object The most important window property is document HTML form elements can be referred to by document.forms[formnumber].elements[elementnumber] Every HTML form element has a name attribute The name can be used in place of the array reference <form name="myform"> <input type="button" name="mybutton"...> Then instead of document.forms[0].elements[0] you can say document.myform.mybutton 123 JavaScript Examples

32 Getting the date <script type="text/javascript"> var d = new Date() document.write(d.getdate() + "/") document.write((d.getmonth() + 1) + "/") document.write(d.getfullyear()) </script> 27/10/2003 Getting and formatting the date <script type="text/javascript"> var d=new Date() var weekday=new Array ("Sunday", "Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday") var monthname=new Array("Jan", "Feb", "Mar","Apr", May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") document.write(weekday[d.getday()] + ", "); document.write(monthname[d.getmonth()] + " " + d.getdate() + ", "); document.write(d.getfullyear()); </script> Monday, Oct 27, Getting a random number The following code gets a random floating-point number between 0 and 1: <script type="text/javascript"> document.write(math.random()) </script> Getting a random integer The following code gets a random integer between 1 and 10: <script type="text/javascript"> var max = 10; number=math.random()*max + 1; document.write(math.floor(number)); </script>

33 Displaying an alert box The following code displays an alert box when a button is clicked: <form> // Buttons can only occur within form <input type="button" name="submit" value="alert! onclick="alert('oh oh, something happened!');"> </form> Telling what happened In the <head> of the HTML page define: <script> <!-- function tell(a, b) { document.forms[0].result.value+="\n"+a+": " + b; } //--> </script> For each form element, I have a handler for every (plausible) event Telling what happened (Button) Sorting a Table (i) <input type="button" name="plainbutton" value="plain Button onmousedown="tell(this.name, 'onmousedown');" onmouseup="tell(this.name, 'onmouseup');" onclick="tell(this.name,'onclick');" ondblclick="tell(this.name,'ondblclick'); onfocus="tell(this.name, 'onfocus'); onblur="tell(this.name, 'onblur'); onmouseover="tell(this.name, 'onmouseover');" onmouseout="tell(this.name, 'onmouseout');" onchange="tell(this.name, 'onchange'); onkeypress="tell(this.name, 'onkeypress'); onkeydown="tell(this.name, 'onkeydown'); onkeyup="tell(this.name, 'onkeyup'); onselect="tell(this.name, 'onselect'); onreset="tell(this.name, 'onreset'); > <title>web Page</title> <table border="1" name="table0"><br> <tr><th><a href="?sortby=names">name</a> <th><a href="?sortby=ranks">rank</a> <th><a href="?sortby=indexes">index</a> <script language="javascript"> <!-- html comment var indexes = new Array(0, 1, 2, 3, 4, 5); var names = new Array("John", "Mary", "Adam", "Zoe", "Otis", "Sarah"); var ranks = new Array(4, 5, 1, 3, 6, 2); var sortarray = indexes; //document.writeln(document.url + "<br>"); var sortparamindex = document.url.lastindexof("sortby=");

34 Sorting a Table (ii) if( sortparamindex!= -1 ) { var sortbystr = document.url.slice(sortparamindex+7); // document.writeln(sortbystr + "<br>"); if( sortbystr === "names" ) sortarray = names; if( sortbystr === "ranks" ) sortarray = ranks; if( sortbystr === "indexes" ) sortarray = indexes; } function printrow(name, rank, index) { document.writeln("<tr><td>" + name + "<TD>" + rank + "<TD>" + index); } 133 Sorting a Table (iii) function getnext(arr, lastindex) { // find the next best var bestvalue = arr[0]; var bestindex = 0; var isfirst = (lastindex < 0); var lastvalue = arr[lastindex]; for(i=1; i < arr.length; i++) { var islower = (arr[i] < bestvalue); var notprevious = (isfirst arr[i] > lastvalue); var isbestprevious = (!isfirst && (bestvalue <= lastvalue)); if( (islower && notprevious) isbestprevious ) { bestvalue = arr[i]; bestindex = i; } } return bestindex; } var index = getnext(sortarray, -1); for(k=0; k < sortarray.length; k++ ) { printrow(names[index], ranks[index], index); index = getnext(sortarray, index); } // --></script></table> 134 Basic Rollover <a href=" onmouseover="document.my_image.src= sign_new.gif'" onmouseout="document.my_image.src= sign.gif'"> <img src= sign.gif" width="30px" height="31px" border="0" name= my_image" alt= My Image"> </a>

JavaScript. Why JavaScript? Dynamic Form Validation. Online calculator. IT Engineering I Instructor: Ali B. Hashemi. Interaction

JavaScript. Why JavaScript? Dynamic Form Validation. Online calculator. IT Engineering I Instructor: Ali B. Hashemi. Interaction JavaScript Why JavaScript? HTML s role on the Web Purpose tell the browser how a document should appear Static fixed view (no interaction) IT Engineering I Instructor: Ali B. Hashemi JavaScript s role

More information

JavaScript. IT Engineering I Instructor: Ali B. Hashemi

JavaScript. IT Engineering I Instructor: Ali B. Hashemi JavaScript IT Engineering I Instructor: Ali B. Hashemi ١ ١ Why JavaScript? HTML s role on the Web Purpose tell the browser how a document should appear Static fixed view (no interaction) JavaScript s role

More information

JavaScript. IT Engineering I Instructor: Ali B. Hashemi

JavaScript. IT Engineering I Instructor: Ali B. Hashemi JavaScript IT Engineering I Instructor: Ali B. Hashemi 1 1 Why JavaScript? HTML s role on the Web Purpose tell the browser how a document should appear Static fixed view (no interaction) JavaScript s role

More information

710 Index Attributes, 127 action attribute, 263 assigning, bottom attribute, domain name attribute, 481 expiration date attribute, 480 8

710 Index Attributes, 127 action attribute, 263 assigning, bottom attribute, domain name attribute, 481 expiration date attribute, 480 8 INDEX Symbols = (assignment operator), 56 \ (backslash), 33 \b (backspace), 33 \" (double quotation mark), 32 \e (escape), 33 \f (form feed), 33

More information

Fundamentals of Website Development

Fundamentals of Website Development Fundamentals of Website Development CSC 2320, Fall 2015 The Department of Computer Science Events handler Element with attribute onclick. Onclick with call function Function defined in your script or library.

More information

New Perspectives on Creating Web Pages with HTML. Tutorial Objectives

New Perspectives on Creating Web Pages with HTML. Tutorial Objectives New Perspectives on Creating Web Pages with HTML Tutorial 9: Working with JavaScript Objects and Events 1 Tutorial Objectives Learn about form validation Study the object-based nature of the JavaScript

More information

JavaScript and XHTML. Prof. D. Krupesha, PESIT, Bangalore

JavaScript and XHTML. Prof. D. Krupesha, PESIT, Bangalore JavaScript and XHTML Prof. D. Krupesha, PESIT, Bangalore Why is JavaScript Important? It is simple and lots of scripts available in public domain and easy to use. It is used for client-side scripting.

More information

CISH-6510 Web Application Design and Development. Overview of JavaScript. Overview

CISH-6510 Web Application Design and Development. Overview of JavaScript. Overview CISH-6510 Web Application Design and Development Overview of JavaScript Overview What is JavaScript? History Uses of JavaScript Location of Code Simple Alert Example Events Events Example Color Example

More information

Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world

Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world Visit us on the World Wide Web at: www.pearsoned.co.uk Pearson Education Limited 2014

More information

CSC Web Programming. Introduction to JavaScript

CSC Web Programming. Introduction to JavaScript CSC 242 - Web Programming Introduction to JavaScript JavaScript JavaScript is a client-side scripting language the code is executed by the web browser JavaScript is an embedded language it relies on its

More information

CGS 3066: Spring 2015 JavaScript Reference

CGS 3066: Spring 2015 JavaScript Reference CGS 3066: Spring 2015 JavaScript Reference Can also be used as a study guide. Only covers topics discussed in class. 1 Introduction JavaScript is a scripting language produced by Netscape for use within

More information

Client-Side Web Technologies. JavaScript Part I

Client-Side Web Technologies. JavaScript Part I Client-Side Web Technologies JavaScript Part I JavaScript First appeared in 1996 in Netscape Navigator Main purpose was to handle input validation that was currently being done server-side Now a powerful

More information

Want to add cool effects like rollovers and pop-up windows?

Want to add cool effects like rollovers and pop-up windows? Chapter 10 Adding Interactivity with Behaviors In This Chapter Adding behaviors to your Web page Creating image rollovers Using the Swap Image behavior Launching a new browser window Editing your behaviors

More information

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript CS 4640 Programming Languages for Web Applications JavaScript CS 4640 Programming Languages for Web Applications 1 How HTML, CSS, and JS Fit Together {css} javascript() Content layer The HTML gives the page structure and adds semantics Presentation

More information

LECTURE-3. Exceptions JS Events. CS3101: Programming Languages: Javascript Ramana Isukapalli

LECTURE-3. Exceptions JS Events. CS3101: Programming Languages: Javascript Ramana Isukapalli LECTURE-3 Exceptions JS Events 1 EXCEPTIONS Syntax and usage Similar to Java/C++ exception handling try { // your code here catch (excptn) { // handle error // optional throw 2 EXCEPTIONS EXAMPLE

More information

Chapter 3 Data Types and Variables

Chapter 3 Data Types and Variables Chapter 3 Data Types and Variables Adapted from JavaScript: The Complete Reference 2 nd Edition by Thomas Powell & Fritz Schneider 2004 Thomas Powell, Fritz Schneider, McGraw-Hill Jargon Review Variable

More information

JavaScript: The Basics

JavaScript: The Basics JavaScript: The Basics CISC 282 October 4, 2017 JavaScript A programming language "Lightweight" and versatile Not universally respected Appreciated in the web domain Adds programmatic functionality to

More information

3 The Building Blocks: Data Types, Literals, and Variables

3 The Building Blocks: Data Types, Literals, and Variables chapter 3 The Building Blocks: Data Types, Literals, and Variables 3.1 Data Types A program can do many things, including calculations, sorting names, preparing phone lists, displaying images, validating

More information

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript CS 4640 Programming Languages for Web Applications JavaScript CS 4640 Programming Languages for Web Applications 1 How HTML, CSS, and JS Fit Together {css} javascript() Content layer The HTML gives the page structure and adds semantics Presentation

More information

Regular Expressions. Regular expressions are a powerful search-and-replace technique that is widely used in other environments (such as Unix and Perl)

Regular Expressions. Regular expressions are a powerful search-and-replace technique that is widely used in other environments (such as Unix and Perl) Regular Expressions Regular expressions are a powerful search-and-replace technique that is widely used in other environments (such as Unix and Perl) JavaScript started supporting regular expressions in

More information

LECTURE-2. Functions review HTML Forms. Arrays Exceptions Events. CS3101: Scripting Languages: Javascript Ramana Isukapalli

LECTURE-2. Functions review HTML Forms. Arrays Exceptions Events. CS3101: Scripting Languages: Javascript Ramana Isukapalli LECTURE-2 Functions review HTML Forms Arrays Exceptions Events 1 JAVASCRIPT FUNCTIONS, REVIEW Syntax function (params) { // code Note: Parameters do NOT have variable type. 1. Recall: Function

More information

JavaScript Handling Events Page 1

JavaScript Handling Events Page 1 JavaScript Handling Events Page 1 1 2 3 4 5 6 7 8 Handling Events JavaScript JavaScript Events (Page 1) An HTML event is something interesting that happens to an HTML element Can include: Web document

More information

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications JavaScript Started as a simple script in a Web page that is interpreted and run by the browser Supported by most modern browsers Allows dynamic update of a web page More generally, allows running an arbitrary

More information

Introduction to DHTML

Introduction to DHTML Introduction to DHTML HTML is based on thinking of a web page like a printed page: a document that is rendered once and that is static once rendered. The idea behind Dynamic HTML (DHTML), however, is to

More information

JAVASCRIPT BASICS. Handling Events In JavaScript. In programing, event-driven programming could be a programming

JAVASCRIPT BASICS. Handling Events In JavaScript. In programing, event-driven programming could be a programming Handling s In JavaScript In programing, event-driven programming could be a programming paradigm during which the flow of the program is set by events like user actions (mouse clicks, key presses), sensor

More information

CSI 3140 WWW Structures, Techniques and Standards. Browsers and the DOM

CSI 3140 WWW Structures, Techniques and Standards. Browsers and the DOM CSI 3140 WWW Structures, Techniques and Standards Browsers and the DOM Overview The Document Object Model (DOM) is an API that allows programs to interact with HTML (or XML) documents In typical browsers,

More information

Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript

Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript Program Structure function sqr(i) var result; // Otherwise result would be global. result = i * i; //

More information

By the end of this section of the practical, the students should be able to:

By the end of this section of the practical, the students should be able to: By the end of this section of the practical, the students should be able to: Write JavaScript to generate HTML Create simple scripts which include input and output statements, arithmetic, relational and

More information

Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript

Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript Program Structure function sqr(i) var result; // Otherwise result would be global. result = i * i; //

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Lecture 3: The Basics of JavaScript. Background. Needs for Programming Capability. Origin of JavaScript. Using Client-side JavaScript

Lecture 3: The Basics of JavaScript. Background. Needs for Programming Capability. Origin of JavaScript. Using Client-side JavaScript Lecture 3: The Basics of JavaScript Wendy Liu CSC309F Fall 2007 Background Origin and facts 1 2 Needs for Programming Capability XHTML and CSS allows the browser to passively display static content How

More information

JavaScript Functions, Objects and Array

JavaScript Functions, Objects and Array JavaScript Functions, Objects and Array Defining a Function A definition starts with the word function. A name follows that must start with a letter or underscore, followed by any number of letters, digits,

More information

Events: another simple example

Events: another simple example Internet t Software Technologies Dynamic HTML part two IMCNE A.A. 2008/09 Gabriele Cecchetti Events: another simple example Every element on a web page has certain events which can trigger JavaScript functions.

More information

5/19/2015. Objectives. JavaScript, Sixth Edition. Introduction to the World Wide Web (cont d.) Introduction to the World Wide Web

5/19/2015. Objectives. JavaScript, Sixth Edition. Introduction to the World Wide Web (cont d.) Introduction to the World Wide Web Objectives JavaScript, Sixth Edition Chapter 1 Introduction to JavaScript When you complete this chapter, you will be able to: Explain the history of the World Wide Web Describe the difference between

More information

Such JavaScript Very Wow

Such JavaScript Very Wow Such JavaScript Very Wow Lecture 9 CGS 3066 Fall 2016 October 20, 2016 JavaScript Numbers JavaScript numbers can be written with, or without decimals. Extra large or extra small numbers can be written

More information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010 Lecture 15 Javascript Announcements Project #1 Graded VG, G= doing well, OK = did the minimum, OK - = some issues, do better on P#2 Homework #6 posted, due 11/5 Get JavaScript by Example Most examples

More information

A.A. 2008/09. Why introduce JavaScript. G. Cecchetti Internet Software Technologies

A.A. 2008/09. Why introduce JavaScript. G. Cecchetti Internet Software Technologies Internet t Software Technologies JavaScript part one IMCNE A.A. 2008/09 Gabriele Cecchetti Why introduce JavaScript To add dynamicity and interactivity to HTML pages 2 What s a script It s a little interpreted

More information

8/19/2018. Web Development & Design Foundations with HTML5. Learning Objectives (1 of 2) Learning Objectives (2 of 2) What is JavaScript?

8/19/2018. Web Development & Design Foundations with HTML5. Learning Objectives (1 of 2) Learning Objectives (2 of 2) What is JavaScript? Web Development & Design Foundations with HTML5 Ninth Edition Chapter 14 A Brief Look at JavaScript and jquery Slides in this presentation contain hyperlinks. JAWS users should be able to get a list of

More information

(Refer Slide Time: 01:40)

(Refer Slide Time: 01:40) Internet Technology Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture No #25 Javascript Part I Today will be talking about a language

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

CERTIFICATE IN WEB PROGRAMMING

CERTIFICATE IN WEB PROGRAMMING COURSE DURATION: 6 MONTHS CONTENTS : CERTIFICATE IN WEB PROGRAMMING 1. PROGRAMMING IN C and C++ Language 2. HTML/CSS and JavaScript 3. PHP and MySQL 4. Project on Development of Web Application 1. PROGRAMMING

More information

E ECMAScript, 21 elements collection, HTML, 30 31, 31. Index 161

E ECMAScript, 21 elements collection, HTML, 30 31, 31. Index 161 A element, 108 accessing objects within HTML, using JavaScript, 27 28, 28 activatediv()/deactivatediv(), 114 115, 115 ActiveXObject, AJAX and, 132, 140 adding information to page dynamically, 30, 30,

More information

Basics of Java Programming

Basics of Java Programming Basics of Java Programming Lecture 2 COP 3252 Summer 2017 May 16, 2017 Components of a Java Program statements - A statement is some action or sequence of actions, given as a command in code. A statement

More information

COMS 469: Interactive Media II

COMS 469: Interactive Media II COMS 469: Interactive Media II Agenda Review Ch. 5: JavaScript An Object-Based Language Ch. 6: Programming the Browser Review Data Types & Variables Data Types Numeric String Boolean Variables Declaring

More information

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications JavaScript Started as a simple script in a Web page that is interpreted and run by the browser Supported by most modern browsers Allows dynamic update of a web page More generally, allows running an arbitrary

More information

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley PHP and MySQL for Dynamic Web Sites Intro Ed Crowley Class Preparation If you haven t already, download the sample scripts from: http://www.larryullman.com/books/phpand-mysql-for-dynamic-web-sitesvisual-quickpro-guide-4thedition/#downloads

More information

Sprite an animation manipulation language Language Reference Manual

Sprite an animation manipulation language Language Reference Manual Sprite an animation manipulation language Language Reference Manual Team Leader Dave Smith Team Members Dan Benamy John Morales Monica Ranadive Table of Contents A. Introduction...3 B. Lexical Conventions...3

More information

JavaScript: Introduction, Types

JavaScript: Introduction, Types JavaScript: Introduction, Types Computer Science and Engineering College of Engineering The Ohio State University Lecture 19 History Developed by Netscape "LiveScript", then renamed "JavaScript" Nothing

More information

EVENT-DRIVEN PROGRAMMING

EVENT-DRIVEN PROGRAMMING LESSON 13 EVENT-DRIVEN PROGRAMMING This lesson shows how to package JavaScript code into self-defined functions. The code in a function is not executed until the function is called upon by name. This is

More information

Skyway Builder Web Control Guide

Skyway Builder Web Control Guide Skyway Builder Web Control Guide 6.3.0.0-07/21/2009 Skyway Software Skyway Builder Web Control Guide: 6.3.0.0-07/21/2009 Skyway Software Published Copyright 2009 Skyway Software Abstract TBD Table of

More information

JAVASCRIPT. sarojpandey.com.np/iroz. JavaScript

JAVASCRIPT. sarojpandey.com.np/iroz. JavaScript JAVASCRIPT 1 Introduction JAVASCRIPT is a compact, object-based scripting language for developing client Internet applications. was designed to add interactivity to HTML pages. is a scripting language

More information

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 2 Professional Program: Data Administration and Management JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) AGENDA

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

PHP by Pearson Education, Inc. All Rights Reserved.

PHP by Pearson Education, Inc. All Rights Reserved. PHP 1992-2012 by Pearson Education, Inc. All Client-side Languages User-agent (web browser) requests a web page JavaScript is executed on PC http request Can affect the Browser and the page itself http

More information

2 rd class Department of Programming. OOP with Java Programming

2 rd class Department of Programming. OOP with Java Programming 1. Structured Programming and Object-Oriented Programming During the 1970s and into the 80s, the primary software engineering methodology was structured programming. The structured programming approach

More information

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 1 Professional Program: Data Administration and Management JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) WHO

More information

Working with JavaScript

Working with JavaScript Working with JavaScript Creating a Programmable Web Page for North Pole Novelties 1 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page 2 Objectives

More information

CHAPTER 6 JAVASCRIPT PART 1

CHAPTER 6 JAVASCRIPT PART 1 CHAPTER 6 JAVASCRIPT PART 1 1 OVERVIEW OF JAVASCRIPT JavaScript is an implementation of the ECMAScript language standard and is typically used to enable programmatic access to computational objects within

More information

Basics of JavaScript. Last Week. Needs for Programming Capability. Browser as Development Platform. Using Client-side JavaScript. Origin of JavaScript

Basics of JavaScript. Last Week. Needs for Programming Capability. Browser as Development Platform. Using Client-side JavaScript. Origin of JavaScript Basics of JavaScript History of the Web XHTML CSS Last Week Nan Niu (nn@cs.toronto.edu) CSC309 -- Fall 2008 2 Needs for Programming Capability XHTML and CSS allows the browser to passively display static

More information

Introduction to JavaScript p. 1 JavaScript Myths p. 2 Versions of JavaScript p. 2 Client-Side JavaScript p. 3 JavaScript in Other Contexts p.

Introduction to JavaScript p. 1 JavaScript Myths p. 2 Versions of JavaScript p. 2 Client-Side JavaScript p. 3 JavaScript in Other Contexts p. Preface p. xiii Introduction to JavaScript p. 1 JavaScript Myths p. 2 Versions of JavaScript p. 2 Client-Side JavaScript p. 3 JavaScript in Other Contexts p. 5 Client-Side JavaScript: Executable Content

More information

New Media Production Lecture 7 Javascript

New Media Production Lecture 7 Javascript New Media Production Lecture 7 Javascript Javascript Javascript and Java have almost nothing in common. Netscape developed a scripting language called LiveScript. When Sun developed Java, and wanted Netscape

More information

The first sample. What is JavaScript?

The first sample. What is JavaScript? Java Script Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari. In this lecture

More information

Web Development & Design Foundations with HTML5

Web Development & Design Foundations with HTML5 1 Web Development & Design Foundations with HTML5 CHAPTER 14 A BRIEF LOOK AT JAVASCRIPT Copyright Terry Felke-Morris 2 Learning Outcomes In this chapter, you will learn how to: Describe common uses of

More information

Name Related Elements Type Default Depr. DTD Comment

Name Related Elements Type Default Depr. DTD Comment Legend: Deprecated, Loose DTD, Frameset DTD Name Related Elements Type Default Depr. DTD Comment abbr TD, TH %Text; accept-charset FORM %Charsets; accept FORM, INPUT %ContentTypes; abbreviation for header

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

Key features. Nothing to do with java It is the Client-side scripting language Designed to add interactivity to HTML pages

Key features. Nothing to do with java It is the Client-side scripting language Designed to add interactivity to HTML pages Javascript Key features Nothing to do with java It is the Client-side scripting language Designed to add interactivity to HTML pages (DHTML): Event-driven programming model AJAX Great example: Google Maps

More information

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003 Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 Java Programs A Java program contains at least one class definition. public class Hello { public static void

More information

A Java program contains at least one class definition.

A Java program contains at least one class definition. Java Programs Identifiers Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 A Java program contains at least one class definition. public class Hello { public

More information

1. Cascading Style Sheet and JavaScript

1. Cascading Style Sheet and JavaScript 1. Cascading Style Sheet and JavaScript Cascading Style Sheet or CSS allows you to specify styles for visual element of the website. Styles specify the appearance of particular page element on the screen.

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

Chapter 2 Working with Data Types and Operators

Chapter 2 Working with Data Types and Operators JavaScript, Fourth Edition 2-1 Chapter 2 Working with Data Types and Operators At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics

More information

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010 Lecture 14 Javascript Announcements Project #2 New website Exam#2 No. Class Date Subject and Handout(s) 17 11/4/10 Examination Review Practice Exam PDF 18 11/9/10 Search, Safety, Security Slides PDF UMass

More information

Controlled Assessment Task. Question 1 - Describe how this HTML code produces the form displayed in the browser.

Controlled Assessment Task. Question 1 - Describe how this HTML code produces the form displayed in the browser. Controlled Assessment Task Question 1 - Describe how this HTML code produces the form displayed in the browser. The form s code is displayed in the tags; this creates the object which is the visible

More information

Place User-Defined Functions in the HEAD Section

Place User-Defined Functions in the HEAD Section JavaScript Functions Notes (Modified from: w3schools.com) A function is a block of code that will be executed when "someone" calls it. In JavaScript, we can define our own functions, called user-defined

More information

What Is JavaScript? A scripting language based on an object-orientated programming philosophy.

What Is JavaScript? A scripting language based on an object-orientated programming philosophy. What Is JavaScript? A scripting language based on an object-orientated programming philosophy. Each object has certain attributes. Some are like adjectives: properties. For example, an object might have

More information

JavaScript I Language Basics

JavaScript I Language Basics JavaScript I Language Basics Chesapeake Node.js User Group (CNUG) https://www.meetup.com/chesapeake-region-nodejs-developers-group START BUILDING: CALLFORCODE.ORG Agenda Introduction to JavaScript Language

More information

JAVASCRIPT. Computer Science & Engineering LOGO

JAVASCRIPT. Computer Science & Engineering LOGO JAVASCRIPT JavaScript and Client-Side Scripting When HTML was first developed, Web pages were static Static Web pages cannot change after the browser renders them HTML and XHTML could only be used to produce

More information

Client vs Server Scripting

Client vs Server Scripting Client vs Server Scripting PHP is a server side scripting method. Why might server side scripting not be a good idea? What is a solution? We could try having the user download scripts that run on their

More information

JavaScript Specialist v2.0 Exam 1D0-735

JavaScript Specialist v2.0 Exam 1D0-735 JavaScript Specialist v2.0 Exam 1D0-735 Domain 1: Essential JavaScript Principles and Practices 1.1: Identify characteristics of JavaScript and common programming practices. 1.1.1: List key JavaScript

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

JavaScript code is inserted between tags, just like normal HTML tags:

JavaScript code is inserted between tags, just like normal HTML tags: Introduction to JavaScript In this lesson we will provide a brief introduction to JavaScript. We won t go into a ton of detail. There are a number of good JavaScript tutorials on the web. What is JavaScript?

More information

Dynamism and Detection

Dynamism and Detection 1 Dynamism and Detection c h a p t e r ch01 Page 1 Wednesday, June 23, 1999 2:52 PM IN THIS CHAPTER Project I: Generating Platform-Specific Content Project II: Printing Copyright Information and Last-Modified

More information

Session 16. JavaScript Part 1. Reading

Session 16. JavaScript Part 1. Reading Session 16 JavaScript Part 1 1 Reading Reading Wikipedia en.wikipedia.org/wiki/javascript / p W3C www.w3.org/tr/rec-html40/interact/scripts.html Web Developers Notes www.webdevelopersnotes.com/tutorials/javascript/

More information

egrapher Language Reference Manual

egrapher Language Reference Manual egrapher Language Reference Manual Long Long: ll3078@columbia.edu Xinli Jia: xj2191@columbia.edu Jiefu Ying: jy2799@columbia.edu Linnan Wang: lw2645@columbia.edu Darren Chen: dsc2155@columbia.edu 1. Introduction

More information

Lesson 1: Writing Your First JavaScript

Lesson 1: Writing Your First JavaScript JavaScript 101 1-1 Lesson 1: Writing Your First JavaScript OBJECTIVES: In this lesson you will be taught how to Use the tag Insert JavaScript code in a Web page Hide your JavaScript

More information

A variable is a name for a location in memory A variable must be declared

A variable is a name for a location in memory A variable must be declared Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;

More information

Introduction to using HTML to design webpages

Introduction to using HTML to design webpages Introduction to using HTML to design webpages #HTML is the script that web pages are written in. It describes the content and structure of a web page so that a browser is able to interpret and render the

More information

Then there are methods ; each method describes an action that can be done to (or with) the object.

Then there are methods ; each method describes an action that can be done to (or with) the object. When the browser loads a page, it stores it in an electronic form that programmers can then access through something known as an interface. The interface is a little like a predefined set of questions

More information

3Lesson 3: Functions, Methods and Events in JavaScript Objectives

3Lesson 3: Functions, Methods and Events in JavaScript Objectives 3Lesson 3: Functions, Methods and Events in JavaScript Objectives By the end of this lesson, you will be able to: 1.3.1: Use methods as. 1.3.2: Define. 1.3.3: Use data type conversion methods. 1.3.4: Call.

More information

Table Basics. The structure of an table

Table Basics. The structure of an table TABLE -FRAMESET Table Basics A table is a grid of rows and columns that intersect to form cells. Two different types of cells exist: Table cell that contains data, is created with the A cell that

More information

TEXTAREA NN 2 IE 3 DOM 1

TEXTAREA NN 2 IE 3 DOM 1 778 TEXTAREA Chapter 9DOM Reference TEXTAREA NN 2 IE 3 DOM 1 The TEXTAREA object reflects the TEXTAREA element and is used as a form control. This object is the primary way of getting a user to enter multiple

More information

Visual C# Instructor s Manual Table of Contents

Visual C# Instructor s Manual Table of Contents Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

More information

Command-driven, event-driven, and web-based software

Command-driven, event-driven, and web-based software David Keil Spring 2009 Framingham State College Command-driven, event-driven, and web-based software Web pages appear to users as graphical, interactive applications. Their graphical and interactive features

More information

Lecture 14. Introduction to JavaScript. Mr. Mubashir Ali Lecturer (Dept. of Computer Science)

Lecture 14. Introduction to JavaScript. Mr. Mubashir Ali Lecturer (Dept. of Computer Science) Lecture 14 Introduction to JavaScript Mr. Mubashir Ali Lecturer (Dept. of dr.mubashirali1@gmail.com 1 Outline What is JavaScript? Embedding JavaScript with HTML JavaScript conventions Variables in JavaScript

More information

CSCE 120: Learning To Code

CSCE 120: Learning To Code CSCE 120: Learning To Code Manipulating Data I Introduction This module is designed to get you started working with data by understanding and using variables and data types in JavaScript. It will also

More information

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java Chapter 3 Syntax, Errors, and Debugging Objectives Construct and use numeric and string literals. Name and use variables and constants. Create arithmetic expressions. Understand the precedence of different

More information

Documents and computation. Introduction to JavaScript. JavaScript vs. Java Applet. Myths. JavaScript. Standard

Documents and computation. Introduction to JavaScript. JavaScript vs. Java Applet. Myths. JavaScript. Standard Introduction to Prof. Ing. Andrea Omicini II Facoltà di Ingegneria, Cesena Alma Mater Studiorum, Università di Bologna andrea.omicini@unibo.it Documents and computation HTML Language for the description

More information