By the end of this section of the practical, the students should be able to:

Similar documents
The first sample. What is JavaScript?

Introduction to JavaScript

JavaScript code is inserted between tags, just like normal HTML tags:

LECTURE-3. Exceptions JS Events. CS3101: Programming Languages: Javascript Ramana Isukapalli

Place User-Defined Functions in the HEAD Section

CISH-6510 Web Application Design and Development. Overview of JavaScript. Overview

Web Development & Design Foundations with HTML5, 8 th Edition Instructor Materials Chapter 14 Test Bank

Exercise 1: Basic HTML and JavaScript

Web Programming/Scripting: JavaScript

710 Index Attributes, 127 action attribute, 263 assigning, bottom attribute, domain name attribute, 481 expiration date attribute, 480 8

What Is JavaScript? A scripting language based on an object-orientated programming philosophy.

1001ICT Introduction To Programming Lecture Notes

Lecture 14. Introduction to JavaScript. Mr. Mubashir Ali Lecturer (Dept. of Computer Science)

Q1. What is JavaScript?

write vs. writeln Prompting as Page Loads Today s Goals CSCI 2910 Client/Server-Side Programming Intermediate File vs. HTML Output

Lesson 5: Introduction to Events

COMS 469: Interactive Media II

8/19/2018. Web Development & Design Foundations with HTML5. Learning Objectives (1 of 2) Learning Objectives (2 of 2) What is JavaScript?

Like most objects, String objects need to be created before they can be used. To create a String object, we can write

CHAPTER 6 JAVASCRIPT PART 1

CMPT 100 : INTRODUCTION TO

Programming language components

New Media Production Lecture 7 Javascript

LECTURE-2. Functions review HTML Forms. Arrays Exceptions Events. CS3101: Scripting Languages: Javascript Ramana Isukapalli

Client vs Server Scripting

Web Development & Design Foundations with HTML5

By the end of this section of the practical, the students should be able to:

Such JavaScript Very Wow

C Functions. 5.2 Program Modules in C

JAVASCRIPT. Computer Science & Engineering LOGO

(Refer Slide Time: 01:40)

The Very Basics of the R Interpreter

Session 16. JavaScript Part 1. Reading

PES DEGREE COLLEGE BANGALORE SOUTH CAMPUS 1 K.M. before Electronic City, Bangalore WEB PROGRAMMING Solution Set II

JavaScript By: A. Mousavi & P. Broomhead SERG, School of Engineering Design, Brunel University, UK

Fundamentals of Website Development

Indian Institute of Technology Kharagpur. Javascript Part III. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T.

UNIT 3 SECTION 1 Answer the following questions Q.1: What is an editor? editor editor Q.2: What do you understand by a web browser?

COMS 469: Interactive Media II

5. JavaScript Basics

CT 229 Java Syntax Continued

<form>. input elements. </form>

New Perspectives on Creating Web Pages with HTML. Tutorial Objectives

Session 6. JavaScript Part 1. Reading

JavaScript is described in detail in many books on the subject, and there is excellent tutorial material at

What is Java Script? Writing to The HTML Document. What Can JavaScript do? CMPT 165: Java Script

EVENT-DRIVEN PROGRAMMING

Software. Programming Languages. Types of Software. Types of Languages. Types of Programming. Software does something

Using Game Maker 8: GML Scripting

Lesson 7: If Statement and Comparison Operators

JUN / 04 VERSION 7.0

Methods (Deitel chapter 6)

JavaScript s role on the Web

Methods (Deitel chapter 6)

CSS The web browser uses its own resources, and eases the burden on the server. It has fewer features than server side scripting.

The Graphing Calculator

Functions. Systems Programming Concepts

About the Author. Liability

VBScript: Math Functions

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Methods CSC 121 Fall 2014 Howard Rosenthal

Programing for Digital Media EE1707. Lecture 3 JavaScript By: A. Mousavi and P. Broomhead SERG, School of Engineering Design, Brunel University, UK

Lecture 2. The variable 'x' can store integers, characters, string, float, boolean.

Enhancing Web Pages with JavaScript

Netscape Introduction to the JavaScript Language

Chapter 3 - Simple JavaScript - Programming Basics. Lesson 1 - JavaScript: What is it and what does it look like?

Then there are methods ; each method describes an action that can be done to (or with) the object.

