Html session 12 :
Introduction
Consider an organization that provides a Web site that allows its customers to view their products. The company has received frequent customer feedbacks to provide the shopping facility online. Therefore, the company has decided to add the shopping facility in their Web site by creating dynamic Web pages. These Web pages will allow the user to shop for the products online. Here, the main task of the developer is to validate the customer’s inputs while they shop online. For example, details such as credit card number, email, and phone number entered by the customer must be in a proper format. Further, the developer also needs to retrieve the chosen products and their quantity to calculate the total cost.
The developer can handle all these critical tasks by using a scripting language. A scripting language refers to a set of instructions that provides some functionality when the user interacts with a Web page.
Scripting
Scripting refers to a series of commands that are interpreted and executed sequentially and immediately on occurrence of an event. This event is an action generated by a user while interacting with a Web page. Examples of events include button clicks, selecting a product from a menu, and so on. Scripting languages are often embedded in the HTML pages to change the behavior of the Web pages according to the user’s requirements.
There are two types of scripting languages. They are as follows:
Client-side Scripting
Refers to a script being executed on the client’s machine by the browser.
Server-side Scripting
Refers to a script being executed on a Web server to generate dynamic HTML pages.
JavaScript
JavaScript is a scripting language that allows you to build dynamic Web pages by ensuring maximum user interactivity.
JavaScript language is an object-based language, which means that it provides objects for specifying functionalities. In real life, an object is a visible entity such as a car or a table. Every object has some characteristics and is capable of performing certain actions. Similarly, in a scripting language, an object has a unique identity, state, and behavior.
The identity of the object distinguishes it from the other objects of the same type. The state of the object refers to its characteristics, whereas the behavior of the object consists of its possible actions.
The object stores its identity and state in fields (also called variables) and exposes its behavior through functions (actions).
Figure 12.3 displays the objects .
Versions of JavaScript
The first version of JavaScript was developed by Brendan Eich at Netscape in 1995 and was named JavaScript 1.0. Netscape Navigator 2.0 and Internet Explorer 3.0 supported JavaScript 1.0. Over the period, it gradually evolved with newer versions where each version provided better features and functionalities as compared to their previous versions.
lists the various versions of JavaScript language.
Version Description
1.1 Is supported from 3.0 version of the Netscape Navigator and Internet Explorer
1.2 Is supported by the Internet Explorer from version 4.0
1.3 Is supported by the Internet Explorer from version 5.0, Netscape Navigator from version 4.0, and Opera from version 5.0
1.4 Is supported by servers of Netscape and Opera 6
1.5 Is supported by the Internet Explorer from version 6.0, Netscape Navigator from version 6.0, and Mozilla Firefox from version 1.0
Version Description
1.6 Is supported in the latest versions of the Internet Explorer and Netscape Navigator browsers. It is also supported by Mozilla Firefox from version 1.5
1.7 Is supported in the latest versions of the Internet Explorer and Netscape Navigator browsers. It is also supported by Mozilla Firefox from version 2.0
Client-side JavaScript
JavaScript is a scripting language, which can be executed on the client-side and on the server-side. A client-side JavaScript (CSJS) is executed by the browser on the user’s workstation. A client-side script might contain instructions for the browser to handle user interactivity. These instructions might be to change the look or content of the Web page based on the user inputs. Examples include displaying a welcome page with the username, displaying date and time, validating that the required user details are filled, and so on.
A JavaScript is either embedded in an HTML page or is separately defined in a file, which is saved with .js extension. In client-side scripting, when an HTML is requested, the Web server sends all the required files to the user’s computer. The Web browser executes the script and displays the HTML page to the user along with any tangible output of the script.
Server-side JavaScript
A server-side JavaScript (SSJS) is executed by the Web server when an HTML page is requested by a user. The output of a server-side JavaScript is sent to the user and is displayed by the browser. In this case, a user might not be aware that a script was executed on the server to produce the desirable output.
A server-side JavaScript can interact with the database, fetch the required information specific to the user, and display it to the user. This means that server-side scripting fulfills the goal of providing dynamic content in Web pages. Unlike client-side JavaScript, HTML pages using server-side JavaScript are compiled into bytecode files on the server. Compilation is a process of converting the code into machine-independent code. This machine-independent code is known as the bytecode, which is an executable file. The Web server runs this executable to generate the desired output.
<Script> Tag
The <script> tag defines a script for an HTML page to make them interactive. The browser that supports scripts interprets and executes the script specified under the <script> tag when the page loads in the browser. You can directly insert a JavaScript code under the <script> tag. You can define multiple <script> tags either in the <head> or in the <body> elements of an HTML page. In HTML5, the type attribute specifying the scripting language is no longer required as it is optional.
Code Snippet 1 demonstrates the use of the <script> tag.
<!DOCTYPE html>
<html>
<head>
<script>
document.write(“Welcome to the Digital World”);
</script>
</head>
<body>
...
</body>
</html>
There are two main purposes of the <script> tag, which are as follows:
Identifies a given segment of script in the HTML page
Loads an external script file
12.8 Variables in JavaScript
A variable refers to a symbolic name that holds a value, which keeps changing. For example, age of a student and salary of an employee can be treated as variables. A real life example for variables includes the variables used in algebraic expressions that store values.
In JavaScript, a variable is a unique location in the computer’s memory that stores a value and has a unique name. The name of the variable is used to access and read the value stored in it. A variable can store different types of data such as a character, a number, or a string. Therefore, a variable acts as a container for saving and changing values during the execution of the script.
Declaring Variables
Declaring a variable refers to creating a variable by specifying the variable name. For example, you can create a variable named studName to store the name of a student. Here, the variable name studName is referred to as an identifier. In JavaScript, the var keyword is used to create a variable by allocating memory to it. A keyword is a reserved word that holds a special meaning in JavaScript.
You can initialize the variable at the time of creating the variable or later. Initialization refers to the task of assigning a value to a variable. Once the variable is initialized, you can change the value of a variable as required.
Variables allow keeping track of data during the execution of the script. While referring to a variable, you are referring to the value of that variable. In JavaScript, you can declare and initialize multiple variables in a single statement. Figure 12.6 displays how to declare variables.
The syntax demonstrates how to declare variables in JavaScript.
Syntax:
var <variableName>;
where,
var: Is the keyword in JavaScript.
variableName: Is a valid variable name.
The syntax demonstrates how to initialize variables in JavaScript.
Syntax:
<variableName> = <value>;
where,
=: Is the assignment operator used to assign values.
value: Is the data that is to be stored in the variable.
The syntax demonstrates how to declare and initialize multiple variables in a single statement, which are separated by commas.
Syntax:
var <variableName1> = <value1>, <variableName2> = <value2>;
Code Snippet 2 declares two variables namely, studID and studName and assign values to them.
var studID;
var studName;
studID = 50;
studName = “David Fernando”;
This code assigns values to studID and studName variables by using the assignment operator (=). The value named David Fernando is specified within double quotes.
Code Snippet 3 demonstrates how to declare and initialize multiple variables in a single statement in JavaScript.
Variable Naming Rules
You cannot refer to a variable until it is created in JavaScript. JavaScript is a case-sensitive language. This means that if you specify X and x as variables, both of them are treated as two different variables. Similarly, in JavaScript, there are certain rules, which must be followed while specifying variables names. These rules for a variable name are as follows:
Can consist of digits, underscore, and alphabets.
Must begin with a letter or the underscore character.
Cannot begin with a number and cannot contain any punctuation marks.
Cannot contain any kind of special characters such as +, *, %, and so on.
Cannot contain spaces.
Cannot be a JavaScript keyword.
Showing posts with label html session 12. Show all posts
Showing posts with label html session 12. Show all posts
Wednesday, 6 May 2015
Tuesday, 5 May 2015
Html tutorials session12
Html tutorials theory :
Data Types in JavaScript :
A Web page designer can store different types of values such as numbers, characters, or strings in variables. However, the Web page designer must know what kind of data a particular variable is expected to store. To identify the type of data that can be stored in a variable, JavaScript provides different data types.
A Web page designer need not specify the data type while declaring variables. Due to this, JavaScript is referred to as the loosely typed language. This means that a variable holding a number can also hold a string value later. The values of variables are automatically mapped to their data types when the script is executed in the browser.
Data types in JavaScript are classified into two broad categories namely, primitive and composite data types. Primitive data types contain only a single value, whereas the composite data types contain a group of values.
Primitive Data Types
A primitive data type contains a single literal value such as a number or a string. A literal is a static value that you can assign to variables.
Table 12.2 lists the primitive data types.
Primitive Data Type Description
boolean Contains only two values namely, true or false
null Contains only one value namely, null. A variable of this value specifies that the variable has no value. This null value is a keyword and it is not the same as the value, zero
number Contains positive and negative numbers and numbers with decimal point. Some of the valid examples include 6, 7.5, -8, 7.5e-3, and so on
string Contains alphanumeric characters in single or double quotation marks. The single quotes is used to represent a string, which itself consists of quotation marks. A set of quotes without any characters within it is known as the null string
Composite Data Types
A composite data type stores a collection of multiple related values, unlike primitive data types. In JavaScript, all composite data types are treated as objects. A composite data type can be either predefined or user-defined in JavaScript.
Composite Data Type Description
Objects Refers to a collection of properties and functions. Properties specify the characteristics and functions determine the behavior of a JavaScript object
Functions Refers to a collection of statements, which are instructions to achieve a specific task
Arrays Refers to a collection of values stored in adjacent memory locations
Methods
JavaScript allows you to display information using the methods of the document object. The document object is a predefined object in JavaScript, which represents the HTML page and allow managing the page dynamically. Each object in JavaScript consists of methods, which fulfills a specific task. There are two methods of the document object, which displays any type of data in the browser. These methods are as follows:
write(): Displays any type of data.
writeln(): Displays any type of data and appends a new line character.
The syntax demonstrates the use of document.write()method, which allows you to display information in the displayed HTML page.
Syntax:
document.write(“<data>” + variables);
where,
data: Specifies strings enclosed in double quotes.
variables: Specify variable names whose value should be displayed on the HTML page.
The syntax demonstrates the use of document.writeln() method, which appends a new line character.
Syntax:
document.writeln(“<data>” + variables);
<!DOCTYPE HTML>
<html>
<head>
<title> JavaScript language </title>
<script>
document.write(“<p> JavaScript:”);
document.writeln(“is a scripting”);
document.write(“and a case-sensitive language.”);
</script>
</head>
<p>
JavaScript: is a scripting and a case-sensitive language.
</p>
</html>
The code uses the writeln() method to display the text after the colon without leaving a space. It finally appends a new line character after the text. Then, the text within the write() method is displayed on the same line after leaving a space.
The same paragraph is displayed in the body of the HTML page. Note that the text in the p element appears on different lines. In HTML, the text on the second line, and a case sensitive language will not be displayed in the new line in the browser even though the ENTER key is pressed while writing the code. Rather, it will be displayed on the same line with a space. The writeln() method also follows this same format.
Using Comments
A Web page designer might code complex script to fulfill a specific task. In JavaScript, a Web page designer specifies comments to provide information about a piece of code in the script. Comments describe the code in simple words so that somebody who reads the code can understand the code. Comments are small piece of text that makes the program more readable. While the script is executed, the browser can identify comments as they are marked with special characters and do not display them.
JavaScript supports two types of comments. These are as follows:
Single-line Comments
Single-line comments begin with two forward slashes (//). You can insert single-line comments as follows:
// This statement declares a variable named num.
var num;
Multi-line Comments
Multi-line comments begin with a forward slash followed by an asterisk (/*) and end with an asterisk followed by a forward slash (*/). You can insert multiple lines of comments as follows:
/* This line of code
declares a variable */
var num;
Escape Sequence Characters
An escape sequence character is a special character that is preceded by a backslash (\). Escape sequence characters are used to display special non-printing characters such as a tab space, a single space, or a backspace. These non-printing characters help in displaying formatted output to the user to maximize readability.
The backslash character specifies that the following character denotes a non-printing character. For example, \t is an escape sequence character that inserts a tab space similar to the Tab key of the keyboard. In JavaScript, the escape sequence characters must always be enclosed in double quotes.
There are multiple escape sequence characters in JavaScript that provides various kind of formatting.
Escape Sequence Non-Printing Character
\b Back space
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\’ Single quote
\” Double quote
\\ Backslash
\aaa Matches a Latin-1 encoding character using octal representation, where aaa are three octal numbers. For example, \251 represents the copyright symbol
\xaa Matches a Latin-1 encoding character using hexadecimal representation, where aa are two hexadecimal numbers. For example, \x61 represents the character ‘a’
\uaaaa Represent the Unicode encoding character, where aaaa are four hexadecimal numbers. For example, the character \ u0020 represents a space
Code Snippet :
<script>
document.write(“You need to have a \u0022credit card\u0022, if you
want to shop on the \’Internet\’.”);
</script>
The code uses a Unicode encoding character namely, \u0022, which represents double quotes. These open and close double quotes will contain the term credit card. Similarly, the word Internet will be placed in single quotes. The single quotes are specified using the backslash character
Built-in Functions
A function is a piece of code that performs some operations on variables to fulfill a specific task. It takes one or more input values, processes them, and returns an output value. JavaScript provides built-in functions that are already defined to fulfill a certain task. Table 12.5 lists the built-in functions.
Function Description Example
alert() Displays a dialog box with some information and OK button alert(“Please fill all the fields of the form”);
Displays a message box with the instruction
confirm() Displays a dialog box with OK and Cancel buttons. It verifies an action, which a user wants to perform confirm(“Are you sure you want to close the page?”);
Displays a message box with the question
parseInt() Converts a string value into a numeric value parseInt(“25 years”);
parseFloat() Converts a string into a number with decimal point parseFloat(“10.33”);
Returns 10.33
eval() Evaluates an expression and returns the evaluated result eval(“2+2”);
Returns 4
isNaN() Checks whether a value is not a number isNan(“Hello”);
Returns true
prompt() Displays a dialog box that accepts an input value through a text box. It also accepts the default value for the text box. prompt(“Enter your name”, “Name”);
Displays the message in the dialog box and Name in the text box.
Code Snippet 6:
<!DOCTYPE HTML>
<html>
<head>
<title> JavaScript language </title>
<script>
var value = “”;
var numone = prompt(“enter first value to perform the
multiplication operation”, value);
var numtwo = prompt(“enter second value to perform the
multiplication operation”, value);
var result = eval(numone * numtwo);
document.write(“The result of multiplying: “ + numone + “
and “ +
numtwo + “ is: “ + result + “.” );
</script>
</head>
</html>
In the code, it takes the first value from the user and stores in the numOne variable. Then, it takes the second value from the user and stores in the numTwo variable. It multiplies the values and stores the output in the result variable and then displays the output on the Web page.
Events
Consider a scenario where you want to design an Employee registration Web form. This form allows the users to fill in the appropriate details and click the submit button. When the user clicks the submit button, the form data is submitted to the server for validation purposes. In this case, when the user clicks the button, an event is generated. The submission of form refers to the action performed on click of the button.
An event occurs when a user interacts with the Web page. Some of the commonly generated events are mouse clicks, key strokes, and so on. The process of handling these events is known as event handling. displays the event .
Event Handling
Event handling is a process of specifying actions to be performed when an event occurs. This is done by using an event handler. An event handler is a scripting code or a function that defines the actions to be performed when the event is triggered.
When an event occurs, an event handler function that is associated with the specific event is invoked. The information about this generated event is updated on the event object. The event object is a built-in object, which can be accessed through the window object.
It specifies the event state, which includes information such as the location of mouse cursor, element on which an event occurred, and state of the keys in a keyboard .
Event Bubbling
Event bubbling is a mechanism that allows you to specify a common event handler for all child elements. This means that the parent element handles all the events generated by the child elements. For example, consider a Web page that consists of a paragraph and a table. The paragraph consists of multiple occurrences of italic text. Now, you want to change the color of each italic text of a paragraph when the user clicks a particular button. Instead of declaring an event handler for each italic text, you can declare it within the P element. This allows you to apply colors for all the italic text within the paragraph. This helps in reducing the development time and efforts since it minimizes the code. displays the event bubbling.
Data Types in JavaScript :
A Web page designer can store different types of values such as numbers, characters, or strings in variables. However, the Web page designer must know what kind of data a particular variable is expected to store. To identify the type of data that can be stored in a variable, JavaScript provides different data types.
A Web page designer need not specify the data type while declaring variables. Due to this, JavaScript is referred to as the loosely typed language. This means that a variable holding a number can also hold a string value later. The values of variables are automatically mapped to their data types when the script is executed in the browser.
Data types in JavaScript are classified into two broad categories namely, primitive and composite data types. Primitive data types contain only a single value, whereas the composite data types contain a group of values.
Primitive Data Types
A primitive data type contains a single literal value such as a number or a string. A literal is a static value that you can assign to variables.
Table 12.2 lists the primitive data types.
Primitive Data Type Description
boolean Contains only two values namely, true or false
null Contains only one value namely, null. A variable of this value specifies that the variable has no value. This null value is a keyword and it is not the same as the value, zero
number Contains positive and negative numbers and numbers with decimal point. Some of the valid examples include 6, 7.5, -8, 7.5e-3, and so on
string Contains alphanumeric characters in single or double quotation marks. The single quotes is used to represent a string, which itself consists of quotation marks. A set of quotes without any characters within it is known as the null string
Composite Data Types
A composite data type stores a collection of multiple related values, unlike primitive data types. In JavaScript, all composite data types are treated as objects. A composite data type can be either predefined or user-defined in JavaScript.
Composite Data Type Description
Objects Refers to a collection of properties and functions. Properties specify the characteristics and functions determine the behavior of a JavaScript object
Functions Refers to a collection of statements, which are instructions to achieve a specific task
Arrays Refers to a collection of values stored in adjacent memory locations
Methods
JavaScript allows you to display information using the methods of the document object. The document object is a predefined object in JavaScript, which represents the HTML page and allow managing the page dynamically. Each object in JavaScript consists of methods, which fulfills a specific task. There are two methods of the document object, which displays any type of data in the browser. These methods are as follows:
write(): Displays any type of data.
writeln(): Displays any type of data and appends a new line character.
The syntax demonstrates the use of document.write()method, which allows you to display information in the displayed HTML page.
Syntax:
document.write(“<data>” + variables);
where,
data: Specifies strings enclosed in double quotes.
variables: Specify variable names whose value should be displayed on the HTML page.
The syntax demonstrates the use of document.writeln() method, which appends a new line character.
Syntax:
document.writeln(“<data>” + variables);
<!DOCTYPE HTML>
<html>
<head>
<title> JavaScript language </title>
<script>
document.write(“<p> JavaScript:”);
document.writeln(“is a scripting”);
document.write(“and a case-sensitive language.”);
</script>
</head>
<p>
JavaScript: is a scripting and a case-sensitive language.
</p>
</html>
The code uses the writeln() method to display the text after the colon without leaving a space. It finally appends a new line character after the text. Then, the text within the write() method is displayed on the same line after leaving a space.
The same paragraph is displayed in the body of the HTML page. Note that the text in the p element appears on different lines. In HTML, the text on the second line, and a case sensitive language will not be displayed in the new line in the browser even though the ENTER key is pressed while writing the code. Rather, it will be displayed on the same line with a space. The writeln() method also follows this same format.
Using Comments
A Web page designer might code complex script to fulfill a specific task. In JavaScript, a Web page designer specifies comments to provide information about a piece of code in the script. Comments describe the code in simple words so that somebody who reads the code can understand the code. Comments are small piece of text that makes the program more readable. While the script is executed, the browser can identify comments as they are marked with special characters and do not display them.
JavaScript supports two types of comments. These are as follows:
Single-line Comments
Single-line comments begin with two forward slashes (//). You can insert single-line comments as follows:
// This statement declares a variable named num.
var num;
Multi-line Comments
Multi-line comments begin with a forward slash followed by an asterisk (/*) and end with an asterisk followed by a forward slash (*/). You can insert multiple lines of comments as follows:
/* This line of code
declares a variable */
var num;
Escape Sequence Characters
An escape sequence character is a special character that is preceded by a backslash (\). Escape sequence characters are used to display special non-printing characters such as a tab space, a single space, or a backspace. These non-printing characters help in displaying formatted output to the user to maximize readability.
The backslash character specifies that the following character denotes a non-printing character. For example, \t is an escape sequence character that inserts a tab space similar to the Tab key of the keyboard. In JavaScript, the escape sequence characters must always be enclosed in double quotes.
There are multiple escape sequence characters in JavaScript that provides various kind of formatting.
Escape Sequence Non-Printing Character
\b Back space
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\’ Single quote
\” Double quote
\\ Backslash
\aaa Matches a Latin-1 encoding character using octal representation, where aaa are three octal numbers. For example, \251 represents the copyright symbol
\xaa Matches a Latin-1 encoding character using hexadecimal representation, where aa are two hexadecimal numbers. For example, \x61 represents the character ‘a’
\uaaaa Represent the Unicode encoding character, where aaaa are four hexadecimal numbers. For example, the character \ u0020 represents a space
Code Snippet :
<script>
document.write(“You need to have a \u0022credit card\u0022, if you
want to shop on the \’Internet\’.”);
</script>
The code uses a Unicode encoding character namely, \u0022, which represents double quotes. These open and close double quotes will contain the term credit card. Similarly, the word Internet will be placed in single quotes. The single quotes are specified using the backslash character
Built-in Functions
A function is a piece of code that performs some operations on variables to fulfill a specific task. It takes one or more input values, processes them, and returns an output value. JavaScript provides built-in functions that are already defined to fulfill a certain task. Table 12.5 lists the built-in functions.
Function Description Example
alert() Displays a dialog box with some information and OK button alert(“Please fill all the fields of the form”);
Displays a message box with the instruction
confirm() Displays a dialog box with OK and Cancel buttons. It verifies an action, which a user wants to perform confirm(“Are you sure you want to close the page?”);
Displays a message box with the question
parseInt() Converts a string value into a numeric value parseInt(“25 years”);
parseFloat() Converts a string into a number with decimal point parseFloat(“10.33”);
Returns 10.33
eval() Evaluates an expression and returns the evaluated result eval(“2+2”);
Returns 4
isNaN() Checks whether a value is not a number isNan(“Hello”);
Returns true
prompt() Displays a dialog box that accepts an input value through a text box. It also accepts the default value for the text box. prompt(“Enter your name”, “Name”);
Displays the message in the dialog box and Name in the text box.
Code Snippet 6:
<!DOCTYPE HTML>
<html>
<head>
<title> JavaScript language </title>
<script>
var value = “”;
var numone = prompt(“enter first value to perform the
multiplication operation”, value);
var numtwo = prompt(“enter second value to perform the
multiplication operation”, value);
var result = eval(numone * numtwo);
document.write(“The result of multiplying: “ + numone + “
and “ +
numtwo + “ is: “ + result + “.” );
</script>
</head>
</html>
In the code, it takes the first value from the user and stores in the numOne variable. Then, it takes the second value from the user and stores in the numTwo variable. It multiplies the values and stores the output in the result variable and then displays the output on the Web page.
Events
Consider a scenario where you want to design an Employee registration Web form. This form allows the users to fill in the appropriate details and click the submit button. When the user clicks the submit button, the form data is submitted to the server for validation purposes. In this case, when the user clicks the button, an event is generated. The submission of form refers to the action performed on click of the button.
An event occurs when a user interacts with the Web page. Some of the commonly generated events are mouse clicks, key strokes, and so on. The process of handling these events is known as event handling. displays the event .
Event Handling
Event handling is a process of specifying actions to be performed when an event occurs. This is done by using an event handler. An event handler is a scripting code or a function that defines the actions to be performed when the event is triggered.
When an event occurs, an event handler function that is associated with the specific event is invoked. The information about this generated event is updated on the event object. The event object is a built-in object, which can be accessed through the window object.
It specifies the event state, which includes information such as the location of mouse cursor, element on which an event occurred, and state of the keys in a keyboard .
Event Bubbling
Event bubbling is a mechanism that allows you to specify a common event handler for all child elements. This means that the parent element handles all the events generated by the child elements. For example, consider a Web page that consists of a paragraph and a table. The paragraph consists of multiple occurrences of italic text. Now, you want to change the color of each italic text of a paragraph when the user clicks a particular button. Instead of declaring an event handler for each italic text, you can declare it within the P element. This allows you to apply colors for all the italic text within the paragraph. This helps in reducing the development time and efforts since it minimizes the code. displays the event bubbling.
Monday, 4 May 2015
html tutorials session 12
Html session 12 theory:
Life Cycle of an Event
An event’s life starts when the user performs an action to interact with the Web page. It finally ends when the event handler provides a response to the user’s action. The steps involved in the life cycle of an event are as follows:
The user performs an action to raise an event.
The event object is updated to determine the event state.
The event is fired.
The event bubbling occurs as the event bubbles through the elements of the hierarchy.
The event handler is invoked that performs the specified actions.
12.14.4 Keyboard Events
Keyboard events are the events that occur when a key or a combination of keys are pressed or released from a keyboard. These events occur for all keys of a keyboard.
The different keyboard events are as follows:
Onkeydown
Occurs when a key is pressed down.
Onkeyup
Occurs when the key is released.
Onkeypress
Occurs when a key is pressed and released.
Introduction to JavaScript
function numericonly()
{
if(!event.keyCode >=48 && event.keyCode<=57))
event.returnValue=false;
}
function countWords()
{
var message = document.getElementByID(‘txtMessage’).value;
message= message.replace(/\s+/g, ‘ ‘);
var numberOfWords = message.split(‘ ‘).length;
document.getElementById(‘txtTrack’).value = words Remaining:
‘ +
eval(50 - numberOfWords);
if(numberOfWords > 50)
alert(“too many words.’);
}
In the code, the function numericOnly()declares an event handler function, numericOnly(). The event.keyCode checks if the Unicode character of the entered key is greater than 48 and less than 57. This checks that only numeric values are entered. It also declares an event handler function, countWords(). It retrieves the text specified in the txtMessage control. split()function splits the specified string when a space is encountered and returns the length after splitting. It also calculates and displays the number of remaining words to complete the count of 50 words. If the number of words is greater than 50, an alert box is displayed.
Mouse Events
Mouse events occur when the user clicks the mouse button. Table 12.6 lists the mouse events.
<!DOCTYPE HTML>
<html>
<head>
<title> Reservation </title>
<script src=”form.js”>
</script>
</head>
<body>
<h2> Hotel Reservation Form</h2>
<form id=”frmreservation”>
<table>
<tr>
<td> <label for=”txtName”>Name:</label></td>
<td> <input id=”txtName” type=”text” /></td>
</tr>
<tr>
<td> Arrival Date: </td>
<td> <input id=”txtArrival” type=”text” /></td>
</tr>
<tr>
<td> Departure Date: </td>
<td> <input id=”txtDeparture” type=”text” /></td>
</tr>
<tr>
<td> Number of Person: </td>
<td> <input id=”txtPerson” type=”text” maxlength=”3”
size=”3”></td>
</tr>
<tr>
<td> <img id=”imgSubmit” width=”120px” height=”30px”
src=”submit.jpg” alt=”Submit”,
onmousedown=”showImage(this, ‘submitdown.jpg’);”
onmouseup=”showImage(this,
‘submit.jpg’);”,onclick=”frmReservation.submit();”/>
</td>
<td> <img id=”imgSubmit” width=”120px” height=”30px”
src=”reset.jpg” alt=”Reset”,
onmousedown=”showImage(this, ‘resetdown.jpg’);”
onmouseup=”showImage(this,
‘reset.jpg’);”,onclick=”frmReservation.reset();”/>
</td>
</tr>
</table>
</form>
</body>
</html>
It will also display the submit.jpg image when the mouse is released from Submit button. It also submits the form data when the Submit button is clicked. Further it displays the image when Reset button is clicked and it displays the reset.jpg image when the mouse is released from Reset button. It will reset the form data when the Reset button is clicked.
Code Snippet 9 demonstrates the loading of images in a JavaScript file.
Code Snippet 9:
function showImage(object,url)
{
object.src=url;
}
Focus and Selection Events
The focus events determine the activation of various elements that uses the input element. It allows you to set or reset focus for different input elements. The selection events occur when an element or a part of an element within a Web page is selected. Table 12.7 lists the focus and selection events.
onfocus Occurs when an element receives focus
onblur Occurs when an element loses focus
onselectstart Occurs when the selection of an element starts
onselect Occurs when the present selection changes
ondragstart Occurs when the selected element is moved
<!DOCTYPE HTML>
<html>
<head>
<title> Reservation </title>
<script>
function showStyle(field)
{
field.style.backgroundColor = ‘#FFFFCC’;
}
function hideStyle(field)
{
field.style.backgroundColor = ‘#FFFFFF’;
}
function setFontStyle(field)
{
field.style.fontWeight = ‘bold’;
field.style.fontFamily = ‘Arial’;
}
</script>
</head>
<body>
<h2> Feedback Form</h2>
<form id=”frmreservation”>
<table>
<tr>
<td> <label for=”txtName”>Name:</label></td>
<td> <input id=”txtName” type=”text” onfocus=”showStyle(this
);” onblur=”hideStyle(this);” onselect=setFontStyle(
this); />
</td>
</tr>
<tr>
<td> <label for=”txtEmail”>E-mail:</label></td>
<td> <input id=”txtEmail” type=”text” onfocus=”showStyle(this);”
onblur=”hideStyle(this);” onselect=setFontStyle(this); />
</td>
</tr>
<tr>
<td> <label for=”txtComment”>Comment:</label></td>
<td> <textarea id=”txtComment” cols=”15” rows=”3”
onfocus=”showStyle(this);” onblur=”hideStyle(this);”
onselect=setFontStyle(this);> </textarea>
</td>
</tr>
<tr>
<td> <input id=”btnSubmit” type=”button” type=”button”
value=”Submit” /></td>
<td> <input id=”btnReset” type=”reset” /></td>
</tr>
</table>
</form>
</body>
</html>
In the code, a specified style is displayed when the element receives and loses focus. It also displays the specified font style when the element is selected. It also declares an event handler function and specifies the background color for the field. It sets the font style for text to bold and the text should appear in Arial font.
jQuery
jQuery is a short and fast JavaScript library developed by John Resig in 2006 with a wonderful slogan: Write less and do more. It simplified the client side scripting of HTML. jQuery also simplifies HTML files animation, event handling, traversing, and developing AJAX based Web applications. It helps in rapid Web application development. jQuery is designed for simplifying several tasks by writing lesser code. The following are the key features supported by jQuery:
Event Handling: jQuery has a smart way to capture a wide range of events, such as user clicks a link, without making the HTML code complex with event handlers.
Animations: jQuery has many built-in animation effects that the user can use while developing their Web sites.
DOM Manipulation: jQuery easily selects, traverses, and modifies DOM by using the cross-browser open source selector engine named Sizzle.
Cross Browser Support: jQuery has a support for cross-browser and works well with the following browsers:
Internet Explorer 6 and above
Firefox 2.0 and above
Safari 3.0 and above
Chrome
Opera 9.0 and above
Lightweight: jQuery has a lightweight library of 19 KB size.
AJAX Support: jQuery helps you to develop feature-rich and responsive Web sites by using AJAX technologies.
Latest Technology: jQuery supports basic XPath syntax and CSS3 selectors.
Using jQuery Library
There is an easy way to use jQuery library. To work with jQuery perform the following steps:
1-Download the jQuery library from the http://jquery.com/ Web site
2-Place the jquery-1.7.2.min.js file in the current directory of the Web site
The user can include jQuery library in their file.
Code Snippet 11 shows how to use a jQuery library.
<!DOCTYPE HTML>
<html>
<head>
<title>The jQuery Example</title>
// Using jQuery library
<script src=”jquery-1.7.2.min.js”>
// The user can add our JavaScript code here
</script>
Calling jQuery Library Functions
Users can do many tasks while jQuery is reading or manipulating the DOM object. The users can add the events only when the DOM object is ready. If the user wants the event on their page then the user has to call the event in the $(document).ready() function. All the content inside the event will be loaded as soon as the DOM is loaded but before the contents of the page are loaded. The users also register the ready event for the document. Place the jquery-1.7.2.min.js file in the current directory and specify the location of this file in the src attribute.
Code Snippet 12 shows how to call jQuery library function and ready event in DOM.
<!DOCTYPE HTML>
<html>
<head>
<title>The jQuery Example</title>
<script src=” jquery-1.7.2.min.js”>
</script>
<script>
$(document).ready(function() {
$(“div”).click(function() {
alert(“Welcome to the jQuery world!”);
});
});
</script>
</head>
<body>
<div id=”firstdiv”>
Click on the text to view a dialog box.
</div>
</body>
</html>
The code includes the jQuery library and also registers the ready event for the document. The ready event contains the click function that calls the click event.
jQuery Mobile
jQuery mobile is a Web User Interface (UI) development framework that allows the user to build mobile Web applications that works on tablets and smartphones. The jQuery mobile framework provides many facilities that include XML DOM and HTML manipulation and traversing, performing server communication, handling events, image effects, and animation for Web pages. The basic features of jQuery mobile are as follows:
Simplicity
This framework is easy to use and allows developing Web pages by using markup driven with minimum or no JavaScript.
Accessibility
The framework supports Accessible Rich Internet Applications (ARIA) that helps to develop Web pages accessible to visitors with disabilities.
Enhancements and Degradation
The jQuery mobile is influenced by the latest HTML5, JavaScript, and CSS3.
Themes
This framework provides themes that allow the user to provide their own styling.
Smaller Size
The size for jQuery mobile framework is smaller for CSS it is 6KB and for JavaScript library it is 12KB.
For executing the jQuery mobile, you have to download the Opera Mobile Emulator from the http://www.opera.com/developer/tools/mobile/ Web site. Download the emulator and install it on your machine and then write the code in the Coffee cup editor. Code Snippet 13 shows an example of a jQuery mobile.
Code Snippet 13:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel=”stylesheet” href=”jquery.mobile-1.0a3.min.css” />
<script src=”jquery-1.5.min.js”></script>
<script src=”jquery.mobile-1.0a3.min.js”></script>
</head>
<body>
<div data-role=”page”>
<div data-role=”header”>
<h1>Car Rental</h1>
</div>
<div data-role=”content”>
<p>Choose from the listed car models</p>
<ul data-role=”listview” data-inset=”true”>
<li><a href=”#”>Ford</a></li>
<li><a href=”#”>Ferrari</a></li>
<li><a href=”#”>BMW</a></li>
<li><a href=”#”>Toyota</a></li>
<li><a href=”#”>Mercedes-Benz</a></li>
</ul>
</div>
<div data-role=”footer”>
<h4>© DriveCars 2012.</h4>
</div>
</div>
</body>
</html>
The jQuery mobile application should have the following three files:
CSS file
jQuery library
jQuery Mobile library
In the code, three files are included the CSS (jquery.mobile-1.0a3.min. css), jQuery library (jquery-1.5.min.js), and the jQuery mobile library (jquery.mobile-1.0a3.min.js). A user can also download the jQuery libraries from http://code.jquery.com/ Web site.
The jQuery Mobile takes HTML tags and renders them on mobile devices. To work with this, HTML has to make use of data attributes. jQuery use these attributes as indicators for rendering it on the Web pages. jQuery also looks for div using a particular data-role values such as page, content, header, and footer are used in this code. There are multiple div blocks added to the code for page, content, header, and footer. Similarly, to display the different car models a data-role listview is added to enhance the look and feel of the mobile Web page.
A user need to install the Opera Mobile Emulator from the Opera Web site.
After installing the Opera Mobile Emulator, perform the following steps to apply settings to the emulator:
Select All Programs Opera Mobile Emulator Opera Mobile Emulator.
The Opera Mobile Emulator dialog box will be displayed.
In the Profile tab, select the Samsung Galaxy Tab.
In the Resolution drop-down, select the WVGA Portrait(480x800).
Click Update.
Click Launch. The Samsung Galaxy tab is displayed.
For executing the jQuery mobile code given in Code Snippet 12 in the CoffeeCup editor, perform the following steps:
Add the Opera Mobile Emulator in the CoffeeCup editor by clicking Tools Additional Browsers Test with Additional Browser 1 and give the location of the Opera Mobile Emulator installed on your system. After adding the emulator, you can see the emulator added to the additional browsers list.
Open the jQuery file in the CoffeeCup editor and save.
Click Tools Additional Browser Test with Additional Browser 1.
Opera Mobile Emulator.
Life Cycle of an Event
An event’s life starts when the user performs an action to interact with the Web page. It finally ends when the event handler provides a response to the user’s action. The steps involved in the life cycle of an event are as follows:
The user performs an action to raise an event.
The event object is updated to determine the event state.
The event is fired.
The event bubbling occurs as the event bubbles through the elements of the hierarchy.
The event handler is invoked that performs the specified actions.
12.14.4 Keyboard Events
Keyboard events are the events that occur when a key or a combination of keys are pressed or released from a keyboard. These events occur for all keys of a keyboard.
The different keyboard events are as follows:
Onkeydown
Occurs when a key is pressed down.
Onkeyup
Occurs when the key is released.
Onkeypress
Occurs when a key is pressed and released.
Introduction to JavaScript
function numericonly()
{
if(!event.keyCode >=48 && event.keyCode<=57))
event.returnValue=false;
}
function countWords()
{
var message = document.getElementByID(‘txtMessage’).value;
message= message.replace(/\s+/g, ‘ ‘);
var numberOfWords = message.split(‘ ‘).length;
document.getElementById(‘txtTrack’).value = words Remaining:
‘ +
eval(50 - numberOfWords);
if(numberOfWords > 50)
alert(“too many words.’);
}
In the code, the function numericOnly()declares an event handler function, numericOnly(). The event.keyCode checks if the Unicode character of the entered key is greater than 48 and less than 57. This checks that only numeric values are entered. It also declares an event handler function, countWords(). It retrieves the text specified in the txtMessage control. split()function splits the specified string when a space is encountered and returns the length after splitting. It also calculates and displays the number of remaining words to complete the count of 50 words. If the number of words is greater than 50, an alert box is displayed.
Mouse Events
Mouse events occur when the user clicks the mouse button. Table 12.6 lists the mouse events.
<!DOCTYPE HTML>
<html>
<head>
<title> Reservation </title>
<script src=”form.js”>
</script>
</head>
<body>
<h2> Hotel Reservation Form</h2>
<form id=”frmreservation”>
<table>
<tr>
<td> <label for=”txtName”>Name:</label></td>
<td> <input id=”txtName” type=”text” /></td>
</tr>
<tr>
<td> Arrival Date: </td>
<td> <input id=”txtArrival” type=”text” /></td>
</tr>
<tr>
<td> Departure Date: </td>
<td> <input id=”txtDeparture” type=”text” /></td>
</tr>
<tr>
<td> Number of Person: </td>
<td> <input id=”txtPerson” type=”text” maxlength=”3”
size=”3”></td>
</tr>
<tr>
<td> <img id=”imgSubmit” width=”120px” height=”30px”
src=”submit.jpg” alt=”Submit”,
onmousedown=”showImage(this, ‘submitdown.jpg’);”
onmouseup=”showImage(this,
‘submit.jpg’);”,onclick=”frmReservation.submit();”/>
</td>
<td> <img id=”imgSubmit” width=”120px” height=”30px”
src=”reset.jpg” alt=”Reset”,
onmousedown=”showImage(this, ‘resetdown.jpg’);”
onmouseup=”showImage(this,
‘reset.jpg’);”,onclick=”frmReservation.reset();”/>
</td>
</tr>
</table>
</form>
</body>
</html>
It will also display the submit.jpg image when the mouse is released from Submit button. It also submits the form data when the Submit button is clicked. Further it displays the image when Reset button is clicked and it displays the reset.jpg image when the mouse is released from Reset button. It will reset the form data when the Reset button is clicked.
Code Snippet 9 demonstrates the loading of images in a JavaScript file.
Code Snippet 9:
function showImage(object,url)
{
object.src=url;
}
Focus and Selection Events
The focus events determine the activation of various elements that uses the input element. It allows you to set or reset focus for different input elements. The selection events occur when an element or a part of an element within a Web page is selected. Table 12.7 lists the focus and selection events.
onfocus Occurs when an element receives focus
onblur Occurs when an element loses focus
onselectstart Occurs when the selection of an element starts
onselect Occurs when the present selection changes
ondragstart Occurs when the selected element is moved
<!DOCTYPE HTML>
<html>
<head>
<title> Reservation </title>
<script>
function showStyle(field)
{
field.style.backgroundColor = ‘#FFFFCC’;
}
function hideStyle(field)
{
field.style.backgroundColor = ‘#FFFFFF’;
}
function setFontStyle(field)
{
field.style.fontWeight = ‘bold’;
field.style.fontFamily = ‘Arial’;
}
</script>
</head>
<body>
<h2> Feedback Form</h2>
<form id=”frmreservation”>
<table>
<tr>
<td> <label for=”txtName”>Name:</label></td>
<td> <input id=”txtName” type=”text” onfocus=”showStyle(this
);” onblur=”hideStyle(this);” onselect=setFontStyle(
this); />
</td>
</tr>
<tr>
<td> <label for=”txtEmail”>E-mail:</label></td>
<td> <input id=”txtEmail” type=”text” onfocus=”showStyle(this);”
onblur=”hideStyle(this);” onselect=setFontStyle(this); />
</td>
</tr>
<tr>
<td> <label for=”txtComment”>Comment:</label></td>
<td> <textarea id=”txtComment” cols=”15” rows=”3”
onfocus=”showStyle(this);” onblur=”hideStyle(this);”
onselect=setFontStyle(this);> </textarea>
</td>
</tr>
<tr>
<td> <input id=”btnSubmit” type=”button” type=”button”
value=”Submit” /></td>
<td> <input id=”btnReset” type=”reset” /></td>
</tr>
</table>
</form>
</body>
</html>
In the code, a specified style is displayed when the element receives and loses focus. It also displays the specified font style when the element is selected. It also declares an event handler function and specifies the background color for the field. It sets the font style for text to bold and the text should appear in Arial font.
jQuery
jQuery is a short and fast JavaScript library developed by John Resig in 2006 with a wonderful slogan: Write less and do more. It simplified the client side scripting of HTML. jQuery also simplifies HTML files animation, event handling, traversing, and developing AJAX based Web applications. It helps in rapid Web application development. jQuery is designed for simplifying several tasks by writing lesser code. The following are the key features supported by jQuery:
Event Handling: jQuery has a smart way to capture a wide range of events, such as user clicks a link, without making the HTML code complex with event handlers.
Animations: jQuery has many built-in animation effects that the user can use while developing their Web sites.
DOM Manipulation: jQuery easily selects, traverses, and modifies DOM by using the cross-browser open source selector engine named Sizzle.
Cross Browser Support: jQuery has a support for cross-browser and works well with the following browsers:
Internet Explorer 6 and above
Firefox 2.0 and above
Safari 3.0 and above
Chrome
Opera 9.0 and above
Lightweight: jQuery has a lightweight library of 19 KB size.
AJAX Support: jQuery helps you to develop feature-rich and responsive Web sites by using AJAX technologies.
Latest Technology: jQuery supports basic XPath syntax and CSS3 selectors.
Using jQuery Library
There is an easy way to use jQuery library. To work with jQuery perform the following steps:
1-Download the jQuery library from the http://jquery.com/ Web site
2-Place the jquery-1.7.2.min.js file in the current directory of the Web site
The user can include jQuery library in their file.
Code Snippet 11 shows how to use a jQuery library.
<!DOCTYPE HTML>
<html>
<head>
<title>The jQuery Example</title>
// Using jQuery library
<script src=”jquery-1.7.2.min.js”>
// The user can add our JavaScript code here
</script>
Calling jQuery Library Functions
Users can do many tasks while jQuery is reading or manipulating the DOM object. The users can add the events only when the DOM object is ready. If the user wants the event on their page then the user has to call the event in the $(document).ready() function. All the content inside the event will be loaded as soon as the DOM is loaded but before the contents of the page are loaded. The users also register the ready event for the document. Place the jquery-1.7.2.min.js file in the current directory and specify the location of this file in the src attribute.
Code Snippet 12 shows how to call jQuery library function and ready event in DOM.
<!DOCTYPE HTML>
<html>
<head>
<title>The jQuery Example</title>
<script src=” jquery-1.7.2.min.js”>
</script>
<script>
$(document).ready(function() {
$(“div”).click(function() {
alert(“Welcome to the jQuery world!”);
});
});
</script>
</head>
<body>
<div id=”firstdiv”>
Click on the text to view a dialog box.
</div>
</body>
</html>
The code includes the jQuery library and also registers the ready event for the document. The ready event contains the click function that calls the click event.
jQuery Mobile
jQuery mobile is a Web User Interface (UI) development framework that allows the user to build mobile Web applications that works on tablets and smartphones. The jQuery mobile framework provides many facilities that include XML DOM and HTML manipulation and traversing, performing server communication, handling events, image effects, and animation for Web pages. The basic features of jQuery mobile are as follows:
Simplicity
This framework is easy to use and allows developing Web pages by using markup driven with minimum or no JavaScript.
Accessibility
The framework supports Accessible Rich Internet Applications (ARIA) that helps to develop Web pages accessible to visitors with disabilities.
Enhancements and Degradation
The jQuery mobile is influenced by the latest HTML5, JavaScript, and CSS3.
Themes
This framework provides themes that allow the user to provide their own styling.
Smaller Size
The size for jQuery mobile framework is smaller for CSS it is 6KB and for JavaScript library it is 12KB.
For executing the jQuery mobile, you have to download the Opera Mobile Emulator from the http://www.opera.com/developer/tools/mobile/ Web site. Download the emulator and install it on your machine and then write the code in the Coffee cup editor. Code Snippet 13 shows an example of a jQuery mobile.
Code Snippet 13:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel=”stylesheet” href=”jquery.mobile-1.0a3.min.css” />
<script src=”jquery-1.5.min.js”></script>
<script src=”jquery.mobile-1.0a3.min.js”></script>
</head>
<body>
<div data-role=”page”>
<div data-role=”header”>
<h1>Car Rental</h1>
</div>
<div data-role=”content”>
<p>Choose from the listed car models</p>
<ul data-role=”listview” data-inset=”true”>
<li><a href=”#”>Ford</a></li>
<li><a href=”#”>Ferrari</a></li>
<li><a href=”#”>BMW</a></li>
<li><a href=”#”>Toyota</a></li>
<li><a href=”#”>Mercedes-Benz</a></li>
</ul>
</div>
<div data-role=”footer”>
<h4>© DriveCars 2012.</h4>
</div>
</div>
</body>
</html>
The jQuery mobile application should have the following three files:
CSS file
jQuery library
jQuery Mobile library
In the code, three files are included the CSS (jquery.mobile-1.0a3.min. css), jQuery library (jquery-1.5.min.js), and the jQuery mobile library (jquery.mobile-1.0a3.min.js). A user can also download the jQuery libraries from http://code.jquery.com/ Web site.
The jQuery Mobile takes HTML tags and renders them on mobile devices. To work with this, HTML has to make use of data attributes. jQuery use these attributes as indicators for rendering it on the Web pages. jQuery also looks for div using a particular data-role values such as page, content, header, and footer are used in this code. There are multiple div blocks added to the code for page, content, header, and footer. Similarly, to display the different car models a data-role listview is added to enhance the look and feel of the mobile Web page.
A user need to install the Opera Mobile Emulator from the Opera Web site.
After installing the Opera Mobile Emulator, perform the following steps to apply settings to the emulator:
Select All Programs Opera Mobile Emulator Opera Mobile Emulator.
The Opera Mobile Emulator dialog box will be displayed.
In the Profile tab, select the Samsung Galaxy Tab.
In the Resolution drop-down, select the WVGA Portrait(480x800).
Click Update.
Click Launch. The Samsung Galaxy tab is displayed.
For executing the jQuery mobile code given in Code Snippet 12 in the CoffeeCup editor, perform the following steps:
Add the Opera Mobile Emulator in the CoffeeCup editor by clicking Tools Additional Browsers Test with Additional Browser 1 and give the location of the Opera Mobile Emulator installed on your system. After adding the emulator, you can see the emulator added to the additional browsers list.
Open the jQuery file in the CoffeeCup editor and save.
Click Tools Additional Browser Test with Additional Browser 1.
Opera Mobile Emulator.
Subscribe to:
Posts (Atom)