JavaScript Mimi Opkins CECS 470. What We’ll Cover Today u What is JavaScript? u What can it do? u How to program your pages using JavaScript u What do.

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 FaaDoOEngineers.com FaaDoOEngineers.com.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing.
The Web Warrior Guide to Web Design Technologies
Page 1 of 26 Javascript/Jscript Ch 7,8,9,10 Vadim Parizher Computer Science Department California State University, Northridge Spring 2003 Slides from.
JavaScript (Part 2) CS 183 4/13/2010. JavaScript (Part 2) Will cover: ◦ For.. In ◦ Events ◦ Try.. Catch, Throw ◦ Objects.
Java review and more. Class Header  Public class Welcome  Case sensitive  Body of the class must be enclosed by braces.
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.
Information Technology Center Hany Abdelwahab Computer Specialist.
Copyright © Terry Felke-Morris WEB DEVELOPMENT & DESIGN FOUNDATIONS WITH HTML5 Chapter 14 Key Concepts 1 Copyright © Terry Felke-Morris.
Introduction to scripting
CST JavaScript Validating Form Data with JavaScript.
1 Forms A form is the usual way that information is gotten from a browser to a server –HTML has tags to create a collection of objects that implement this.
Scripting Languages.
Chapter 5 Java Script And Forms JavaScript, Third Edition.
IT – som værktøj Bent Thomsen Institut for Datalogi Aalborg Universitet.
JavaScript Part 1.
Copyright © Terry Felke-Morris WEB DEVELOPMENT & DESIGN FOUNDATIONS WITH HTML5 Chapter 14 Key Concepts 1 Copyright © Terry Felke-Morris.
DHTML: Dynamic HTML Internet Technology1. What is DHTML? A collection of enhancements to HTML ► To create dynamic and interactive websites Combination.
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.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing.
Javascript. Outline Introduction Fundamental of JavaScript Javascript events management DOM and Dynamic HTML (DHTML)
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Using Client-Side Scripts to Enhance Web Applications 1.
JavaScript, Fourth Edition Chapter 5 Validating Form Data with JavaScript.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
JavaScript, jQuery, and Mashups Incorporating JavaScript, jQuery, and other Mashups into existing pages.
JS Basics 1 Lecture JavaScript - Basics. JS Basics 2 What is JavaScript JavaScript is a “simple”, interpreted, programming language with elementary object-
1 JavaScript
JavaScript - Basic Concepts Prepared and Presented by Hienvinh Nguyen, Afshin Tiraie.
Scott Marino MSMIS Summer Session Web Site Design and Authoring Session 8 Scott Marino.
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
 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.
1 Chapter 3 – JavaScript Outline Introduction Flowcharts Control Structures if Selection Structure if/else Selection Structure while Repetition Structure.
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.
Making dynamic pages with javascript Lecture 1. Java script java versus javascript Javascript is a scripting language that will allow you to add real.
JavaScript 1 COE 201- Computer Proficiency. Introduction JavaScript scripting language ▫Originally created by Netscape ▫Facilitates disciplined approach.
© 2007 D. J. ForemanJS-1 A Light Introduction for Non-programmers JavaScript for Beginners.
CIS 3.5 Lecture 2.3 "Introduction to JavaScript".
Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing a Line of Text in a Web Page 7.3 Another JavaScript.
Chapter 4 Java Script - Part1. 2 Outlines Introduction to Java Script Variables, Operators and Functions Conditional statements JavaScript Objects Forms.
WEB SYSTEMS & TECHNOLOGY. Java Script  JavaScript created by Netscape  It is also client side programming  It can be use for client side checks.
JavaScript: Control Structures I Outline 1 Introduction 2 Algorithms 3 Pseudocode 4 Control Structures 5 if Selection Structure 6 if/else Selection Structure.
 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)