ORB Education Quality Teaching Resources

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

A Balanced Introduction to Computer Science, 3/E

INTRODUCTION TO WEB DEVELOPMENT AND HTML. Lecture 13: Intro to JavaScript - Spring 2011

JavaScript!= Java. Intro to JavaScript. What is JavaScript? Intro to JavaScript 4/17/2013 INTRODUCTION TO WEB DEVELOPMENT AND HTML

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

Lesson 1: Writing Your First JavaScript

Dr Richard Greenaway

Methods: A Deeper Look

Downloaded from Chapter 2. Functions

Chapter 16. JavaScript 3: Functions Table of Contents

PIC 40A. Lecture 10: JS: Wrapper objects, Input and Output, Control structures, random numbers. Copyright 2011 Jukka Virtanen UCLA 1 04/24/17

JavaScript Introduction

COMS 469: Interactive Media II

JavaScript and XHTML. Prof. D. Krupesha, PESIT, Bangalore

JavaScript: Introduction, Types

Built-in Types of Data

Macro Programming Reference Guide. Copyright 2005 Scott Martinez

Math 2250 MATLAB TUTORIAL Fall 2005

Javascript. A key was pressed OR released. A key was released. A mouse button was pressed.

Variable Definition and Statement Suppression You can create your own variables, and assign them values using = >> a = a = 3.

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Exercise 1 Using Boolean variables, incorporating JavaScript code into your HTML webpage and using the document object

Want to add cool effects like rollovers and pop-up windows?

Lecture 5. Connecting Code to Web Page Events

Javascript Hierarchy Objects Object Properties Methods Event Handlers. onload onunload onblur onfocus

CSC Web Programming. Introduction to JavaScript

Computer Programming in MATLAB

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Pace University. Fundamental Concepts of CS121 1

MaSH Environment nxt. Contents

CSE123. Program Design and Modular Programming Functions 1-1

Transcription:

By the end of this section of the practical, the students should be able to: Write JavaScript to generate HTML Create simple scripts which include input and output statements, arithmetic, relational and equality operators. Understand counter-controlled repetition and sentinel-controlled repetition. Write functions and pass information between functions Write programs that use JavaScript objects such as Math, String and Date. 6 Introduction JavaScript, which was originally named LiveScript, was developed by Netscape. LiveScript became joint venture of Netscape and Sun Microsystems and its name was changed to JavaScript. Microsoft s JavaScript is named Jscript. The original goal of JavaScript was to provide programming capability at both the server and the client ends of a Web connection. Server-side JavaScript can serve as an alternative for some of what is done with server-side programming, in which computational capability resides on the server and is requested by the client. On the other hand, Client-side JavaScript cannot replace all server-side computing. It defines the collection of objects, methods, and properties that allow scripts to interact with HTML documents on the client. In this chapter, you will learn to write, test and debug Clientside JavaScript.

6.1 Hands-on Exercises Javascript can enhance the dynamics and interactive features of your page by allowing you to perform calculations, check forms, write interactive games, add special effects, customize graphics selections, create security passwords and more. JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types. Objects and Properties Your web page document is just one of the many objects. Any table, form, button, image, or link on your page is also an object. Each object has certain properties (information about the object). For example, the background color of your document is written document.bgcolor. You would change the color of your page to red by writing the line: document.bgcolor="red". The contents (or value) of a textbox named "password" in a form named "entryform" is document.entryform.password.value. Methods Most objects have a certain collection of things that they can do. Different objects can do different things. A new document is opened with the method document.open() You can write "Hello World" into a document by typing document.write("hello World"). open() and write() are both methods of the object: document. Events Events are how we trigger our functions to run. The easiest example is a button, whose definition includes the words onclick="run_my_function()". The onclick event, as its name implies, will run the function when the user clicks on the button. Other events include OnMouseOver, OnMouseOut, OnFocus, OnBlur, OnLoad, and OnUnload.

6.1.1 Generating HTML & Displaying Variables 1. Open a text editor and type the following HTML document that contains JavaScript code. Save the file as Basic.html. 2. The HTML file executes the JavaScript statement to display the Welcome to my website. text. 3. Line 8, 11: JavaScript code is included in an HTML document using the <script></script> tag.

