© 2007 D. J. Foreman (& U.H. St.Clair) JS-1 More JavaScript for Beginners Basic Concepts.

Slides:



Advertisements
Similar presentations
Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.
Advertisements

JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
1 CS101 Introduction to Computing Lecture 41 Images & Animation (Web Development Lecture 14)
JavaScript Part 6. Calling JavaScript functions on an event JavaScript doesn’t have a main function like other programming languages but we can imitate.
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
JavaScript (Part 2) CS 183 4/13/2010. JavaScript (Part 2) Will cover: ◦ For.. In ◦ Events ◦ Try.. Catch, Throw ◦ Objects.
Forms cs105. More Interactive web-pages So far what we have seen was to present the information. (Ex: tables. Lists,….). But it is not enough. We want.
Chapter 7 © 2001 by Addison Wesley Longman, Inc. 1 Chapter 7 Sebesta: Programming the World Wide Web.
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.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Information Technology Center Hany Abdelwahab Computer Specialist.
Introduction to JavaScript for Python Programmers
1 CS101 Introduction to Computing Lecture 38 String Manipulations (Web Development Lecture 13)
1 CS101 Introduction to Computing Lecture 35 Mathematical Methods (Web Development Lecture 12)
Javascript and the Web Whys and Hows of Javascript.
CS346 - Javascript 1, 21 Module 1 Introduction to JavaScript CS346.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Scripting Languages.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
Test Automation For Web-Based Applications Portnov Computer School Presenter: Ellie Skobel.
Bridges To Computing General Information: This document was created for use in the "Bridges to Computing" project of Brooklyn College. You are invited.
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
© 2000 – All Rights Reserved - Page 1 Introduction to JavaScript Programming Part Two.
Fluency with Information Technology INFO100 and CSE100 Katherine Deibel Katherine Deibel, Fluency in Information Technology1.
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.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Using Client-Side Scripts to Enhance Web Applications 1.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
Client-Side Scripting JavaScript.  produced by Netscape for use within HTML Web pages.  built into all the major modern browsers. properties  lightweight,
20-753: Fundamentals of Web Programming 1 Lecture 12: Javascript I Fundamentals of Web Programming Lecture 12: Introduction to Javascript.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
Dr. Qusai Abuein1 Internet & WWW How to program Chap.(6) JavaScript:Introduction to Scripting.
1 JavaScript
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.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming basics.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Fluency with Information Technology INFO100 and CSE100 Katherine Deibel Katherine Deibel, Fluency in Information Technology1.
 2000 Deitel & Associates, Inc. All rights reserved. Outline 8.1Introduction 8.2A Simple Program: Printing a Line of Text in a Web Page 8.3Another JavaScript.
JavaScript, Fourth Edition
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.
4. Javascript M. Udin Harun Al Rasyid, S.Kom, Ph.D Lab Jaringan Komputer (C-307) Desain.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
© 2007 D. J. ForemanJS-1 A Light Introduction for Non-programmers JavaScript for Beginners.
Tutorial 11 1 JavaScript Operators and Expressions.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
JavaScript Tutorial. What is JavaScript JavaScript is the programming language of HTML and the Web Programming makes computers do what you want them to.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
 2001 Prentice Hall, Inc. All rights reserved. Outline 1 JavaScript.
Chapter 4 Java Script – Part2. 2 Location object Properties Properties href – whole path will be displayed. ex: window.location.href ( see example 11)
© 2007 D. J. ForemanJS-m1 String, Math & Miscellaneous Methods & Properties.
Chapter 6 JavaScript: Introduction to Scripting
Project 9 Creating Pop-up Windows, Adding Scrolling Messages, and Validating Forms.
JavaScript Syntax and Semantics
4. Javascript Pemrograman Web I Program Studi Teknik Informatika
JavaScript for Beginners
14 A Brief Look at JavaScript and jQuery.
String, Math & Miscellaneous Methods & Properties
T. Jumana Abu Shmais – AOU - Riyadh
CIS 136 Building Mobile Apps
JavaScript for Beginners
String, Math & Miscellaneous Methods & Properties
JavaScript for Beginners
Web Programming and Design
Presentation transcript:

© 2007 D. J. Foreman (& U.H. St.Clair) JS-1 More JavaScript for Beginners Basic Concepts

Variables and Statements ©2007 D. J. Foreman JS-2

Basics ©2007 D. J. Foreman JS-3 Variables: names that are place holders for data X, x, myval The var prefix is needed for objects and arrays and to "privatize" a name inside a function Expressions: perform computations X*Cuberoot(B) Statements: sentences that perform work X=x*y; // x and X are DIFFERENT document.write("aha ");

Variables: Naming Conventions ©2007 D. J. Foreman JS-4 Each 'word' within the name of a variable usually gets capitalized: MySpecialName A constant (name for something that NEVER changes) is usually all caps: Math.PI, Math.LOG10E, MYINTRATE

