12-Aug-15 JavaScript Language Fundamentals. 2 About JavaScript JavaScript is not Java, or even related to Java The original name for JavaScript was “LiveScript”

Slides:



Advertisements
Similar presentations
The Web Warrior Guide to Web Design Technologies
Advertisements

JavaScript Language Fundamentals. About JavaScript JavaScript is not Java, or even related to Java –The original name for JavaScript was “LiveScript”
Chapter 7 © 2001 by Addison Wesley Longman, Inc. 1 Chapter 7 Sebesta: Programming the World Wide Web.
12-Jun-15 JavaScript Language Fundamentals I. 2 About JavaScript JavaScript is not Java, or even related to Java The original name for JavaScript was.
Javascript Client-side scripting. Up to now  We've seen a little about how to control  content with HTML  presentation with CSS  Javascript is a language.
18-Jun-15 JavaScript Language Fundamentals. 2 About JavaScript JavaScript is not Java, or even related to Java The original name for JavaScript was “LiveScript”
20-Jun-15 JavaScript and HTML Simple Event Handling.
24-Jun-15 JavaScript Language Fundamentals. 2 About JavaScript JavaScript is not Java, or even related to Java The original name for JavaScript was “LiveScript”
Information Technology Center Hany Abdelwahab Computer Specialist.
25-Jun-15 JavaScript Language Fundamentals II. 2 Exception handling, I Exception handling in JavaScript is almost the same as in Java throw expression.
JavaScript, Third Edition
2012 •••••••••••••••••••••••••••••••••• Summer WorkShop Mostafa Badr
Introduction To JavaScript What JavaScript Is: a general purpose scripting language that allows a static page to interact with users and respond to events.
Java. Why Java? It’s the current “hot” language It’s almost entirely object-oriented It has a vast library of predefined objects It’s platform independent.
Event Handlers CS101 Introduction to Computing. Learning Goals Learn about event handlers Determine how events are useful in JavaScript Discover where.
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
JavaScript II ECT 270 Robin Burke. Outline JavaScript review Processing Syntax Events and event handling Form validation.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
JavaScript Part 1.
Chapter 3 : Processing on the Front End JavaScript Technically its name is ECMA-262, which refers to the international standard which defines it. The standard.
1 JavaScript. 2 What’s wrong with JavaScript? A very powerful language, yet –Often hated –Browser inconsistencies –Misunderstood –Developers find it painful.
CSS Class 7 Add JavaScript to your page Add event handlers Validate a form Open a new window Hide and show elements Swap images Debug JavaScript.
Javascript. Outline Introduction Fundamental of JavaScript Javascript events management DOM and Dynamic HTML (DHTML)
Lesson13. JavaScript JavaScript is an interpreted language, designed to function within a web browser. It can also be used on the server.
Introduction to JavaScript Gordon Tian
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Using Client-Side Scripts to Enhance Web Applications 1.
20-753: Fundamentals of Web Programming 1 Lecture 12: Javascript I Fundamentals of Web Programming Lecture 12: Introduction to Javascript.
27-Oct-15 JavaScript Language Fundamentals. 2 About JavaScript JavaScript is not Java, or even related to Java The original name for JavaScript was “LiveScript”
Intro to JavaScript Scripting language –ECMAScript compliant –Client side vs. server side Syntactic rules –White space –Statement end: ; optional –Comments:
JavaScript, jQuery, and Mashups Incorporating JavaScript, jQuery, and other Mashups into existing pages.
4.4 JavaScript (JS) Deitel Ch. 7, 8, 9, JavaScript & Java: Similarities JS (JavaScript) is case-sensitive Operators –arithmetic: unary +, unary.
Lecture 10 JavaScript: DOM and Dynamic HTML Boriana Koleva Room: C54
15-Nov-15 JavaScript Language Fundamentals. 2 About JavaScript JavaScript is not Java, or even related to Java The original name for JavaScript was “LiveScript”
JavaScript - Basic Concepts Prepared and Presented by Hienvinh Nguyen, Afshin Tiraie.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Scott Marino MSMIS Summer Session Web Site Design and Authoring Session 8 Scott Marino.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming basics.
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
Tharith Sriv.  JavaScript is a simple programming language that can be written directly into HTML documents to allow for increased interactivity with.
05 – Java Script (1) Informatics Department Parahyangan Catholic University.
JavaScript, Fourth Edition
What is JavaScript? JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language (a scripting language is a lightweight.
Introduction To JavaScript. Putting it Together (page 11) All javascript must go in-between the script tags. All javascript must go in-between the script.
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
Making dynamic pages with javascript Lecture 1. Java script java versus javascript Javascript is a scripting language that will allow you to add real.
Creating Web Documents: JavaScript Ftp / file management: review Introduction to JavaScript Sources Homework: start review for midterm, work on Project.
JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.
JavaScript. JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers,
Overview JavaScript. Overview 2 About Basics Objects DOM.
JavaScript II ECT 270 Robin Burke. Outline Functions Events and event handling Form validation.
JavaScript Event Handlers. Introduction An event handler executes a segment of a code based on certain events occurring within the application, such as.
About JavaScript JavaScript is not Java, or even related to Java –The original name for JavaScript was “LiveScript” –The name was changed when Java became.
Introduction to Javascript. What is javascript?  The most popular web scripting language in the world  Used to produce rich thin client web applications.
Javascript Basic Concepts Presentation By: Er. Sunny Chanday Lecturer CSE/IT RBIENT.
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
6-Jun-16 JavaScript Language Fundamentals. 2 About JavaScript JavaScript is not Java, or even related to Java The original name for JavaScript was “LiveScript”
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
JavaScript and HTML Simple Event Handling 11-May-18.
JavaScript is a programming language designed for Web pages.
JavaScript and HTML Simple Event Handling 19-Sep-18.
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
What is JavaScript? JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language (a scripting language is a lightweight.
JavaScript CS 4640 Programming Languages for Web Applications
JavaScript Basics What is JavaScript?
JavaScript is a scripting language designed for Web pages by Netscape.
JavaScript and HTML Simple Event Handling 26-Aug-19.
JavaScript CS 4640 Programming Languages for Web Applications
JavaScript and HTML Simple Event Handling 4-Oct-19.
Presentation transcript:

12-Aug-15 JavaScript Language Fundamentals

2 About JavaScript JavaScript is not Java, or even related to Java The original name for JavaScript was “LiveScript” The name was changed when Java became popular Now that Microsoft no longer likes Java, its name for their JavaScript dialect is “Active Script” Statements in JavaScript resemble statements in Java, because both languages borrowed heavily from the C language JavaScript should be fairly easy for Java programmers to learn However, JavaScript is a complete, full-featured, complex language JavaScript is reasonably platform-independent

3 Using JavaScript in a browser JavaScript code is included within tags: document.write(" Hello World! ") ; Notes: The type attribute is to allow you to use other scripting languages (but JavaScript is the default) This simple code does the same thing as just putting Hello World! in the same place in the HTML document The semicolon at the end of the JavaScript statement is optional You need semicolons if you put two or more statements on the same line It’s probably a good idea to keep using semicolons

4 JavaScript isn’t always available Some old browsers do not recognize script tags These browsers will ignore the script tags but will display the included JavaScript To get old browsers to ignore the whole thing, use: The <!-- introduces an HTML comment To get JavaScript to ignore the HTML close comment, -->, the // starts a JavaScript comment, which extends to the end of the line Some users turn off JavaScript Use the message to display a message in place of whatever the JavaScript would put there

5 Where to put JavaScript JavaScript can be put in the or in the of an HTML document JavaScript functions should be defined in the This ensures that the function is loaded before it is needed JavaScript in the will be executed as the page loads JavaScript can be put in a separate.js file Put this HTML wherever you would put the actual JavaScript code An external.js file lets you use the same JavaScript on multiple HTML pages The external.js file cannot itself contain a tag JavaScript can be put in an HTML form object, such as a button This JavaScript will be executed when the form object is used

6 Primitive data types JavaScript has three “primitive” types: number, string, and boolean Everything else is an object Numbers are always stored as floating-point values Hexadecimal numbers begin with 0x Some platforms treat 0123 as octal, others treat it as decimal Since you can’t be sure, avoid octal altogether! Strings may be enclosed in single quotes or double quotes Strings can contain \n (newline), \" (double quote), etc. Booleans are either true or false 0, "0", empty strings, undefined, null, and NaN are false, other values are true

7 Variables Variables are declared with a var statement: var pi = , x, y, name = "Dr. Dave" ; Variables names must begin with a letter or underscore Variable names are case-sensitive Variables are untyped (they can hold values of any type) The word var is optional (but it’s good style to use it) Variables declared within a function are local to that function (accessible only within that function) local variables must be declared using var Variables declared outside a function are global (accessible from anywhere on the page)

8 Operators, I Most JavaScript syntax is borrowed from C Arithmetic operators (all numbers are floating-point): + - * / % Comparison operators: = > Logical operators: && || ! (&& and || are short-circuit operators) Bitwise operators: & | ^ ~ > >>> Assignment operators: += -= *= /= %= >= >>>= &= ^= |=

9 Operators, II 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 new typeof void delete

10 Comments Comments are as in C++ or Java: Between // and the end of the line Between /* and */ Java’s javadoc comments, /**... */, are treated just the same as /*... */ comments; they have no special meaning in JavaScript

11 Statements, I Most JavaScript statements are also borrowed from C Assignment: greeting = "Hello, " + name; Compound statement: { statement ;...; statement } If statements: if ( condition ) statement ; if ( condition) statement ; else statement ; Familiar loop statements: while ( condition ) statement ; do statement while ( condition ); for ( initialization ; condition ; increment ) statement ;

12 Statements, II The switch statement: switch ( expression) { case label : statement ; break; case label : statement ; break;... default : statement ; } Other familiar statements: break; continue; The empty statement, as in ;; or { }

13 JavaScript is not Java By now you should have realized that you already know a great deal of JavaScript JavaScript has some features that resemble features in Java: JavaScript has Objects and primitive data types JavaScript has qualified names; for example, document.write("Hello World"); JavaScript has Events and event handlers Exception handling in JavaScript is almost the same as in Java JavaScript has some features unlike anything in Java: Variable names are untyped: the type of a variable depends on the value it is currently holding Objects and arrays are defined in quite a different way JavaScript has with statements and a new kind of for statement

14 Exception handling, I Exception handling in JavaScript is almost the same as in Java throw expression creates and throws an exception The expression is the value of the exception, and can be of any type (often, it's a literal String) try { statements to try } catch ( e ) { // Notice: no type declaration for e exception handling statements } finally { // optional, as usual code that is always executed } With this form, there is only one catch clause

15 Exception handling, II try { statements to try } catch ( e if test1 ) { exception handling for the case that test1 is true } catch ( e if test2 ) { exception handling for when test1 is false and test2 is true } catch ( e ) { exception handling for when both test1and test2 are false } finally { // optional, as usual code that is always executed } Typically, the test would be something like e == "InvalidNameException"

16 Object literals 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", 7: "Mazda", getCar: CarTypes("Honda"), special: Sales} The fields are myCar, getCar, 7 (this is a legal field name), 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);

17 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 this.number = n; // keyword "this" is required, not optional this.teacher = t; } var course = new Course("CIT597", "Dr. Dave");

18 Array literals You don’t declare the types of variables in JavaScript 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

19 Four ways to create 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");

20 The length of an array 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 As in C and Java, there are no two-dimensional arrays; but you can have an array of arrays: myArray[5][3]

21 Arrays and objects 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"]

22 Array functions 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

23 The for…in statement You can loop through all the properties of an object with for ( variable in object ) statement ; Example: 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, … Notice that course["teacher"] is equivalent to course.teacher You must use brackets if the property name is in a variable

24 Functions Functions should be defined in the of an HTML page, to ensure that they are loaded first The syntax for defining a function is: function name ( arg1, …, argN ) { statements } The function may contain return value ; statements Any variables declared within the function are local to it The syntax for calling a function is just name ( arg1, …, argN ) Simple parameters are passed by value, objects are passed by reference

25 Regular expressions 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

26 Warnings 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

27 Example JavaScript 1 document.write(" This is it. "); document.write(Date()); This is the rest of the page.

28 Modified example JavaScript 1 <!-- var rawDate = Date(); var mon = rawDate.substr(4,3); document.write("The date is"); document.write(rawDate, " ") document.write("The month is ", mon); //--> This is the rest of the page.

29 Using built-in functions, variables JavaScript 1 <!-- var rawDate = Date(); var mon = rawDate.substr(4,3); document.write("The month is "); document.write(mon); //--> This is the rest of the page. Variable set to what Date() returns. Extract the month.

30 Form example function verify(f) { if (f.lname.value == null || f.address.value == null) { alert("Form needs a last name and an address"); return false; } if (f.lname.value == "" || f.address.value == "") { alert("Form needs a last name and an address"); return false; } return true; }

31 Address Information <form method=post enctype="text/plain" onSubmit="return verify(this);"> First Name: Last Name: Street Address: Town/City: State: Utah Idaho New York New Jersey Connecticut Pennsylvania Status: Returning client New client Thank you Javascript Event

32 Javscript Events Events are actions that can be detected by Javascript Every element on a web page has certain events which can trigger Javascript functions Often placed within the HTML tag The set of all events which may occur and the page elements on which they can occur is part of the Document Object Model(DOM) not Javascript Browsers don’t necessarily share the same set of events

33 Common Javascript Events EventOccurs when...Event Handler click User clicks on form element or link onClick change User changes value of text, textarea, or select element onChange focus User gives form element input focus onFocus blur User removes input focus from form element onBlur mouseover User moves mouse pointer over a link or anchor onMouseOver mouseout User moves mouse pointer off of link or anchor onMouseOut select User selects form element's input field onSelect submit User submits a form onSubmit resize User resizes the browser window onResize load User loads the page in the Navigator onLoad unload User exits the page onUnload

34 The Document Object Model When a document is loaded in the web browser, a number of objects are created. Most commonly used are window and document Window open(), close(), alert(), confirm(), prompt() Document Contains arrays which store all the components of your page You can access and call methods on the components using the arrays An object may also be accessed by its name document.myform.address.value = “123 Main” document.myform.reset() Can also search for element by name or id document.getElementById(“myelementid”) document.getElementsByName(“myelementname”)