Chapter 5 Validating Form Data with JavaScript
JavaScript and HTML Simple Event Handling 11-May-18.
CHAPTER 10 JAVA SCRIPT.
In this session, you will learn to:
Web Development & Design Foundations with HTML5
JavaScript is a programming language designed for Web pages.
CIIT-Human Computer Interaction-CSC456-Fall-2015-Mr
Project 9 Creating Pop-up Windows, Adding Scrolling Messages, and Validating Forms.
WEB APPLICATION PROGRAMMING
Introduction to Scripting
JAVASCRIPTS AND HTML DOCUMENTS
JavaScript for Beginners
14 A Brief Look at JavaScript and jQuery.
JavaScript and HTML Simple Event Handling 19-Sep-18.
WEB PROGRAMMING JavaScript.
Chapter 7 - JavaScript: Introduction to Scripting
JavaScript is a scripting language designed for Web pages by Netscape.
JavaScript: Introduction to Scripting
JavaScript and Ajax (JavaScript Events)
JavaScript for Beginners
JavaScript for Beginners
JavaScript and HTML Simple Event Handling 26-Aug-19.
JavaScript and HTML Simple Event Handling 4-Oct-19.
Presentation transcript:

JavaScript Mimi Opkins CECS 470

What We’ll Cover Today u What is JavaScript? u What can it do? u How to program your pages using JavaScript u What do JavaScript programs look like?

What is JavaScript? u Allows you to embed commands in an HTML page u JavaScript commands are loaded by the web browser as part of the page u Commands can also be triggered when the user clicks page items, form fields, etc.

What is JavaScript? (con’t.) u Interpreted Language u Powerful and simple u Limited sets of objects that cannot be extended like JAVA

Why Use a Scripting Language? u HTML is static u Can write small scripts that execute on the user’s browser instead of the server u Increased functionality

What Can JavaScript Do? u Provides a fairly complete set of built-in functions and commands Math Calculations Manipulate Strings Open new windows Verify form input

How to Program Your Page u JavaScript Commands are embedded in HTML documents between SCRIPT tags

What Does JavaScript Look Like? u Resembles many other languages like C++ or JAVA u Case-sensitive u Flexible - a single statement can cover multiple lines or multiple statements/line u Braces group statements into blocks

Hiding Your Scripts u To keep browsers that don’t support JavaScript from interpreting your script as HTML, hide it HTML comments <!-- Hide script from older browsers Alert(“This is JavaScript”); -->

Respecting “JavaScript- Challenged” Browsers u Since not all browsers support JavaScript, use the NOSCRIPT tags as an alternative

Comments u Single Line Comments use // // This is a single line comment u Multiple Line Comments start with /* and end with */ /* This comments extends across multiple lines */

Using Identifiers u Used to identify a variable, method or object u Must start with a letter or underscore and contain 0-9, a-z, A-Z

Built-In Datatypes u Integers u Floating-Point Numbers u Strings u Boolean

Object-Oriented Terms u An object is a collection of data and functions that have been grouped together u A function is a piece of code that performs a specific operation u An object’s functions are methods, its data is called properties

Major Components of the Browser u Window History Location Document Frame v Document Form –Form Elements Status Bar

Browser Object Hierarchy document frame1 document form1 form2 element 2element 3element 1 window

Using Built-In Objects u Individual JavaScript elements are objects u Access objects by specifying their name the active document object is document

Using Properties u To access a property, just use the object name followed by a ‘.’ and the property name address.length u To set a property house.color=“blue” u To create a property customer.name=“Joe Smith”

Using Methods u Works like properties for an object customer.Bill(5.12) u Or without one add(1,3)

Window Object u Top-level object that contains almost everything else in the JavaScript object system u Properties and methods can be used without referring to it explicitly

Window Properties u history - the list of visited URLs u location - the window’s URL, if any u frames - array containing the window’s frames, if any u document - the document contained within the window

Window Methods u alert() - pop up a warning message u confirm() - “OK” or “cancel” u prompt() - retrieve information u open() - open a new window u close() - close a window

