1 A World Wind Tour of JavaScript JavaScript. 2 Objectives l Introduction to JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How.

Slides:



Advertisements
Similar presentations
Chapter 08: Adding Adding Interactivity Interactivity With With Behaviors Behaviors By Bill Bennett Associate Professor MSJC CIS MVC.
Advertisements

Essentials for Design JavaScript Level One Michael Brooks
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
The Web Warrior Guide to Web Design Technologies
Georgia Institute of Technology JavaScript part 2 Barb Ericson Georgia Institute of Technology May 2006.
Multimedia and the World Wide Web HCI 201 Lecture Notes #8B.
Chapter 7 © 2001 by Addison Wesley Longman, Inc. 1 Chapter 7 Sebesta: Programming the World Wide Web.
1 Week 10 A World Wind Tour of JavaScript JavaScript.
1 Outline 13.1Introduction 13.2A Simple Program: Printing a Line of Text in a Web Page 13.3Another JavaScript Program: Adding Integers 13.4Memory Concepts.
Tutorial 10 Programming with JavaScript
Information Technology Center Hany Abdelwahab Computer Specialist.
Web Development & Design Foundations with XHTML Chapter 14 Key Concepts.
JavaScript Client Side scripting. Client-side Scripts Client-side scripts, which run on the user’s workstation can be used to: Validate user inputs entered.
2012 •••••••••••••••••••••••••••••••••• Summer WorkShop Mostafa Badr
Copyright © Terry Felke-Morris WEB DEVELOPMENT & DESIGN FOUNDATIONS WITH HTML5 Chapter 14 Key Concepts 1 Copyright © Terry Felke-Morris.
Introduction to scripting
Web Programming Material From Greenlaw/Hepp, In-line/On-line: Fundamentals of the Internet and the World Wide Web 1 Introduction The JavaScript Programming.
Javascript and the Web Whys and Hows of Javascript.
4.1 JavaScript Introduction
JavaScript: Control Structures September 27, 2005 Slides modified from Internet & World Wide Web: How to Program (3rd) edition. By Deitel, Deitel,
Introduction to JavaScript Dr. John P. Abraham University of Texas – Pan American.
CS346 - Javascript 1, 21 Module 1 Introduction to JavaScript CS346.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
JavaScript Defined DOM (Document Object Model) General Syntax Body vs. Head Variables Math & Logic Selection Functions & Events Loops Animation Getting.
Bridges To Computing General Information: This document was created for use in the "Bridges to Computing" project of Brooklyn College. You are invited.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
Internet Mark-up Languages CO32036 Part Lecture: Elementary JavaScript.
Copyright © Terry Felke-Morris WEB DEVELOPMENT & DESIGN FOUNDATIONS WITH HTML5 Chapter 14 Key Concepts 1 Copyright © Terry Felke-Morris.
DOM and JavaScript Aryo Pinandito.
DHTML: Dynamic HTML Internet Technology1. What is DHTML? A collection of enhancements to HTML ► To create dynamic and interactive websites Combination.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
Javascript. Outline Introduction Fundamental of JavaScript Javascript events management DOM and Dynamic HTML (DHTML)
Chapter 4 JavaScript and Dynamic Web pages. Objectives Static Web pages Dynamic Web pages JavaScript Variables Assignments. JavaScript Functions –(prompt(“”,””)
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 AND DOM Internet Engineering Spring 2012.
Introduction to JavaScript Basharat Mahmood, Department of Computer Science, CIIT, Islamabad, Pakistan. 1.
An Introduction to JavaScript Summarized from Chapter 6 of “Web Programming: Building Internet Applications”, 3 rd Edition.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
JS Basics 1 Lecture JavaScript - Basics. JS Basics 2 What is JavaScript JavaScript is a “simple”, interpreted, programming language with elementary object-
Introduction to JavaScript CS101 Introduction to Computing.
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.
CSC318 – DYNAMIC WEB APPLICATION DEVELOPMENT BY: SITI NURBAYA ISMAIL FACULTY of COMPUTER and MATHEMATICAL SCIENCES.
By Tharith Sriv. To write a web page you use: HHTML (HyperText Markup Language), AASP (Active Server Page), PPHP (HyperText Preprocessor), JJavaScript,
Jaana Holvikivi 1 Introduction to Javascript Jaana Holvikivi Metropolia.
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
Project 8: Reacting to Events Essentials for Design JavaScript Level One Michael Brooks.
© 2007 D. J. ForemanJS-1 A Light Introduction for Non-programmers JavaScript for Beginners.
COS 125 DAY 20. Agenda Assignment 8 not corrected yet Assignment 9 posted  Due April 16 New course time line Discussion on Scripts 
JavaScript Defined DOM (Document Object Model) General Syntax Body vs. Head Variables Math & Logic Selection Functions & Events Loops Animation Getting.
CIS 3.5 Lecture 2.3 "Introduction to JavaScript".
Copyright © Terry Felke-Morris WEB DEVELOPMENT & DESIGN FOUNDATIONS WITH HTML5 7 TH EDITION Chapter 14 Key Concepts 1 Copyright © Terry Felke-Morris.
1 CSC160 Chapter 1: Introduction to JavaScript Chapter 2: Placing JavaScript in an HTML File.
Javascript Basic Concepts Presentation By: Er. Sunny Chanday Lecturer CSE/IT RBIENT.
Web Programming Java Script-Introduction. What is Javascript? JavaScript is a scripting language using for the Web. JavaScript is a programming language.
Web Development & Design Foundations with HTML5
JavaScript is a programming language designed for Web pages.
Web Development & Design Foundations with HTML5 7th Edition
JavaScript for Beginners
14 A Brief Look at JavaScript and jQuery.
WEB PROGRAMMING JavaScript.
JavaScript Basics What is JavaScript?
JavaScript is a scripting language designed for Web pages by Netscape.
JavaScript for Beginners
JavaScript for Beginners
Presentation transcript:

1 A World Wind Tour of JavaScript JavaScript

2 Objectives l Introduction to JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How differs from html and server side programs »Working with JS and HTML tags. »Running onload, when done, on an event »Using JS objects »Objects with properties and methods »Using conditional tests

3 Competencies l At end of unit be able to »Describe 3 times when javascript runs »Describe some of the capabilities of JavaScript »Write a JavaScript with conditional expression »Use a JavaScript program with variables and calculations Competency Alert: You need to know this ! Common Problem Area! People seem to forget this

4 JavaScript: Its Beginnings l JavaScript developed by Netscape & initially called livescript. l After Java came out, Netscape cut a deal with Sun to rename it to JavaScript (12/95). »They are separate, distinct languages. (Though JavaScript is simpler). l Microsoft … »Came out with their own flavor of JavaScript called “Jscript”. »They also added support for VBScript in IE. Differences are minor. l Eventually standardized … »JavaScript has been turned over to the European Computer Manufactures Association, and is now officially called ECMAScript »Both Netscape & IE4.0 and Netscape implement ECMAScript standard.

5 The “goods” on JavaScript l JavaScript can be used to: 1. perform simple client-side computations l For example, add up total costs of shopping cart before it is submitted. 2. facilitate dynamic and interactive Web page creation l For example, do image roll overs, pop up windows on click, expand a menu. 3. Verify HTML forms enhance HTML forms with data collections and form validation 4. manipulate user cookies -

6 The “not so goods” on JavaScript l JavaScript runs completely on Client machine l It does NOT have: 1. Any graphic capabilities l E.g., cannot show a graph of survey results. 2. Access to client (you PC) resources l Cannot print, modifying PC files, or launching client applications. 3. Access to any Web server resources l E.g., cannot send , write to file, write to database.

7 PHP/JavaScript Similarities and Differences l What they have in common. Both languages can: 1.Be embedded in HTML documents 2.Cause dynamic content to be displayed (e.g., the current date) 3.Can be placed in external files and “included” into html files 4.Look more like a programming language than HTML l What they DON’T have in common: 1.The big difference … JavaScript runs 100% on client (i.e., PC). This means: A. JavaScript stuff runs noticeably faster (not dependent on Internet and Web Server) B. PHP has access to Web Server resources (mail, databases, files) 2.Using differences A.Writing JavaScript does NOT require a Web Server (but more concern about browser implementation differences). B.PHP’s syntax is easier to write and understand for beginners.

8 How JavaScript Pages are Run JavaScript does not run here JavaScript is run here by the browser but just before HTML

9 Objectives l Introduction to JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How differs from html and server side programs »Working with JS and HTML tags. »Running onload, when done, on an event »Using JS objects »Objects with properties and methods »Using conditional tests

10 Adding JavaScript to HTML pages JavaScript is added to HTML pages using the tag. usually placed in the HEAD or BODY of the document <!-- Javascript code //--> If link to an external file (use.js suffix) If embed JS within HTML

11 A Simple Example A Beginning Script document.write ("Welcome to the wonderful world of JavaScript"); These statements are run before HTML document interpreted by browser Within the javascript ‘mode’ any output to browswer needs to be within a document.write output command

12 Where do you put it? Can add JavaScript to head or body of html document Functions are usually added to the head section assures that the functions OK (parsed) by the time they are called. Non-functions usually put in body then can call and functions in head

13 Objectives l Introduction to JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How differs from html and server side programs »Working with JS and HTML tags. »Running onload, when done, on an event »Using JS objects »Objects with properties and methods »Using conditional tests

14 When does it run? JavaScript can run 1.as the page loads 2.as soon as the page is finished loading 3.in response to user input (remember the form button?) Competency Alert: You need to know this !

15 Document Object Document Object document.write("This page was last modified on” + document.lastModified); JavaScript that Runs as Page Loads Enter JavaScript. Within the html body (in this case) Normal HTML code document.write like print. Get lastModified browser vrbl.. The + is catenation. Calls function to get current date and output date document.write("This page was last modified on” + document.lastModified); Output this set of text (called a string)Output the result of this ‘command’

16 JavaScript output (onload) is HTML input ….. The output of JavaScript statements is taken as HTML input... A Beginning Script document.write (" JavaScript commands are interpreted first "); document.write (" JS output often generates HTML "); Write these 2 messages

17 Java Example 2 welcome to my page Here is my stuff function waitLittle() { setTimeout( "alertMe()", 5000 ); } function alertMe() { alert('test'); } This is some text over here. JavaScript that Runs when Loading Complete Run ‘allertMe’ code call after 5000 miliseconds Create a pop-up box with test as text After 5000 milisecond pop-up Run ‘waitLittle’ when page is loaded

18 JavaScript that Runs in Response to User Input <!-- function showTime() { document.forms["getDate"].curTime.value = (new Date()).toLocaleString(); } function alertme() { alert("Don't Do that"); } //--> <input type="button" name="getTime" onClick="showTime()" value="Show Current Time" /> When click call showtime Set the value of the form variable curTime to the current time If they click generate an alert

19 Dealing with Browsers that don’t Support JavaScript You may have noticed something a little strange about the examples so far. <!-- Javascript code //--> This makes the script invisible to browsers that don’t support JavaScript by “commenting it out”. In addition, you can provide some page content that only displays when the browser DOESN’T handle JavaScript: Your browser doesn’t support Javascript The only limitation with this is that this will NOT be displayed by NS if the user has JavaScript just disabled.

20 Some Important Aspects of JavaScript Case Sensitive: Variable names, functions you use - (e.g., Date not date ) Space Insensitive - generally ignored, except in strings Statements end in semicolon – Except JS will assume you meant to semicolon at the end of the line if the statement appears to be complete.

21 Objectives l Introduction to JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How differs from html and server side programs »Working with JS and HTML tags. »Running onload, when done, on an event »Using JS objects »Objects with properties and methods »Using conditional tests

22 JavaScript And Objects... l JavaScript is object-oriented –Objects are things your scripts can work with l Have JS objects to work with browsers, windows, and forms –Objects have l properties - are variables or other objects describing the object. »E.g., document.lastmodified l methods - behaviors or built-in functions you use »E.g., accessed my ObjectName.MethodName() Object name Property has time value (like a date) Method name

23 Using JavaScript Objects … l Lots of useful properties available l Here are some properties for window object: »document.lastModified – (read-only property) gives the document last changed date »document.URL - (read-only property) gives the URL of the document source code file. »window.referrer – (read-only property) gives the URL of the calling document. (It is an empty string, if user does not reach the URL by clicking a link. »window.title – (read-only property) gives the value in the... tag.

24 Printing out one of these Can use the plus sign (+) to attach string output with propert output document.write("last modified:” + document.lastModified + " "); Print out this string Attach to the string this property Attach to the entire string this html tag Write the following out.

25 A couple other interesting properties l Here are a few examples of properties »navigator.appName – Set to the browser name »window.location – the current URL your viewing. Setting this property to a URL will redirect the browser –window.location = ‘ »window.status – what is being displayed on the status line of the browser »navigator.appName – Name of browser running »document.title – the information in the tag »document.lastModified – last modified time of document Competency Alert: You need to know this !

26 For example Document Information Properties document.write("Referring link was:” + document.referrer) + " ") document.write("Document URL is:“ + document.URL +" ") document.write("The title is: " + document.title +" ") document. write("last modified:” + document.lastModified + " ") This is my web site. It is my Web Site all by myself.

27 Using an Object Method – date() The Date object to access time and date information. Unlike the Math object, need to create a Date object first: var dateObj = new Date(); You can specify the data/time when you create the object. xmasObj = new Date(“December, 25, 2002”); Can print out current date via: document.write ( new Date().toLocaleString()); Creates new date object Document Object Document Object document.write ( new Date().toLocaleString());

28 The Math Object An example JavaScript object. Math.abs( number ) Math.sin( number ) Math.cos( number ) Math.round( number ) Math.ceil( number ) Math.floor( number ) Math.log( number ) Math.sqrt( number ) Math.random( number ) absolute value sine of an angle (expressed in radians) cosine of an angle (expressed in radians) closest integer value rounds up to next integer value rounds down to next integer value natural log of the number square root of the number returns a floating point number that is >= 0.0 but < 1.0 Other methods include: tangent, arc tangent, arc sine, arc cosine, tangent, power, angle of polar coordinates, maximum, and minimum. Also has constant definitions for values like pi and e (natural log base).

29 Math Object Example Document Object document.write( " sqrt(25)=" + Math.sqrt(25)); document.write( " round(5.632)=" +Math.round(5.632)); document.write( " floor( )=" + Math.floor( ));

30 Objectives l Introduction to JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How differs from html and server side programs »Working with JS and HTML tags. »Running onload, when done, on an event »Using JS objects »Objects with properties and methods »Using conditional tests

31 Using Variables Document Object Using Variables var x = 12; var y = 15; var z = y + x; document.write( "x=" + x + " "); document.write ( 'y='+ y + " " ); document.write ( 'z=' + z + " "); Set variables x, y, z Output a string, then a variable and then tag. Common Problem Area! People seem to forget this Note: remember to separate strings from values with a plus sign Competency Alert: You need to know this ! Each variable should be ‘defined’ with var

32 Some JavaScript Operators OperExampleResult +X = 2 + zAddition - X is assigned z plus 2 + (strg)Z = ‘a’ + ‘b” ;Catenation - Z is assigned ‘ab’ -y= 3 – 1;Subtraction – y is assign 2; *y=2*apple;Multiplication – y is assign 2 times apple /x = y / 2;Division = z is assign y divided by 2. %x = y / 2;Modulus – x is assign remainder of y/2; --x--;Decrement – same as x = x – 1; ++y++;Increment – same as y = y + 1;

33 Some JavaScript Assignments OperExampleResult =X = 1 + 2;X is assign 3; +=y += 2;y= y + 2; -=z -= 1z = z – 1; *=X *= 2;x = x * 2; / =x /= 2;x = x / 2; Document Object Using Variables x = 1; x++; x *= 2; document.write( "x=" + x + " ");

34 Using prompt... l Prompt will ask the user for input and set a variable with result... Document Object Using Variables var rad = prompt('What is radius of wheel (in inches)?'); rad = parseInt(rad); var rotations = prompt('How many rotations did the wheel make?'); rotations = parseInt(rotations); var dist = 3.14 * (rad * rad) * rotations; var dist_feet = dist / 12; document.write( "Caluating distance using a wheel of radius " + rad + " inches"); document.write( " that made " + rotations + " rotations "); document.write( "distance=" + dist + " inches "); document.write( "dist in feet=" + dist_feet + " feet "); Convert character 10 to number 10

35 JavaScript Is also Event Driven l In JavaScript you can specify actions to take on many different events: »onAbort, » onBlur, » onChange, »onClick, »onDblClick, »onDragDrop, »onError, »onFocus, »onKeyDown, »onKeyPress, »onKeyUp, »onload, »onMouseDown, »onMouseOut, »onMouseOver, »onMouseUp, »onMove, »onReset, »onResize, »onSelect, » onSubmit, »onUnload User selects a window item contents can specify some action User puts cursor over a window item (then take some action) User clicks a window item (then can specify some action) User’s cursor left a window item (then can specify some action)

36 Example of a JavaScript Event my form function genAlert() { alert( "Don't do that!" ); } When click form item then do genalert() code.

37 Debugging JavaScript l Both Netscatpe and Firefox have built in JavaScript debug tool From URL line type javascript: Entering javascript: will open a JavaScript debug window Any error messages, while script runs will show errors here Common Problem Area! People seem to forget this

38 Objectives l Introduction to JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How differs from html and server side programs »Working with JS and HTML tags. »Running onload, when done, on an event »Using JS objects »Objects with properties and methods »Using conditional tests

39 Conditionals l JavaScript has many programming constructs if ( x == 6 ) { document.write( “6 X=“ ); document.write( x ); x += 1; } else if ( x > 6 ) { document.write( “LT 6 X=“ ); document.write( x ); x += 1; } else { document.write( “else 6 X=“ ); document.write( x ); } document.write( “x=“ + x ); 1 or more statements to run when x is equal to 6. Test these only when x X is not 6 Run when X > 6. Run X is not 6 or gt 6 HTML> Document Object x=5; if ( x == 6 ) { document.write( "6 X=" ); document.write( x ); x += 1; } else if ( x > 6 ) { document.write( "LT 6 X=" ); document.write( x ); x += 1; } else { document.write( "else 6 X=" ); document.write( x ); } document.wirte( "x=" + x ); Using Variables Competency Alert: You need to know this !

40 Example Grade Calculator Document Object var t1 = prompt( "Enter the score for the first test"); t1=parseInt(t1); if ( t1 100 ) { alert( "Impossible score - I cannot go on!"); exit; } var t2 = prompt( "Enter the score for the second test"); t2=parseInt(t2); if ( t2 100 ) { alert( "Impossible score for t2 - I cannot go on!"); exit; } var t3 = parseInt(prompt( "Enter the score for the third test")); if ( t3 100 ) { alert( "Impossible score - I cannot go on!"); exit; } var aver = ( t1 + t2 + t3 ) / 3; var grade; if ( aver >= 90 ) { grade = 'A'; } else if ( aver >= 80 ) { grade = 'B' } else if ( aver >= 70 ) { grade = 'C' } else { grade = 'D or lower'; } document.write( 'Student average was ' + aver ); document.write( ' This score is a ' + grade ); Notice how convert to number on 1 line

41 JavaScript Conditional Tests OperExampleResult ==if ( x == 1 )Is true if x is equal to 1 !=if ( apple != ‘blue’ )Is true if apple is NOT equal to ‘blue’ >if ( z > y )Is true if z is greater that y >=if ( z >= y )Is true if z is greater than or equal to y <if ( z < 3 )Is true if z is less than 3 <=if ( z <= y )Is true if z is less than or equal to y &&If ( a && b)Is true if both a and b are true ||If ( a || b)Is true if both a || b are true !If ( !x )Is true is x is false

42 Testing Browser Versions Document Object if ( navigator.appName == 'Netscape' ) { document.bgColor='#c6c6c6'; document.write( 'name=' + navigator.appName ); document.write( ' version=' + navigator.appVersion ); document.write( ' appCodename=' + navigator.appCodeName ); document.write( ' userAgenet=' + navigator.userAgent ); } else { document.bgColor='yellow'; document.write( 'Not netscape name=' + navigator.appName ); document.write( ' version=' + navigator.appVersion); document.write( ' appCodename=' + navigator.appCodeName ); document.write( ' userAgenet=' + navigator.userAgent ); } When netscape do this When not netscape do this

43 Summary l Introduction to JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How differs from html and server side programs »Working with JS and HTML tags. »Running onload, when done, on an event »Using JS objects »Objects with properties and methods »Using conditional tests

44 Hands on assignment l Write a simple javascript-based web page that »Redirects the browser to if the user is using netscape or firefox »Redirects the browser to otherwise »Hint: you can redirect a browser by setting the window.location property.

45 One Possible Solution... Document Object if ( navigator.appName == 'Netscape') { window.location = ' } else { window.location = ' }

46 Another Hands on assignment l Create a webpage with JavaScript that: »Displays the current date »Prompts the user for number of rows, cols and ticket cost. »Displays number of seats and total revenue.

47 One Possible Solution Document Object document.write ("Today is " + new Date().toLocaleString() + " "); var rows = parseInt( prompt("How many rows?")); var cols = parseInt( prompt("How many seats per row?")); var ticket = parseInt( prompt("How much per ticket?")); var size = rows * cols; var rev = size * ticket; document.write( "We have " + size + " total seats. " ); document.write( "We have maximum of " + rev + " total revenue. " );