4. Line 10: The word document.write is a standard JavaScript command for writing output to a page. "document" is a built-in object representing the HTML document where the JavaScript is embedded in. "write(string)" is a method provided by the "document" object. It writes the specified string into the HTML document represented by the "document" object. 5. Line 9: The two forward slashes at the end of comment line (//) are a JavaScript comment symbol. This prevents the JavaScript compiler from compiling the line. 6. Now, you will modify the above code. To do this, add a new output statement which formats the text with <h1> tag. Declare a JavaScript variable named title and assign the text Faizal s website. as value to it, and then display the variable as shown below. 7. Your code should produce the following output on the browser. 6.1.2 Using an External JavaScript

1. The JavaScript you have created so far have only applied to the document itself. Internal scripts apply only to the document in which they were created. Now, you ll learn how to import an external JavaScript which contains the script you defined in respective document. The reason of creating external JavaScript is to enable user to run the same JavaScript on several pages, without having to write the same script on every page. 2. Open a new page on a text editor and copy all the JavaScript you have created in the Basic.html in Exercise 6.1.1. Save the external JavaScript file with an external.js file extension in the same folder with the html document. Please remember that the external script cannot contain the <script> tag. 3. To embed the external JavaScript in Basic.html, point to the external.js file in the src attribute of the <script> tag like below. Remember to place the script exactly where you normally would write the script. <head> <script type = text/javascript src= external.js ></script> </head> <body> </body> 4. Open the Basic.html on the browser. Your code should produce the output as same Exercise 6.1.1. 6.1.3 Built-in Alert, Confirm, Prompt Commands As mentioned previously, JavaScript treats window as an object which has properties and method to access. Window (PROPERTIES): document, bgcolor, fgcolor, default status, frame, parent, referrer, lastmodified, history, location, name etc.

Window (METHODS): alert, prompt, confirm, write, writeln, close, open, settimeout, reload, cleartimeout, blur, focus etc. The alert, confirm and prompt message boxes are methods of the interface window object. Because the window object is at the top of the object hierarchy, you do not have to use the full name (for example, window.alert()) of any of these dialog boxes. However, it is a good idea to use the full name, because it helps you remember which object the methods belong to. 1. To demonstrate this, type down this code below and save your file as dialogbox.html. The following code will add an alert box by using a HTML button and the onclick event. <head><title>dialog Boxes Demos</title> <body> <form name="myform"> <input type="button" value="click here" onclick="window.alert('thank you for your submission.'); "> </form> </body> 2. Whatever you put inside the quotation marks in windows.alert, it will display it in the pop-up box. The button triggers an alert method when it's clicked. When a user triggers an event, your browser usually does something in response. Click a link, and it loads up the page in the link's href. Click into a form field and it receives the browser's focus. These are the default event handlers for each object in a HTML page. When we write our own event handlers, we write them directly into the HTML code so the browser knows which element we're addressing, and add in new commands on top of the existing default actions. Event Handlers aren't scripts in themselves, but often use variables, methods and functions from scripts to perform their action. You will learn more about event handlers in the next chapter.

3. Javascript Alert box are ideal for the following situations: If you want to be absolutely sure they see a message before doing anything on the website. You would like to warn the user about something. An error has occurred and you want to inform the user of the problem. When asking the user for confirmation of some action. 4. Next, you are going to use a Confirm box. Confirmation are most often used to confirm an important actions that are taking place on a website. For example, they may be used to confirm an order submission or notify visitors that a link they clicked will take them to another website. Modify dialogbox.html by replacing the existing code with these blocks of snippets. <head> <title>dialog Boxes and Event Handlers</title> <script type="text/javascript"> function myconfirm(){ var answer = confirm("you are about to leave our site. We are not responsible for a any third party websites contents. Are you sure you want to proceed?"); if(answer) { window.location="http://www.softpedia.com"; } else { document.write("thanks for sticking around."); } }

</script> </head> <body> <form name="myform"> <input type="button" value="download Apps at Softpedia" onclick="myconfirm(); "> </form> </body> 5. An interactive dialogue box will be displayed with the message-jump to another URL. If you click OK you will be taken to that page because the window.location property is addressed to that place. If you click Cancel then it will be cancelled. 6. Now, insert another button between the existing form tag. <input type="button" value="calculate the sum of 2 numbers" onclick="myprompt(); "> 7. Finally, place another JavaScript function in the head section. function myprompt() { var num1, num2, result; num1=parseint(window.prompt("enter the first number","0")); num2=parseint(window.prompt("enter the second number","0")); result = num1 + num2; document.write('the sum of ' + num1 + ' and ' + num2 + ' is ' + result);

} 8. The Prompt box is very useful when you want to pop-up a text box to get user input. Thus it enable you to interact with the user. The user needs to fill in the field and then click OK. The parseint() function converts a string to an integer value. 9. Close your previous file and create a new HTML document. Insert this code and save it as SwitchCase.html <head><title>more Examples</title></head> <body> <script type="text/javascript"> var number = prompt("congratulations for being the winner of our lucky draw contest. Enter a number between 1 to 3 to collect your prize.", 0) switch (number) { case (number = "1"): {document.write("you have won yourself an IPhone!"); document.write("<br /><img src='http://farah.com.nu/pix/iphone.jpg'/> ");} break; case (number = "2"): {document.write("you have won yourself an IPod!"); document.write("<br /><img src='http://farah.com.nu/pix/ipod.jpg'/>");} break; case (number = "3"):

{document.write("you have won yourself an IPad!"); document.write("<br /><img src='http://farah.com.nu/pix/ipad.jpg'/>");} break; default: alert("sorry, wrong value."); break; } </script> </body> 10. So far, you have explored Javascript programming syntax such as variables, functions, operators, expressions, assignment, relational, logical arithmetic, operators, control structures such as if.. else and switch..case statements. Next, you will work with more arithmetic operations and iteration loops in your program. 6.1.4 Using Loop Statements 1. The For loop is used when you know in advance how many times the script should perform. Type down the code below and save your file as LoopFor.html. <head> <title>temperature Converter Table</title> </head> <body> <table border=3> <tr><td>celsius</td><td>fahrenheit</td></tr> <script language="javascript"> for (celsius=-8; celsius<=47; celsius=celsius+1) { document.write("<tr><td>"+celsius+"</td><td>"

+((celsius*9/5)+32)+"</td></tr>"); } </script> </table> </body> 2. The While loop is used when you want the loop to continue until a certain condition becomes true. Create a new HTML document named LoopWhile.html and write this code. <head><title>quick Quiz</title></head> <body> <script type="text/javascript"> var x=5*5; x=prompt("what is 5 x 5?"); while (x!= 25) { alert("wrong answer"); x=prompt("what is 5 x 5?",0); } document.write("correct, the answer is " + x) </script> </body> 3. You have declared variable x and initialized 25. Then, you set it equal to the prompt box. The prompt box asks the product of 5x5 and continues asking until true answer is provided. It also informs each wrong attempts or each loop

4. Try modifying the current code using a Do.. While loop instead. 6.1.5 Working with JavaScripts Math Objects Among the wide array of features offered by the Math object are several special values such as PI, natural logarithms, and common square roots, trigonometric methods, rounding methods, an absolute value method, and more. These can be used to make complex calculations in Javascript when needed. Name Abs() Acos() Asin() Atan() Ceil() Cos() Exp() floor() log() max() min() pow() random() round() sin() sqrt() tan() Usage Calculates the absolute value of a number. Calculates the arc cosine of a number returns result in radians. Calculates the arc sine of a number returns result in radians. Calculates the arc tangent of a number returns result in radians. Returns the next integer greater than or equal to a number. Calculates the cosine of a number. Calculates e to the power of a number. Returns the next integer less than or equal to a number. Calculates the natural logarithm of a number. Returns the greater of two numbers takes two arguments. Returns the least of two numbers takes two arguments Calculates the value of one number to the power of a second number takes two arguments. Returns a random number between zero and one. Presently, this is only implemented in UNIX versions of Navigator 2.0. Rounds a number to the nearest integer. Calculates the sine of a number. Calculates the square root of a number. Calculates the tangent of a number.

1. In this exercise, you are going to use the pow() method to calculate the volume of a cube based on the side s value. 2. Type down this code below and save your file as Math.html. <head><title>volume of Cube</title></head> <body> <script type = "text/javascript"> var s, vol; s = parseint(window.prompt("enter the side of the volume","0")); vol = Math.pow(s,3); document.write("the volume of the cube is " + vol); </script> </body>