Alert Example window.alert( "Welcome to\nJavaScript\n Programming!" ); Click Refresh (or Reload) to run this script again.

Alert Example

Prompt Example window.alert( "Welcome " + window.prompt("Enter your name"," ")); Click Refresh (or Reload) to run this script again.

Prompt Example

Document Object u Contained within each window or frame is a single document u Corresponds to the HTML itself

Document Properties u bgColor - page’s background color u fgColor - page’s foreground color u forms - array of forms u links - array of links u location - complete URL u lastModified - date document was last modified

Document Methods u open() - open the doc for writing u close() - close and format the doc u clear() - clear the contents u write() - write some text into doc u writeln() - write a line of text into doc

Printing a Line Example A First Program in JavaScript document.writeln( " Welcome to JavaScript Programming! " );

Printing a Line Example

Operators u Assignment (=) u Math (+ - * / % ) u Comparison (== != >=) u Logical (&& || !) u String (+)

Assignments u Item=“turtle dove”; u quantity=2; u day=‘Monday’; u for_sale=true; u price=29.97; u value=null;

Adding Numbers Example var firstNumber, // first string entered by user secondNumber, // second string entered by user number1, // first number to add number2, // second number to add sum; // sum of number1 and number2 // read in first number from user as a string firstNumber = window.prompt( "Enter first integer", "0" ); // read in second number from user as a string secondNumber = window.prompt( "Enter second integer", "0" ); // convert numbers from strings to integers number1 = parseInt( firstNumber ); number2 = parseInt( secondNumber ); // add the numbers sum = number1 + number2; // display the results document.writeln( " The sum is " + sum + " " );

Adding Numbers Example

Comparisons and Conditonal Statements u If/else clauses if (age<10) alert(“you are very young”); else alert(“you are very old”); if (name<“M”) alert(“your are in the first line”);

IF Example inname = window.prompt("Enter your name"," "); window.alert( "Welcome " + inname); if (inname == "Mimi") document.writeln("That is a great name"); Click Refresh (or Reload) to run this script again.

IF Example

Loops u While var a; while (a<10) { document.writeln(“item=“+a); a++; }

While Loop Example var total, // sum of grades gradeCounter, // number of grades entered gradeValue, // grade value average, // average of all grades grade; // grade typed by user // Initialization Phase total = 0; // clear total gradeCounter = 1; // prepare to loop

While Loop Example // Processing Phase while ( gradeCounter <= 10 ) { // loop 10 times // prompt for input and read grade from user grade = window.prompt( "Enter integer grade:", "0" ); // convert grade from a String to an integer gradeValue = parseInt( grade ); // add gradeValue to total total = total + gradeValue; // add 1 to gradeCounter gradeCounter = gradeCounter + 1; }

While Loop Example // Termination Phase average = total / 10; // calculate the average // display average of exam grades document.writeln( " Class average is " + average + " " );

While Loop Example

Loops (con’t.) u For for (var i=0;i<10; ++) { document.writlen(“Item=“ + i); } u Break immediately exits loop u Continue back to the top of the loop

For Loop Example Sum the Even Integers from 2 to 100 var sum = 0; for ( var number = 2; number <= 100; number += 2 ) sum += number; document.writeln ( " The sum of the even integers " + "from 2 to 100 is " + sum + " " );

For Loop Example

Variable Scope u If you make a direct variable assignment in a function, the variable becomes global u To define a local variable use the var statement var remainder;

Arrays u Predefined arrays history list, hyperlinks, frames u Uses [ ] for definition u The length property gives the size of the array

Array Example Sum the Elements of an Array var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; var total1 = 0 for ( var i = 0; i < theArray.length; i++ ) total1 += theArray[ i ]; document.writeln( "Total using subscripts: " + total1 );

Array Example

Defining Functions u Use the function statement u Parameters are optional u A return statement is optional. If it is not used the function will return an undefined value

Function with No Parameters function warn() { alert(“I wouldn’t do that if I were you”); } u Invoked by: warn();