A strange variable statement ©2007 D. J. Foreman JS-5 Normal syntax: I=I+1; Shortened form: I++; ONLY for adding 1

Adding comments ©2007 D. J. Foreman JS-6 Two kinds of JavaScript comments: // ignore remainder of this line /* ignore what's inside these markers */ VS One kind of HTML comment  !-- ignore what's inside these markers --  Note: tag ends with 2 DASHES before the ">"

One big problem Some browsers may not accept JavaScript, so we have to hide it from them... © 2007 D. J. Foreman JS-7

Hiding JavaScript (from old browsers) ©2007 D. J. Foreman JS-8 <!-- hiding JavaScript These lines might confuse the browser, so the comment tags hide them. The and tags will be ignored (remember the rule about unknown tags?) //-- 

Example 1: writing to the page ©2007 D. J. Foreman JS-9 <!-- hide the Javascript document.write (“I think we’re in trouble,Captain!"); // end of hide -->

Example 2: A Prompt Window ©2007 D. J. Foreman JS-10 A PopUp Dialog <!-- hide from non-js browsers engrname = window.prompt("What's the engineer's name?",""); // pop-up text document.write("Thanks! Beam me up, " + engrname + "!! "); // note use of the "+" sign --> Display this line for every browser

Events ©2007 D. J. Foreman JS-11 Connection between JS and the system users’ actions Some pre-defined events: OnLoad / OnUnload OnClick / OnMouseOver OnFocus / OnBlur // see Prof. Hinton's website OnChange - lost focus and value changed OnSelect - text, textarea, password objects OnSubmit - with the form object prompts Many events are connected to prompts by the browser

Object Hierarchy ©2007 D. J. Foreman JS-12 Browser WindowHistoryLocation Document Links AnchorForms

About objects, their properties and methods Formatting Documents with JS ©2007 D. J. Foreman JS-13

Document Objects some examples ©2007 D. J. Foreman JS-14 document.title - contains the webpage title document.form (the form on the page) document.form.button1 (1st button on the form)

More Document Objects ©2007 D. J. Foreman JS-15 Datemydate_object=new Date(); Mathx=Math.sqrt(xyz); framesframes[0] is the first frame stringsxyz="my data"; I=xyz.length; "mydata" is a string, as is the variable xyz

Some Document Properties ©2007 D. J. Foreman JS-16 alinkColor vlinkColor linkColor bgColor fgColor locationthe URL of this document titletext that appears in title-bar

Document Methods ©2007 D. J. Foreman JS-17 objects have methods that perform work these are some document-focused methods clear() close() open() write()

Examples of work usage ©2007 D. J. Foreman JS-18 Can 'get' and ‘set’ properties of objects document.title="this is my webpage title"; X=document.title;

Program building blocks Functions ©2007 D. J. Foreman JS-19

Functions - program building blocks ©2007 D. J. Foreman JS-20 A function is a reusable code-block that will be executed by an event, or when the function is called. Functions accept input, process it, and deliver output Functions accept input, process it, and deliver output Functions make Web pages dynamic! Functions make Web pages dynamic! Function - user-defined sequence of code Placed between Defined within

Functions – Format (Syntax) function function_name( ) {statements of the function go between the braces, and are ended with a semi-colon; } Example function myfunction() { alert("HELLO"); } ©2007 D. J. Foreman JS-21

Examples of functions – and code Function How to call a function. Function Function with arguments How to pass a variable to a function, and use the variable in the function. Function with arguments Function with arguments 2 How to pass variables to a function, and use these variables in the function. Function with arguments 2 Function that returns a value How to let the function return a value. Function that returns a value A function with arguments, that returns a value How to let the function find the product of two arguments and return the result. A function with arguments, that returns a value function The word function must be written in lowercase letters, otherwise a JavaScript error occurs! ©2007 D. J. Foreman JS-22

Invoking (Calling) a Simple Function – With a Button ©2007 D. J. Foreman JS-23 Calling a Function function myfunction() { alert("HELLO"); } <input type="button" value="Call function"> onclick="myfunction()" Function is being “called”

Functions with and without Arguments Function arguments may be empty or non-empty Remember: functions are always invoked in the body Examples 1.myfunction() {The result (or “work”) of these statements is displayed, every time myfunction is called; } 2.myfunction(txt) {The statements here display some text specified in the body, when myfunction is called; } ©2007 D. J. Foreman JS-24 SEE DEMO EXAMPLES

return The function return statement The return statement is used to specify the value that is returned from the function. So, functions that are going to return a value must use the return statement. ©2007 D. J. Foreman JS-25

Return statement example + a variable The function below should return the product of two numbers (a and b): var = product function prod(a,b) { x=a*b; return x; } When you call the function above, you must pass along two parameters: product=prod(2,3); product The returned value from the prod() function is 6, and it will be stored in the variable called product. ©2007 D. J. Foreman JS-26

Objects within Forms ©2007 D. J. Foreman JS-27 Text fields and areas Password Checkbox Radio Select Button Reset Submit

Limitations ©2007 D. J. Foreman JS-28 Interpreter is ‘hooked-into’ browser Can’t access files (open, read, write)

Control Statements © 2007 D. J. Foreman JS-29 Statements used to control the "flow" of execution within a JS program oif … else conditional statement oFor … loop

Reason for Using Conditional Statements Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements In your code to do this. if...else statement - use this statement if you want to execute some code if the condition is true and another code if the condition is false* Example: If you are taking 12 credit hours or more, pay full-time tuition; else, pay per-credit-hour fee ©2007 D. J. Foreman JS-30 TRUEFALSE Pay $5000Pay $600 * cr hr

Syntax of if … else statement if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true } ©2007 D. J. Foreman JS-31

