Welcome to Web Technology Course by Mr B

Welcome to Web Technology Course by Mr. B. Srinu Asst. Prof. Department of CSE

UNIT-5 Introduction to Java Script (Client side programming)

Introduction to Java Script §Browsers have limited functionality §Text, images, tables, frames §Java. Script allows for interactivity §Browser/page manipulation §Reacting to user actions §A type of programming language §Easy to learn §Developed by Netscape

Java. Script Allows Interactivity • Improve appearance • Especially graphics • Visual feedback • Site navigation • Perform calculations • Validation of input • Other technologies

How Does It Work? §Embedded within HTML page §View source §Executes on client §Fast, no connection needed once loaded §Simple programming statements combined with HTML tags §Interpreted (not compiled) § No special tools required

Learning Java. Script • Special syntax to learn • Learn the basics and then use other people's (lots of free sites) • Write it in a text editor, view results in browser • You need to revise your HTML • You need patience and good eyesight

Why Study Java. Script? Java. Script is one of the 3 languages all web developers must learn: 1. HTML to define the content of web pages 2. CSS to specify the layout of web pages 3. Java. Script to program the behavior of web pages

Java. Script Statements <html> <head><title>My Page</title></head> <body> <script language="Java. Script"> document. write('This is my first Java. Script Page'); </script> </body> </html>

Java. Script Statements <html> <head><title>My Page</title></head> <body> <script language="Java. Script"> document. write(‘<h 2>This is my first Java. Script Page</h 2>'); </script> </body> </html> HTML written inside Java. Script

Java. Script Statements <html> <head><title>My Page</title></head> <body> <p> <a href="myfile. html">My Page</a> <a href="myfile. html" on. Mouseover="window. alert('Hello'); "> My Page</A> </p> </body> HTML written inside Java. Script </html>

Java. Script outputs Java. Script can "display" data in different ways: Writing into an HTML element, using inner. HTML. Writing into the HTML output using document. write(). Writing into an alert box, using window. alert(). Writing into the browser console, using console. log().

Using inner. HTML To access an HTML element, Java. Script can use the document. get. Element. By. Id(id) method. The id attribute defines the HTML element. The inner. HTML property defines the HTML content: Example <!DOCTYPE html> <body> <h 1>My First Web Page</h 1> <p>My First Paragraph</p> <p id="demo"></p> <script> document. get. Element. By. Id("demo"). inner. HTML = 5 + 6; </script> </body> </html>

Using document. write() Example <!DOCTYPE html> <body> <h 1>My First Web Page</h 1> <p>My first paragraph. </p> <script> document. write(5 + 6); </script> </body> </html>

Using document. write() Example <!DOCTYPE html> <body> <h 2>My First Web Page</h 2> <p>My first paragraph. </p> <button type="button" onclick="document. write(5 + 6)">Try it</button> </body> </html>

Using window. alert() Example <!DOCTYPE html> <body> <h 1>My First Web Page</h 1> <p>My first paragraph. </p> <script> window. alert(5 + 6); </script> </body> </html>

Using console. log() Example <!DOCTYPE html> <body> <script> console. log(5 + 6); </script> </body> </html>

Java. Script Where To • In HTML, Java. Script code must be inserted between <script> and </script> tags. • Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both. • External Java. Script External file: my. Script. js Ex: function my. Function() { document. get. Element. By. Id("demo"). inner. HTML = "Paragraph changed. "; } <script src="my. Script. js"></script>

Java. Script Variables Java. Script variables are containers for storing data values. Example var x = 5; var y = 6; var z = x + y; The general rules for constructing names for variables (unique identifiers) are: §Names can contain letters, digits, underscores, and dollar signs. §Names must begin with a letter §Names can also begin with $ and _ (but we will not use it in this tutorial) §Names are case sensitive (y and Y are different variables) §Reserved words (like Java. Script keywords) cannot be used as names

Declaring (Creating) Java. Script Variables Creating a variable in Java. Script is called "declaring" a variable. You declare a Java. Script variable with the var keyword: var car. Name; After the declaration, the variable has no value. (Technically it has the value of undefined) To assign a value to the variable, use the equal sign: car. Name = "Volvo";

Declaring (Creating) Java. Script Variables Example <p id="demo"></p> <script> var car. Name = "Volvo"; document. get. Element. By. Id("demo"). inner. HTML = car. Name; </script>

Java. Script Functions A Java. Script function is a block of code designed to perform a particular task. A Java. Script function is executed when "something" invokes it (calls it). Java. Script Function Syntax: A Java. Script function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter 1, parameter 2, . . . ) The code to be executed, by the function, is placed inside curly brackets: {} function name(parameter 1, parameter 2, parameter 3) { code to be executed }

Java. Script Functions Function parameters are listed inside the parentheses () in the function definition. Function arguments are the values received by the function when it is invoked. Inside the function, the arguments (the parameters) behave as local variables. Function Invocation: The code inside the function will execute when "something" invokes (calls) the function: • When an event occurs (when a user clicks a button) • When it is invoked (called) from Java. Script code • Automatically (self invoked)