Function with Two Parameters and Return function add(a,b) { return(a+b); } u Invoked by: add(a,b);

Programmer-Defined Functions Example A Programmer-Defined square Function document.writeln( " Square the numbers from 1 to 10 " ); // square the numbers from 1 to 10 for ( var x = 1; x <= 10; ++x ) document.writeln( "The square of " + x + " is " + square( x ) + " " ); // The following square function's body is executed only // when the function is explicitly called. // square function definition function square( y ) { return y * y; }

Programmer-Defined Functions Example

User-Defined Objects u Actually just associative arrays u Can assign new data fields and methods freely u Create a function with the same name as the object type (constructor function) u Call the new operator to create new instances of the object

String Built-in Object u substring() - returns a portion of a string u charAt() - returns a single character in a string u indexOf() - returns the position of a character in a string

String Object Example Character Processing Methods var s = "ZEBRA"; var letters = "abcdefghijklmnopqrstuvwxyzabcdefghijklm"; document.writeln( " Character at index 0 in '" + s + "' is ” + s.charAt( 0 ) ); document.writeln( " The index of the characters jkl in '" + letters + "' is " + letters.indexOf('jkl') ); document.writeln( " The substring from positions 3,4,5 and 6 in '" + letters + "' is " + letters.substring(3,7) );

String Object Example

Date Built-in Object u new Date() - returns today’s date and time u new Date(year,month,day) - returns midnight on the given date u new Date(year,month,day,hours, minutes, seconds) - returns given date and time

Date Object Example var current = new Date(); document.writeln( "String representation: " + current.toString()); document.writeln( " getDate: " + current.getDate() + " getDay: " + current.getDay() + " getMonth: " + current.getMonth() + " getFullYear: " + current.getFullYear() + " getTime: " + current.getTime() + " getHours: " + current.getHours() + " getMinutes: " + current.getMinutes() + " getSeconds: " + current.getSeconds()); var anotherDate = new Date( 1999, 2, 18, 1, 5, 0, 0 ); document.writeln( " New Date: " + anotherDate );

Date Object Example

Math Built-In Object u Full suite of scientific and trignometric functions u Don’t create a Math object, just use the methods

Math Object Example document.writeln( "Square Root of 81: " + Math.sqrt(81)); document.writeln( " 5 raised to the 3rd power: " + Math.pow(5,3)); document.writeln( " 33.7 rounded: " + Math.round(33.7) );

Math Object Example

Form Elements u An array corresponding to the elements on a form u Each element has several properties of its own

Form Properties u name - name defined in tag u value - element’s value u checked - is the button checked? u selected - option selected? u text - text label of a list object u options - array of options in a list

Form Methods u submit() - causes browser to immediately submit the form u focus() - moves the text cursor into the field u blur() - moves the cursor out of a field u select() - selects the entire contents of a field

Form Validation Example

Handling Events u onLoad Document Loaded into Browser For documents and framesets u onUnload Document unloaded from Browser For documents and framesets u onSubmit Submit button pressed in a form For forms

Handling Events (con’t.) u onClick User has clicked on an element Radio buttons, pushbutton, checkboxes and links u onFocus Form field has become active Text Fields, password fields, etc.

Handling Events (con’t.) u onBlur Form field has become inactive Text Fields, password fields, etc. u onChange Form field has changed Text Fields, scrolling links and popup menus

Handling Events (con’t.) u onMouseOver Mouse is over the element Hypertext links u onSelect The selected area of a field has changed Text Fields

On Click Example Event Model - ONCLICK <INPUT TYPE = "button" VALUE = "Click Me!" ONCLICK = "alert( 'Hi there good lookin' )";>

On Click Example

OnMouseOver Example Event Model - ONMOUSEOVER <a href=" ONMOUSEOVER = "alert( 'The mouse over works' )";>

OnMouseOver Example

OnFocus OnBlur Example Name: Click here if you like this site

OnFocus OnBlur Example