Client-Side Scripting with JavaScript Barry Sosinsky Valda Hilley

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

Java Script Session1 INTRODUCTION.
The Web Warrior Guide to Web Design Technologies
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Introduction to Web Site Development Steven Emory Department of Computer Science California State University, Los Angeles Lecture 8: JavaScript I.
Information Technology Center Hany Abdelwahab Computer Specialist.
CIS101 Introduction to Computing Week 11. Agenda Your questions Copy and Paste Assignment Practice Test JavaScript: Functions and Selection Lesson 06,
Computer Science 103 Chapter 4 Advanced JavaScript.
Web Development & Design Foundations with XHTML Chapter 14 Key Concepts.
2012 •••••••••••••••••••••••••••••••••• Summer WorkShop Mostafa Badr
Introduction to scripting
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
SYST Web Technologies SYST Web Technologies Lesson 6 – Intro to JavaScript.
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
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,
What is Java Script? An extension to HTML. An extension to HTML. Allows authors to incorporate some functionality in their web pages. (without using CGI.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
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,
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Dr. Qusai Abuein1 Internet & WWW How to program Chap.(6) JavaScript:Introduction to Scripting.
JavaScript - Basic Concepts Prepared and Presented by Hienvinh Nguyen, Afshin Tiraie.
Overview of Form and Javascript fundamentals. Brief matching exercise 1. This is the software that allows a user to access and view HTML documents 2.
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.
XP Tutorial 8 Adding Interactivity with ActionScript.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
JavaScript, Fourth Edition
COMP403 Web Design JAVA SCRİPTS Tolgay KARANFİLLER.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
ECA 225 Applied Interactive Programming ECA 225 Applied Online Programming control structures, events, objects.
Pertemuan 5 IT133 Pengembangan Web JavaScript. What is JavaScript? JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
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.
XHTML Forms.
>> Introduction to JavaScript
VB Script V B S.
CHAPTER 10 JAVA SCRIPT.
Chapter 6 JavaScript: Introduction to Scripting
Tutorial 10 Programming with JavaScript
Web Development & Design Foundations with HTML5
JavaScript is a programming language designed for Web pages.
In this session, you will learn about:
Project 9 Creating Pop-up Windows, Adding Scrolling Messages, and Validating Forms.
Web Development & Design Foundations with HTML5 7th Edition
My First Web Page document.write("" + Date() + ""); To insert.
JavaScript Syntax and Semantics
JavaScript for Beginners
JavaScript.
CHAPTER 4 CLIENT SIDE SCRIPTING PART 2 OF 3
WEB PROGRAMMING JavaScript.
Introduction to JavaScript for Python Programmers
My First Web Page document.write("" + Date() + ""); To insert.
T. Jumana Abu Shmais – AOU - Riyadh
JavaScript CS 4640 Programming Languages for Web Applications
Tutorial 10: Programming with javascript
JavaScript Basics What is JavaScript?
JavaScript is a scripting language designed for Web pages by Netscape.
Introduction to Programming and JavaScript
JavaScript: Introduction to Scripting
PHP an introduction.
CIS 136 Building Mobile Apps
JavaScript for Beginners
JavaScript for Beginners
Web Programming and Design
CS105 Introduction to Computer Concepts JavaScript
Presentation transcript:

Client-Side Scripting with JavaScript Barry Sosinsky Valda Hilley Chapter 7 Client-Side Scripting with JavaScript Barry Sosinsky Valda Hilley Programming the Web

Learning Objectives Adding JavaScript to HTML Pages Working with JavaScript Variables Working with objects Controlling JavaScript programs Forms with JavaScript

Getting to Know JavaScript JavaScript is Netscape’s cross-platform, object-oriented scripting language. It is supported by all major browsers like Netscape and Internet Explorer. JavaScript is not a scaled-down version of Java. It is not Java, nor is it related to Java.

Core JavaScript Client-side and server-side JavaScript have the following elements in common: Keywords Statement syntax and grammar Rules for expressions, variables, and literals Underlying object model (although client-side and server-side JavaScript have different sets of predefined objects) Predefined objects and functions, such as such as Array, Date, and Math

A First Look at JavaScript JavaScript code appears embedded within an HTML document <!-- Welcome.htm --> <html><head></head> <body> <script language="javascript"> document.write("Welcome to JavaScript!") </script> </body> </html> Your first JavaScript script

A First Look at JavaScript (2) One of the most common uses for JavaScript is to display text. The Document object makes this possible in JavaScript. <!-- Welcome.htm --> <html><head></head> <body> <script language="javascript"> document.write("Welcome to JavaScript!") </script> </body> </html>

The <SCRIPT> Tag <!--alert.htm --> <html><head> <title>Client Side Scripting with JavaScript</title> <script language="JavaScript"> alert("Welcome to Web Programming!") </script> </head></html> The LANGUAGE attribute in the opening <SCRIPT> tag specifies that JavaScript is the scripting language used here Everything that appears between the opening and closing <SCRIPT> tags is known as the body of the script

Where the Put the JavaScript HTML documents are divided into two sections: a head and body <HTML> <HEAD> <TITLE>Untitled</TITLE> </HEAD> <BODY> . </BODY> </HTML> Place your JavaScript code in the <HEAD> when you want a script to execute (run) when a user triggers it, (such as by clicking) Place your JavaScript code in the <BODY> when you want the script to execute (run) immediately, when the HTML page loads

Putting JavaScript in the <HEAD> Section Usually, all functions are placed in the <HEAD> section, to ensure the script is loaded before the function is called. <html> <head> <script language="javascript"> some statements go here </script> </head> .

Putting JavaScript in the <BODY> Section A script that’s placed in the <BODY> section executes immediately and is known as an Immediate script. <html> <head> </head> <body> <script language ="JavaScript"> some statements go here </script> </body> . You can place an unlimited number of scripts in your HTML document, in both the <HEAD> and <BODY> sections.

Working with Variables A variable is a reserved space in computer memory that JavaScript can use to store data while a script runs. You can use variables to: Store input from the user gathered via your Web page Save data returned from functions Hold results from calculations

Working with Variables (2) JavaScript has four basic data types for variables: Variable Numeric String Boolean null Sample value 10,072 "122 Green Street" true value undefined

Declaring a Variable Before you can use a variable to store some data you must define or declare it. You can create a variable with the var statement: var strname = some value You can also create a variable without the var statement: strname = some value Variables are more useful and your code more readable if you use descriptive names that have some association with its contents or purpose.

Storing Values in Variables You should assign a value to a variable when you create it. This is referred to as initializing a variable. The format is as follows: var strname = "Color" Or: strname = "Color" The equal sign (=) is an assignment operator, not an arithmetic operator. The name of the variable is entered on the left side of the assignment operator and the value of the variable is entered on the right side of the operator.

Initializing Variables You should assign a value to a variable when you create it. This is referred to as initializing a variable. The format is as follows: The variable counter is a script-level variable. It can be utilized throughout the script. <html><body> <script language ="JavaScript"> var counter = 1 Sub cmdButton_onClick() var temp = 5 End Sub </script> </body> </html> The variable temp is a procedural variable. It exists only within the cmdButton_onClick function.

Working with Arrays An array in JavaScript is a set of values grouped together under a single variable name: colors = new Array("Red", "Yellow", "Blue") The elements of an array are indexed according to their order, starting with 0. The second element in the above array ( "Yellow") could be referred to as colors[1]. You can also specify the number of elements in a new array. This code creates an array of 5 elements: dish = new Array(5)

Sample Array: An Example <!-- Array1.htm --> <html><body> <script language="javascript"> var famname = new Array(6) famname[0] = "Valda" famname[1] = "Glenn" famname[2] = "Sidney" famname[3] = "Myrna" famname[4] = "Jett" famname[5] = "Moonie" for (i=0; i<6; i++) { document.write(famname[i] + "<br>") } </script> </body></html>

Sample Array: An Example (2) This is another way of writing the script to produce the same output: <!-- Array2.htm --> <html> <body> <script language="javascript"> var famname = new Array("Valda","Glenn","Sidney","Myrna","Jett","Moonie") for (i=0; i<famname.length; i++) { document.write(famname[i] + "<br>") } </script> </body></html>

JavaScript Functions JavaScript supports several functions that can be executed by an event or called from any script. A function runs code and can also return a result to the script that called it. You define functions at the beginning of a file (in the head section), and call them later in the document. To create a function you define its name, any values (arguments), and statements: function myfunction(argument1,argument2,etc) { some statements } A function with no arguments must include the parentheses: function myfunction() { some statements }

Arguments An argument is a variable used in the function. The variable values are values passed on by the function call. By placing functions in the head section of the document, you make sure that all the code in the function has been loaded before the function is called. Some functions return a value to the calling expression function result(a,b) { c=a+b return c }

JavaScript Functions This code defines a function and creates an input button that, when pressed, calls the function. The function in turn then displays an alert box with the message “Welcome.” <!-- Function1.htm --> <html><head> <script language="javascript"> function firstfunction() { alert("Welcome") } </script></head> <body> <form> <input type="button" onclick="firstfunction()" value="Call function"> </form> </body></html>

Anatomy of a Simple Function <!-- Function1.htm --> <html><head> <script language="javascript"> function firstfunction() { alert("Welcome") } </script></head> <body> <form> <input type="button" onclick="firstfunction()" value="Call function"> </form> </body></html> When the input button is pressed, the function displays an alert box with the message “Welcome.”

The return Statement Functions that return a result must use the "return" statement. <!-- Total.htm --> <html><head> <script language="javascript"> function total(a,b) { return a + b } </script></head> <body> document.write(total(2,3)) </script> </body></html>

Controlling Your JavaScript Routines JavaScript lets you control the order in which your scripts process data through the use of conditional and looping statements. By using conditional statements you can develop scripts that make decisions by evaluating data and criteria to determine what tasks to perform. Looping statements allow you to repetitively execute a line or lines of a script until a certain condition or criteria are met.

Conditional Statements JavaScript provides three forms of conditional statements: if if…else Switch The programming required to create this kind of logic is implemented via conditional controls known as branching.

If and If…Else Statements Use the if statement when you want to execute some code if a condition is true: if (condition) { code to be executed if condition is true } To execute certain code if a condition is true and some other code if a condition is false, use the if....else statement. if (condition) { code to be executed if condition is true } else code to be executed if condition is false

Switch Statement The switch statement tests an expression against a number of case options and executes the statements associated with the first one to match. switch (color) { case label1: code to be executed if color = label1 break case label2: code to be executed if color = label2 default: code to be executed if color is different from both label1 and label2 }

Switch Statement: Another Code Example Here, the user receives different messages depending upon what day of the week it is: <!-- Switch1.htm --> <script language="javascript"> //You will receive a different greeting based //on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc. var d=new Date() theDay=d.getDay() switch (theDay) { case 5: document.write("Finally Friday") break case 6: document.write("Super Saturday") case 0: document.write("Sleepy Sunday") default: document.write("I'm looking forward to this weekend!") } </script>

Conditional Operator JavaScript also contains a conditional operator (==) that assigns a value to a variable based on some condition: Variable name=(condition)?value1:value2 For example: greeting=(visitor=="PRES")?"Dear President ":"Dear " If the variable visitor is equal to PRES, then put the string "Dear President " in the variable named greeting. If the variable visitor is not equal to PRES, then put the string "Dear " into the variable named greeting.

Using Looping Statements In JavaScript, looping statements force a program do something again and again a specified number of times, until some condition is met or as long as some condition exists. JavaScript provides three forms of looping statements: while do…while for…run

Using Looping Statements (2) A for statement is best used when you want to perform a loop a specific number of times. The do…while and for…run statements are best used to perform a loop an undetermined number of times or while a certain condition exists.

While Statements The while statement will execute a block of code while a condition is true: while (condition) { code to be executed } This while statement simply counts 1 thru 10 by incrementing a counter by 1 each time for as long as the counter is less than 11: var i = 0 while(i<11) { document.write(i + "<br/>") i++ }

Do…While Statements The do...while statement executes one or more statements at least once, checking that a certain condition is met each time before repeating. If that condition is not met, then control moves to the statement immediately after the loop. The following example counts up in twos for as long as the number is less than 20: var i = 0 do { document.write(i + ".<br/>") i+=2 } while(i<20)

For Statements The for statement creates a loop consisting of three optional expressions. The first expression is used to initialize a counter variable, the second (optional) provides a condition that is evaluated on each pass through the loop, and the third updates or increments the counter variable. This example simply counts up from zero for as long as the counter is less than 10: for(i=0; i<10; i++) document.write(i + ".<br/>");

JavaScript Syntax Here are the essential characters and punctuation used in JavaScript scripts: Characters // /* */ { and } ; Definition Indicates the start of a comment Begins a comment that spans more than one line Indicates the end of a comment that covers more than one line. Used to indicate a block of code Defines the end of a statement (optional, but still a good idea)

All About Forms Forms let you prompt a user for input using elements such as radio buttons, checkboxes and selection lists. <!-- Dropdown.htm --> <html><head> <script type="text/javascript"> function put() { var option= document.forms[0].dropdown.options[document.forms[0]. dropdown.selectedIndex].text var txt=option document.forms[0].favorite.value=txt } </script></head><body><form><p> Select your favorite browser: <select name="dropdown" onchange="put()"> <option>Internet Explorer <option>Netscape Navigator </select> </p><p>Your favorite browser is: <input type="text" name="favorite" value="Internet Explorer"> </p></form></body></html>

Creating Mouseovers With event handlers like onMouseMove, onMouseOut, onMouseOver and onClick, you can load a new image for the hyperlink or display text in the status bar of the browser in place of the hyperlink’s URL: <!-- Mouseover.htm --> <html><head> <script language="JavaScript"> function showImage(imgName, imgSrc) { document.all[imgName].src=imgSrc } </script></head> <body> <h3>Here is a Mouseover example</h3> <a HREF="http://www.mcgraw-hill.com/markets/mcgrawhill_education.html" onmouseover="showImage('imgSomeImage','McGrawHillEducation.gif')" onmouseout="showImage('imgSomeImage','McGrawHillCommunity.jpg')" </a> <img name="imgSomeImage" src='McGrawHillHome.gif' width="200" height="100"/> </body></html>

Opening a New Window The window.open method lets you pop open a second window. This method takes four optional parameters: Location Name It’s a good idea to store this object reference in a local variable for later reference (for example, to close it): Set oNavWin = window.open("nav.html") Options Replace History Item

Opening a New Window (2) The following code example shows how you can open a navigation window from an HTML page: <!-- OpenWindow.htm --> <html><head> <script type="text/javascript"> function openwindow() { window.open("http://www.w3schools.com","my_new_window","toolbar=yes,location=yes,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=no,copyhistory=yes,width=400,height=400") } </script></head><body><form> <input type="button" value="Open Window" onclick="openwindow()"/> </form></body></html>

The End