The if … else Statement ©2007 D. J. Foreman JS-32 Basic Example if (a==b) // note the TWO = signs {true part } else {false part } Condition What happens if Condition is true What happens if Condition is false

if Statement Example ©2007 D. J. Foreman JS-33 Better Example: if (these shoes==shoes on sale) (then) {I will buy these shoes } else {I will not buy these shoes } Condition What happens if Condition is true What happens if Condition is false

If (another example) ©2007 D. J. Foreman JS-34 if (a > b) document.write("See? 'A' was bigger"); else document.write('See? "A" was smaller or equal'); NOTE: single quotes inside the double-quoted strings or vice-versa

Real if … Example ©2007 D. J. Foreman JS-35 //If the time is less than 10, //you will get a "Good morning, CS205 Friend!" greeting. //Otherwise you will get a "Good day, CS205 Attendee!" greeting. var d = new Date(); var time = d.getHours(); if (time < 10) { document.write("Good morning, CS205 Friend!"); } else { document.write("Good day, CS205 Attendee!"); }

The for … Statement ©2007 D. J. Foreman JS-36 Very often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this. In JavaScript there are two different kind of loops: for - loops through a block of code a specified number of times while - loops through a block of code while a specified condition is true The for loop is used when you know in advance how many times the script should run.*

The for Statement ©2007 D. J. Foreman JS-37 Must be lowercase Repeats a set of instructions until a limit is reached (i.e. it’s a loop) Syntax: for (start ; test ; change) Example: for (i=1 ; i<10; i++) {instructions to be repeated go here} In English: “Starting with ‘1’, if a number is smaller than 10, add ‘1’ to that number until you reach 10!”

for Statement Components ©2007 D. J. Foreman JS-38 for (i=1 ; i<10; i++) {instructions to be repeated go here} In English: “Starting with ‘1’, if a number is smaller than 10, add ‘1’ to that number!” Control variable name Initial value of control variable Loop continuation condition Increment of control variable

For … Example – explanation ©2007 D. J. Foreman JS-39 This example defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs. Note: The increment parameter could also be negative, and the <= could be any comparing statement.* generic name

For … Example – code ©2007 D. J. Foreman JS-40 FOR loop example var i=0; for (i=0;i<=10;i++) { document.write("The number is " + i); document.write(" "); }

For … Example - result ©2007 D. J. Foreman JS-41 The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10 Cool!

© 2007 D. J. ForemanJS-m42 String, Math, Date, Array, & Miscellaneous Methods & Properties

© 2007 D. J. Foreman JS-m43 String Object Methods & Properties anchor( ) big( ) blink( ) bold( ) charAt( ) fontcolor( ) fontsize( ) indexOf( ) italics( ) lastIndexOf( ) link( ) small( ) sub( ) sup( ) substr(start, length) substring(start, end) toLowerCase( ) toUpperCase( ) A “string” is a sequence of characters The String object is used to manipulate a stored piece of text.

Window.open Syntax ©2007 D. J. Foreman JS-44 Parameters URL, if any Name for new window Size attributes NOTEs: Quotes around WHOLE attribute string But no quotes around values in attributes

© 2007 D. J. Foreman JS-m45 String function:indexOf Purpose: Purpose: Find a string’s location in another string (the “string” to be found may be a single character) Method: Method: How to use the indexOf() method to return the position of the first occurrence of a specified string value in a string. Look for more information here!here

© 2007 D. J. Foreman JS-m46 Example: indexOf Let x be a string variable (maybe from some kind of input operation) that currently has the value: "DJ Foreman" We want to see if it contains an "F“ and where the “F” is located in the string: x = DJ Foreman n = x.indexOf("F"); n now has the index position of the "F" Remember that we start counting at ZERO So J now has the value of 3 Why is it 3 and not 2? DJ Foreman 0