Java. Script Functions Function Return • When Java. Script reaches a return statement, the function will stop executing. • If the function was invoked from a statement, Java. Script will "return" to execute the code after the invoking statement. • Functions often compute a return value. • The return value is "returned" back to the "caller": Example Calculate the product of two numbers, and return the result: var x = my. Function(4, 3); // Function is called, return value will end up in x function my. Function(a, b) { return a * b; // Function returns the product of a and b }

Java. Script Functions Function Return • When Java. Script reaches a return statement, the function will stop executing. • If the function was invoked from a statement, Java. Script will "return" to execute the code after the invoking statement. • Functions often compute a return value. • The return value is "returned" back to the "caller": Example Calculate the product of two numbers, and return the result: var x = my. Function(4, 3); // Function is called, return value will end up in x function my. Function(a, b) { return a * b; // Function returns the product of a and b }

Java. Script Functions The () Operator Invokes the Function <!DOCTYPE html> <body> <h 2>Java. Script Functions</h 2> <p>Accessing a function without () will return the function definition instead of the function result: </p> <p id="demo"></p> <script> function to. Celsius(f) { return (5/9) * (f-32); } document. get. Element. By. Id("demo"). inner. HTML = to. Celsius; </script> </body> </html>

Java. Script Functions Output: Accessing a function without () will return the function definition instead of the function result: function to. Celsius(f) { return (5/9) * (f-32); }

Java. Script Scope determines the accessibility (visibility) of variables. In Java. Script there are two types of scope: • Local scope • Global scope Java. Script has function scope: Each function creates a new scope.

Java. Script Scope(cont. . ) Local Java. Script Variables: Variables declared within a Java. Script function, become LOCAL to the function. Local variables have local scope: They can only be accessed within the function. Example // code here can not use car. Name function my. Function() { var car. Name = "Volvo"; // code here can use car. Name }

Local Variables: Example Program <!DOCTYPE html> <body> <p>The local variable car. Name cannot be accessed from code outside the function: </p> <p id="demo"></p> <script> my. Function(); document. get. Element. By. Id("demo"). inner. HTML = "The type of car. Name is " + typeof car. Name; function my. Function() { var car. Name = "Volvo"; } </script> </body> </html>

Java. Script Scope(cont. . ) Global Java. Script Variables • A variable declared outside a function, becomes GLOBAL. • A global variable has global scope: All scripts and functions on a web page can access it. Example var car. Name = " Volvo"; // code here can use car. Name function my. Function() { // code here can use car. Name }

Example code: <!DOCTYPE html> <body> <p>A GLOBAL variable can be accessed from any script or function. </p> <p id="demo"></p> <script> var car. Name = "Volvo"; my. Function(); function my. Function() { document. get. Element. By. Id("demo"). inner. HTML = "I can display " + car. Name; } </script> </body>

Automatically Global If you assign a value to a variable that has not been declared, it will automatically become a GLOBALvariable. This code example will declare a global variable car. Name, even if the value is assigned inside a function. Example my. Function(); // code here can use car. Name function my. Function() { car. Name = "Volvo"; }

Java. Script Events HTML events are "things" that happen to HTML elements. When Java. Script is used in HTML pages, Java. Script can "react" on these events. HTML Events An HTML event can be something the browser does, or something a user does. Here are some examples of HTML events: • An HTML web page has finished loading • An HTML input field was changed • An HTML button was clicked

Java. Script Events HTML allows event handler attributes, with Java. Script code, to be added to HTML elements. With single quotes: <element event='some Java. Script'> With double quotes: <element event="some Java. Script"> In the following example, an onclick attribute (with code), is added to a button element: Example <button onclick="document. get. Element. By. Id('demo'). inner. HTML = Date()">The time is? </button>

Java. Script Events Common HTML Events Here is a list of some common HTML events: Event. Description • Onchange An HTML element has been changed • Onclick The user clicks an HTML element • Onmouseover The user moves the mouse over an HTML element • Onmouseout The user moves the mouse away from an HTML element • onkeydown The user pushes a keyboard key • Onload The browser has finished loading the page

Java. Script Events Event handlers can be used to handle, and verify, user input, user actions, and browser actions: • Things that should be done every time a page loads • Things that should be done when the page is closed • Action that should be performed when a user clicks a button • Content that should be verified when a user inputs data. . etc. Many different methods can be used to let Java. Script work with events: • HTML event attributes can execute Java. Script code directly • HTML event attributes can call Java. Script functions • You can assign your own event handler functions to HTML elements • You can prevents from being sent or being handled. . etc. .

Java. Script Events • Onclick The user clicks an HTML element <!DOCTYPE html> <body> <button onclick="document. get. Element. By. Id('demo'). inner. HTML=Date()">The time is? </button> <p id="demo"></p> </body> </html>

Java. Script Events • Onclick The user clicks an HTML element <!DOCTYPE html> <body> <button onclick="document. get. Element. By. Id('demo'). inner. HTML=Date()">The time is? </button> <p id="demo"></p> </body> </html>