Code Example: indexOf ©2007 D. J. Foreman JS-47 IndexOf Example var str="DJ Foreman!"; document.write(str.indexOf("F") + " "); document.write(str.indexOf("e") + " "); document.write(str.indexOf("n"));

© 2007 D. J. Foreman JS-m48 Example: lastindexOf, length X="DJ Foreman, Ph. D."; document.write(X.lastIndexOf(" ")+" "); document.write(X.length); Result is:15 17

String Examples with code Return the length of a string How to use the length property to find the length of a string. Return the length of a string Style strings How to style strings. Style strings The indexOf() method How to use the indexOf() method to return the position of the first occurrence of a specified string value in a string. The indexOf() method The match() method How to use the match() method to search for a specified string value within a string and return the string value if found The match() method Replace characters in a string - replace() How to use the replace() method to replace some characters with some other characters in a string. Replace characters in a string - replace() ©2007 D. J. Foreman JS-49

© 2007 D. J. Foreman JS-m50 Example of substring [substr] Purpose: copy a piece of a string, given its start and ending position Let X be a string variable (maybe from some kind of input operation) that currently has the value: "DJ Foreman, Ph. D." If we want the "Foreman": M=X.indexOf(" ")+1;// finds the 1 st char after the blank N=X.indexOf(",");// finds the comma Y=X.substring(M,N);// gets the "Foreman" into Y

What’s an array? The array object is used to store multiple values in a single variable. An ordered arrangement of data elements A vector is a one dimensional array A matrix is a two-dimensional array An array can be as simple as a pricing table held in memory for instant access by an order entry program For more information, look here!here Array object ©2007 D. J. Foreman JS-51

Simple Array – Visual Example ©2007 D. J. Foreman JS-52 Var MyHeight SylviaWinnieChasidaLili 5’2”5’5”5’4”5’7” new Array 1234

Array object and code Create an array Create an array, assign values to it, and write the values to the output. Create an array For...In Statement How to use a for...in statement to loop through the elements of an array. For...In Statement Join two arrays - concat() How to use the concat() method to join two arrays. Join two arrays - concat() Put array elements into a string - join() How to use the join() method to put all the elements of an array into a string. Put array elements into a string - join() Literal array - sort() How to use the sort() method to sort a literal array. Literal array - sort() Numeric array - sort() How to use the sort() method to sort a numeric array. Numeric array - sort() ©2007 D. J. Foreman JS-53

Array Example ©2007 D. J. Foreman JS-54 var mycars = new Array(); mycars[0] = "1989 Merkur Scorpio"; mycars[1] = "1996 Nissan Maxima"; mycars[2] = "2001 Toyota Sienna"; mycars[3] = "1998 BMW 528i"; mycars[4] = "1997 Mercedes Benz E for sale!"; mycars[5] = "2003 Toyota Avalon"; for (i=0;i<mycars.length;i++) { document.write(mycars[i] + " "); }

Array Example Result ©2007 D. J. Foreman JS Merkur Scorpio 1996 Nissan Maxima 2001 Toyota Sienna 1998 BMW 528i 1997 Mercedes Benz E for sale! 2003 Toyota Avalon

© 2007 D. J. Foreman JS-m56 Some Math Object Methods abs( ) ceil( ), floor( ) exp( ) log( ) max( ), min( ) pow( ) random( ) round( ) sqrt( ) sin(radians), asin( ) cos( ), acos( ) tan( ), atan( )

© 2007 D. J. Foreman JS-m57 Some Math Object Properties E LN2, LN10 LN2E, LOG2E PI SQRT2 SQRT1_2 (sqrt of 1/2) ex: Math.PI These are all constants

Date Object The Date object is used to work with dates and times. Find out more here!here ©2007 D. J. Foreman JS-58

Date object Examples Return today's date and time How to use the Date() method to get today's date. Return today's date and time getTime() Use getTime() to calculate the years since getTime() setFullYear() How to use setFullYear() to set a specific date. setFullYear() toUTCString() How to use toUTCString() to convert today's date (according to UTC) to a string. toUTCString() getDay() Use getDay() and an array to write a weekday, and not just a number. getDay() Display a clock How to display a clock on your web page. Display a clock ©2007 D. J. Foreman JS-59

© 2007 D. J. Foreman JS-m60 Some Misc Methods blur( ) focus( ) select( ) eval( ) to re-call the interpreter parseInt( ) or ParseFloat( ) if var x="10"; y="5"; x+y gives "105" parseInt(x)+parseInt(y) gives 15

© 2007 D. J. Foreman JS-m61 Some Useful References "Javascript by Example" (various publishers, if you can find it) "How to Set Up and Maintain a WWW Site", Addison Wesley "Essential Javascript for Web Professionals", Prentice Hall "Essential CSS & DHTML for Web Professionals", Prentice Hall

©2007 D. J. Foreman JS-62