Java. Script Events Onkeydown and onkeyup The user clicks an HTML element (example 1) <!DOCTYPE html> <body> <p>Press and hold down a key inside the text field to set a red background color. Release the key to set a green background color. </p> <input type="text" id="demo" onkeydown="keydown. Function()" onkeyup="keyup. Function()"> <script> function keydown. Function() { document. get. Element. By. Id("demo"). style. background. Color = "red"; } function keyup. Function() { document. get. Element. By. Id("demo"). style. background. Color = "green"; } </script>

Java. Script Events Onkeydown and onkeyup The user clicks an HTML element (example 1) <!DOCTYPE html> <body> <p>This example uses the add. Event. Listener() method to attach a "keydown" event to an input element. </p> <p>Press a key inside the text field to set a red background color. </p> <input type="text" id="demo"> <script> document. get. Element. By. Id("demo"). add. Event. Listener("keydown", my. Function); function my. Function() { document. get. Element. By. Id("demo"). style. background. Color = "red"; } </script> </body> </html>

Java. Script Events onmousedown Event The onmousedown event occurs when a user presses a mouse button over an element. Tip: The order of events related to the onmousedown event (for the left/middle mouse button): • onmousedown • onmouseup • onclick

Java. Script Events onmousedown Event <!DOCTYPE html> <body> <p>This example uses the add. Event. Listener() method to attach a "mousedown" and "mouseup" event to a p element. </p> <p id="demo">Click me. </p> <script> document. get. Element. By. Id("demo"). add. Event. Listener("mousedown", mouse. Down); document. get. Element. By. Id("demo"). add. Event. Listener("mouseup", mouse. Up); function mouse. Down() { document. get. Element. By. Id("demo"). inner. HTML = "The mouse button is held down. "; } function mouse. Up() { document. get. Element. By. Id("demo"). inner. HTML = "You released the mouse button. "; } </script> </body> </html>

Java. Script Form Validation HTML form validation can be done by Java. Script. If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form from being submitted: Java. Script Example function validate. Form() { var x = document. forms["my. Form"]["fname"]. value; if (x == "") { alert("Name must be filled out"); return false; } }

Form Validation program <!DOCTYPE html> <head> <script> function validate. Form() { var x = document. forms["my. Form"]["fname"]. value; if (x == "") { alert("Name must be filled out"); return false; } } </script> </head> <body> <form name="my. Form" action="/action_page. php" onsubmit="return validate. Form()" method="post"> Name: <input type="text" name="fname"> <input type="submit" value="Submit"> </form> </body>

Form Validation program <!DOCTYPE html> <body> <h 2>Java. Script Can Validate Input</h 2> <p>Please input a number between 1 and 10: </p> <input id="numb"> <button type="button" onclick="my. Function()">Submit</button> <p id="demo"></p> <script> function my. Function() { var x, text; // Get the value of the input field with id="numb" x = document. get. Element. By. Id("numb"). value; // If x is Not a Number or less than one or greater than 10 if (is. Na. N(x) || x < 1 || x > 10) { text = "Input not valid"; } else { text = "Input OK"; } document. get. Element. By. Id("demo"). inner. HTML = text; } </script> </body> </html>

Automatic HTML Form Validation HTML form validation can be performed automatically by the browser: If a form field (fname) is empty, the required attribute prevents this form from being submitted: <!DOCTYPE html> <body> <form action="/action_page. php" method="post"> <input type="text" name="fname" required> <input type="submit" value="Submit"> </form> <p>If you click submit, without filling out the text field, your browser will display an error message. </p> </body> </html>

Data Validation Data validation is the process of ensuring that user input is clean, correct, and useful. Typical validation tasks are: • has the user filled in all required fields? • has the user entered a valid date? • has the user entered text in a numeric field? Most often, the purpose of data validation is to ensure correct user input. Validation can be defined by many different methods, and deployed in many different ways. Server side validation is performed by a web server, after input has been sent to the server. Client side validation is performed by a web browser, before input is sent to a web server.

HTML Constraint Validation HTML 5 introduced a new HTML validation concept called constraint validation. HTML constraint validation is based on: • Constraint validation HTML Input Attributes • Constraint validation CSS Pseudo Selectors • Constraint validation DOM Properties and Methods

Constraint Validation HTML Input Attributes Attribute Description disabled Specifies that the input element should be disabled max Specifies the maximum value of an input element min Specifies the minimum value of an input element pattern Specifies the value pattern of an input element required Specifies that the input field requires an element type Specifies the type of an input element

Example 1 <!DOCTYPE html> <body> <h 2>The readonly Attribute</h 2> <p>The readonly attribute specifies that the input field is read only (cannot be changed): </p> <form action=""> First name: <input type="text" name="firstname" value ="John" readonly> Last name: <input type="text" name="lastname"> </form> </body> </html>

Example 2 <!DOCTYPE html> <body> <h 2>The disabled Attribute</h 2> <p>The disabled attribute specifies that the input field is disabled: </p> <form action=""> First name: <input type="text" name="firstname" value ="John" disabled> Last name: <input type="text" name="lastname"> </form> </body> </html>
- Slides: 51