Html session 11 theory :
Introduction :
Traditionally, Web browsers were capable of handling only graphics and text. Suppose, if a user had to play some video, then, a distinct program, plug-in, or an ActiveX control had to be installed. Earlier, Web designers and Web developers used to set up Web pages to play audio and video on the Web using Adobe Flash player.
11.2 Multimedia in HTML5
Multimedia is a combination of various elements such as video, graphics, sound, and text. A common way of inserting a multimedia content on Web pages is by embedding a video or audio file in the Web page.
Consider the earlier situations where a Web site developer did not have the facility of including videos or audios directly on their Web site until and unless the browser had the required plug-in installed. These days, Web site developers want their visitors to not only download, but also, view movies online on their Web site. This is possible by adding the new features of HTML5 which can provide this facility.
HTML5 has made lives easier by introducing <audio> and <video> elements. In other words, HTML5 has provided the developers with the features to embed media on the Web pages in a standard manner. Thus, the user need not depend on Flash to access the audio and video files.
11.3 Supported Media Types in Audio and Video
There are various video and audio codecs which are used for handling of video and audio files. The codec is a device or a program used for encoding and decoding digital data stream. These different codecs have different level of compression quality.
For storing and transmitting coded video and audio together, a container format is used. There are a number of container formats which includes Ogg (.ogv), the Audio Video Interleave (.avi), Flash Video (.flv), and many others. WebM is a new open source video container format supported by Google. Different browsers support different container format.
Table 11.1 lists the common audio and video formats.
Container Video Codec Audio Codec
Mp4 H.264 AAC
Ogg Theora Vorbis
WebM VP8 Vorbis
Audio Formats
There are the three supported file formats for the <audio> element in HTML5. Table 11.2 lists the audio file formats supported by the Web browsers.
Browsers Support MP3 Wav Ogg
Opera 10.6 No Yes Yes
Apple Safari 5 Yes Yes No
Google Chrome 6 Yes Yes Yes
FireFox 4.0 No Yes Yes
Internet Explorer 9 Yes No No
Video Formats
There are the three supported file formats for the <video> element in HTML5. Table 11.3 lists the video file formats supported by the Web browsers.
Browsers Support MP4 WebM Ogg
Opera 10.6 No Yes Yes
Apple Safari 5 Yes No No
Google Chrome 6 Yes Yes Yes
FireFox 4.0 No Yes Yes
Internet Explorer 9 Yes No No
Audio Elements in HTML5
The <audio> element will help the developer to embed music on the Web site and allow the user to listen to music. The <audio> element is one of the best features in HTML5. This feature allows the user to enable a native audio file within the Web browser. The <audio> tag specifies the audio file to be used in the HTML document. The src attribute is used to link to the audio file.
Code Snippet 1 displays the embedding of an audio file in the Web page using the <audio> tag. The music is played in the background when the page is loaded on the browser.
Code Snippet :
<!DOCTYPE html>
<html>
<head>
<title>audio element</title>
</head>
<body>
<audio src=”d:\sourcecodes\audio.mp3”
controls autoplay loop>
html5 audio not supported
</audio>
</body>
</html>
The src attribute is mandatory, the <audio> tag includes several other options .
The users can also use the <source> tag to specify the media along with the media type and other attributes. An audio element can contain multiple source elements and the browser will identify the first supported format.
Audio Tag Attributes
HTML tags normally consist of more than one attribute. Attributes provide additional information to the browser about the tag. HTML5 has a number of attributes for controlling the look and feel of various functionalities. According to HTML5 specifications, the <audio> element has the following attributes. Table 11.4 lists the <audio> tag attributes.
Audio Attributes Description
autoplay This attribute identifies whether to start the audio or not once the object is loaded. The attribute accepts a boolean value which when specified will automatically start playing the audio as soon as possible without stopping
autobuffer This attribute starts the buffering automatically
controls This attribute identifies the audio playback controls that should be displayed such as resume, pause, play, and volume buttons
loop This attribute identifies whether to replay the audio once it has stopped
preload This attribute identifies whether the audio has to be loaded when the page loads and is ready to execute. This preload attribute is ignored if autoplay exists
src This attribute specifies the location or the URL of the audio file that has to be embedded
Creating Audio Files
Suppose, if the user plays the audio in older browsers then the <embed> tag will be used. The <embed> tag has two attributes, src and autostart. The src attribute is used to specify the source of the audio and the autostart attribute controls the audio and determines whether the audio should play as soon as the page loads.
Code Snippet 2:
<!DOCTYPE HTML>
<html>
<body>
<audio autoplay loop>
<source src=”sampaudio.mp3”>
<source src=”sampaudio.ogg”>
<embed src=”sampaudio.mp3”>
</audio>
</body>
</html>
The <audio> element in HTML5 supports multiple formats. The content included within the <embed> tag is automatically played by default. Suppose, if the user does not want to play the audio file automatically then he/she can set the value of the autostart attribute to ”false”.
Code Snippet 3 demonstrates the use of the autostart attribute.
Code Snippet :
<embed src=”mpaudio.mp3” autostart=”false” >
The <embed> tag also supports another attribute named loop. The loop attribute determines whether the audio clip will be replayed continuously or not. If the value of the loop attribute is set to true or infinite then the music will be played continuously. If the loop attribute is not specified then it is same as setting the value to false.
Code Snippet :
<!DOCTYPE HTML>
<html>
<body>
<audio controls autoplay>
<source src=”/html5/sampaudio.ogg” type=”audio/ogg” />
<source src=”/html5/sampaudio.wav” type=”audio/wav” />
Your browser does not support the <audio> element.
</audio>
</body>
</html>
This code snippet shows the ogg and wav formats supported by the <audio> tag. While adding the <audio> element in the code, the user can specify error messages to check if the browser is supporting the <audio> tag or not.
Monday, 11 May 2015
Sunday, 10 May 2015
Html session 11
Html Session 11 Theory :
Video Elements in HTML5
The <video> element is a new feature added in HTML5. The user can use the <video> element for embedding the video content on the Web page. The easiest way to specify the video is by using the src attribute which give the URL of the video file to be used. Suppose, if the browser does not support the <video> element then the content between the start tag and end tag is displayed on the browser.
Code Snippet :
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<video src=”D:\Source codes\movie.mp4”>
Your browser does not support the video.
</video>
</body>
</html>
In the code, the src attribute is used for specifying the location of the mp4 video file format used by the <video> tag. While adding the <video> element in the code, the user can specify messages between the <video> and </video> tag to check if the browser is supporting the <video> tag or not.
displays the <video> element.
Video Tag Attributes
The HTML5 specification provides a list of attributes that can be used with the <video> element. Table 11.5 lists the <video> tag attributes.
Video Attributes Description
autoplay Specifies that the browser will start playing the video as soon as it is ready
muted Allows to mute the video initially, if this attribute is existing
controls Allows displaying the controls of the video, if the attribute exists
loop Specifies that the browser should repeat playing the existing video once more if the loop attribute exists and accepts a boolean value
preload Specifies whether the video should be loaded or not when the page is loaded
src Specifies the location of the video file to be embedded
Preloading the Video
The <video> element comprises a preload attribute that allows the browser to download or buffer the video while the Web page containing the video is being downloaded. If the video is preloaded, then it decreases the initial delay once the user has started the playback. The preload attribute has the following values:
None
This attribute allows the browser to load only the page. The video will not be downloaded while the page is being loaded.
Metadata
This attribute allows the browser to load the metadata when the page is being loaded.
Auto
This is the default behavior as it allows the browser to download the video when the page is loaded. The browser can avoid the request.
Code Snippet :
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<video width=”160” height=”140” src=”D:\Source Codes\movie. mp4”
controls preload=”none” muted>
Your browser does not support the video.
</video>
<video width=”160” height=”140” src=”D:\ Source Codes\movie. mp4”
controls preload=”metadata” muted>
Your browser does not support the video.
</video>
</body>
</html>
Setting the Video Size
The user can specify the size of the video with the height and width attribute of the <video> element. Suppose, if these attributes are not provided then the browser sets the video with the key dimensions of the video. This will result in changing the page layout as the Web page is adjusted to accommodate the video.
<!DOCTYPE HTML>
<html>
<head>
</head>
<title> Video Size</title>
<style>
video{
background-color: black;
border: medium double black;
}
</style>
<body>
<video src=”D:\Source Codes\movie.mp4”
controls preload=”auto” width=”360” height=”340”>
Your browser does not support the video.
</video>
</body>
</html>
In the code, the style attribute is used to specify the background-color and border style of the video. The code also specifies the preload, height, and width attributes for the <video> element.
Converting the Video Files
The <video> element used in HTML5 is a great feature but how will the user get the video files in a correct format. There are many problems with browser vendors for supporting the various video formats on the Web sites. The following are some of the video formats supported by the significant browsers:
Ogg/Theora
This is an open source, royalty-free, and patent-free format available. This format is supported by browsers such as Opera, Chrome, and Firefox.
WebM
This is a royalty-free and patent-free format supported by Google. This format is supported by browsers such as Opera, Chrome, and Firefox. Free WebM Encoder 1.2 is a simple utility that allows you to convert video files to the WebM format.
H.264/MP4
H.264 or MP4 formats are supported on iPhone and Google Android devices.
There is a simple way to encode H.264 is by using the Handbrake. Handbrake is an open-source, GPL-license application and is accessible by using Mac OS X, Windows, and Linux. Handbrake has two versions, command-line and graphical versions.
This format is available for free till 2015. This format is supported by browsers such as Internet Explorer, Chrome, and Safari.
Micro Video Controller
This converter creates all files that the user requires for HTML5 <video> element that works on the cross browser.
11.6 Accessibility of Audio and Video Elements
Enterprises across the world are employing people with varied skills and abilities. They may even include people with limited abilities or disabilities such as people with visual, cognitive, or mobility impairments. Accessibility is the level of ease with which computers can be used and be available to a wide range of users, including people with disabilities.
Applications can be accessed through various sources. If the application considers the requirements of the target audience, then it will be appreciated and used by number of users.
There are various types of users who will view the application containing the media content. Therefore, while developing an application a lot of assumptions are to be considered and some of them are as follows:
Users can check the content on laptop, mobile, tablet, or desktop
Users can listen to the audio by using headphones or speakers
Users can understand the language in which the media was delivered
Users can successfully play and download the media
These assumptions meet the requirements of a vast majority of users accessing the application. However, not all users will fall in this category. Therefore, another set of assumptions are to be considered for these users and they are as follows:
Users who have hearing and visual impairment and thus, cannot listen to the audio or view the video
Users who are not familiar with the language that the content is delivered
Users who use keyboards and screen readers to access the content on Web
Users who cannot view or hear the media content because of their working environment or due to device restrictions
HTML5 provides powerful features to make applications accessible to such users.
WebVTT (Web Video text Tracks) is a file format used to mark up the external text tracks. This format allows the user to give a textual description of the content in the video. This description is then used by different accessibility devices to define the content to those users who cannot see it.
11.6.1 The Track Element
The track element provides an easy, standard way to add captions, subtitles, chapters, and screen reader descriptions to the <audio> and <video> elements.
Track elements are also used for other types of timed metadata. The source data for this track element is in a form of a text file that is made up of a list of timed cues. A cue is a pointer at an accurate time point in the length of a video. These cues contain data in formats such as Comma-Separated Values (CSV) or JavaScript Object Notation (JSON).
The track element is not supported in many major browsers. This track element is now available in IE 10 and Chrome 18+.
Container Description
src Contains the URL of the text track data
srclang Contains the language of the text track data
kind Contains the type of content the track definition is used for
default Indicates that this will be the default track if the user does not specifies the value
label Specifies the title to be displayed for the user
<video controls>
<source src=”myvideo.mp4” type=”video/mp4”>
<source src=”myvideo.webm” type=”video/webm”>
<track src=”eng.vtt”
label=”English p subtitles” kind=”subtitles”
srclang=”en” >
</video>
This code specifies the src, label, and srclang attributes in the track element. Here, the srclang is set to en that is English language.
Code Snippet 9 demonstrates a track element used in combination with <video> element providing subtitles in another language
<video controls>
<source src=”myvideo.mp4” type=”video/mp4”>
<source src=”myvideo.webm” type=”video/webm”>
<track src=”de.vtt” srclang=”de” label=”German p subtitles”
kind=”subtitles”>
</video>
This code specifies the src, label, and srclang attributes in the track element. Here, the srclang is set to de which represents French language.
Accessibility for Audio and Video Element
There are some accessibility supports for <audio> and <video> elements. These are as follows:
Audio Support
The following are the accessibility support for <audio> elements:
Firefox - This browser exposes controls with accessibility APIs, however individual controls do not interact with keyboard. The access to keyboard is provided by the Firefox specific shortcuts.
Opera - This browser has only keyboard support.
IE 9 - This browser expose controls with accessibility APIs, however individual controls do not interact with keyboard.
Video Support
The following are the accessibility support for <video> elements:
Firefox - This browser cannot interact with individual controls.
Opera - This browser has only keyboard support.
IE 9 - This browser does not allow individual controls to interact with keyboard
Non-Supporting Browsers
There are many browsers that do not support HTML5 elements. Browsers such as Firefox, IE9, Chrome, Opera, and Safari support the <audio> and the <video> elements. Google chrome 17 and lower version has no support for <audio> elements. Similarly, Safari browser does not support <audio> element in HTML5. Internet Explorer 8 and earlier versions do not support the <audio> and the <video> elements .
Video Elements in HTML5
The <video> element is a new feature added in HTML5. The user can use the <video> element for embedding the video content on the Web page. The easiest way to specify the video is by using the src attribute which give the URL of the video file to be used. Suppose, if the browser does not support the <video> element then the content between the start tag and end tag is displayed on the browser.
Code Snippet :
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<video src=”D:\Source codes\movie.mp4”>
Your browser does not support the video.
</video>
</body>
</html>
In the code, the src attribute is used for specifying the location of the mp4 video file format used by the <video> tag. While adding the <video> element in the code, the user can specify messages between the <video> and </video> tag to check if the browser is supporting the <video> tag or not.
displays the <video> element.
Video Tag Attributes
The HTML5 specification provides a list of attributes that can be used with the <video> element. Table 11.5 lists the <video> tag attributes.
Video Attributes Description
autoplay Specifies that the browser will start playing the video as soon as it is ready
muted Allows to mute the video initially, if this attribute is existing
controls Allows displaying the controls of the video, if the attribute exists
loop Specifies that the browser should repeat playing the existing video once more if the loop attribute exists and accepts a boolean value
preload Specifies whether the video should be loaded or not when the page is loaded
src Specifies the location of the video file to be embedded
Preloading the Video
The <video> element comprises a preload attribute that allows the browser to download or buffer the video while the Web page containing the video is being downloaded. If the video is preloaded, then it decreases the initial delay once the user has started the playback. The preload attribute has the following values:
None
This attribute allows the browser to load only the page. The video will not be downloaded while the page is being loaded.
Metadata
This attribute allows the browser to load the metadata when the page is being loaded.
Auto
This is the default behavior as it allows the browser to download the video when the page is loaded. The browser can avoid the request.
Code Snippet :
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<video width=”160” height=”140” src=”D:\Source Codes\movie. mp4”
controls preload=”none” muted>
Your browser does not support the video.
</video>
<video width=”160” height=”140” src=”D:\ Source Codes\movie. mp4”
controls preload=”metadata” muted>
Your browser does not support the video.
</video>
</body>
</html>
Setting the Video Size
The user can specify the size of the video with the height and width attribute of the <video> element. Suppose, if these attributes are not provided then the browser sets the video with the key dimensions of the video. This will result in changing the page layout as the Web page is adjusted to accommodate the video.
<!DOCTYPE HTML>
<html>
<head>
</head>
<title> Video Size</title>
<style>
video{
background-color: black;
border: medium double black;
}
</style>
<body>
<video src=”D:\Source Codes\movie.mp4”
controls preload=”auto” width=”360” height=”340”>
Your browser does not support the video.
</video>
</body>
</html>
In the code, the style attribute is used to specify the background-color and border style of the video. The code also specifies the preload, height, and width attributes for the <video> element.
Converting the Video Files
The <video> element used in HTML5 is a great feature but how will the user get the video files in a correct format. There are many problems with browser vendors for supporting the various video formats on the Web sites. The following are some of the video formats supported by the significant browsers:
Ogg/Theora
This is an open source, royalty-free, and patent-free format available. This format is supported by browsers such as Opera, Chrome, and Firefox.
WebM
This is a royalty-free and patent-free format supported by Google. This format is supported by browsers such as Opera, Chrome, and Firefox. Free WebM Encoder 1.2 is a simple utility that allows you to convert video files to the WebM format.
H.264/MP4
H.264 or MP4 formats are supported on iPhone and Google Android devices.
There is a simple way to encode H.264 is by using the Handbrake. Handbrake is an open-source, GPL-license application and is accessible by using Mac OS X, Windows, and Linux. Handbrake has two versions, command-line and graphical versions.
This format is available for free till 2015. This format is supported by browsers such as Internet Explorer, Chrome, and Safari.
Micro Video Controller
This converter creates all files that the user requires for HTML5 <video> element that works on the cross browser.
11.6 Accessibility of Audio and Video Elements
Enterprises across the world are employing people with varied skills and abilities. They may even include people with limited abilities or disabilities such as people with visual, cognitive, or mobility impairments. Accessibility is the level of ease with which computers can be used and be available to a wide range of users, including people with disabilities.
Applications can be accessed through various sources. If the application considers the requirements of the target audience, then it will be appreciated and used by number of users.
There are various types of users who will view the application containing the media content. Therefore, while developing an application a lot of assumptions are to be considered and some of them are as follows:
Users can check the content on laptop, mobile, tablet, or desktop
Users can listen to the audio by using headphones or speakers
Users can understand the language in which the media was delivered
Users can successfully play and download the media
These assumptions meet the requirements of a vast majority of users accessing the application. However, not all users will fall in this category. Therefore, another set of assumptions are to be considered for these users and they are as follows:
Users who have hearing and visual impairment and thus, cannot listen to the audio or view the video
Users who are not familiar with the language that the content is delivered
Users who use keyboards and screen readers to access the content on Web
Users who cannot view or hear the media content because of their working environment or due to device restrictions
HTML5 provides powerful features to make applications accessible to such users.
WebVTT (Web Video text Tracks) is a file format used to mark up the external text tracks. This format allows the user to give a textual description of the content in the video. This description is then used by different accessibility devices to define the content to those users who cannot see it.
11.6.1 The Track Element
The track element provides an easy, standard way to add captions, subtitles, chapters, and screen reader descriptions to the <audio> and <video> elements.
Track elements are also used for other types of timed metadata. The source data for this track element is in a form of a text file that is made up of a list of timed cues. A cue is a pointer at an accurate time point in the length of a video. These cues contain data in formats such as Comma-Separated Values (CSV) or JavaScript Object Notation (JSON).
The track element is not supported in many major browsers. This track element is now available in IE 10 and Chrome 18+.
Container Description
src Contains the URL of the text track data
srclang Contains the language of the text track data
kind Contains the type of content the track definition is used for
default Indicates that this will be the default track if the user does not specifies the value
label Specifies the title to be displayed for the user
<video controls>
<source src=”myvideo.mp4” type=”video/mp4”>
<source src=”myvideo.webm” type=”video/webm”>
<track src=”eng.vtt”
label=”English p subtitles” kind=”subtitles”
srclang=”en” >
</video>
This code specifies the src, label, and srclang attributes in the track element. Here, the srclang is set to en that is English language.
Code Snippet 9 demonstrates a track element used in combination with <video> element providing subtitles in another language
<video controls>
<source src=”myvideo.mp4” type=”video/mp4”>
<source src=”myvideo.webm” type=”video/webm”>
<track src=”de.vtt” srclang=”de” label=”German p subtitles”
kind=”subtitles”>
</video>
This code specifies the src, label, and srclang attributes in the track element. Here, the srclang is set to de which represents French language.
Accessibility for Audio and Video Element
There are some accessibility supports for <audio> and <video> elements. These are as follows:
Audio Support
The following are the accessibility support for <audio> elements:
Firefox - This browser exposes controls with accessibility APIs, however individual controls do not interact with keyboard. The access to keyboard is provided by the Firefox specific shortcuts.
Opera - This browser has only keyboard support.
IE 9 - This browser expose controls with accessibility APIs, however individual controls do not interact with keyboard.
Video Support
The following are the accessibility support for <video> elements:
Firefox - This browser cannot interact with individual controls.
Opera - This browser has only keyboard support.
IE 9 - This browser does not allow individual controls to interact with keyboard
Non-Supporting Browsers
There are many browsers that do not support HTML5 elements. Browsers such as Firefox, IE9, Chrome, Opera, and Safari support the <audio> and the <video> elements. Google chrome 17 and lower version has no support for <audio> elements. Similarly, Safari browser does not support <audio> element in HTML5. Internet Explorer 8 and earlier versions do not support the <audio> and the <video> elements .
Wednesday, 6 May 2015
Html session 12
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.
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.
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.
Sunday, 3 May 2015
html session 13
Html tutorial theory :
if-else if statement:
The if-else if statements allow you to check multiple conditions and specify a different block to be executed for each condition. The flow of these statements begins with the if statement followed by multiple else if statements and finally by an optional else block. The entry point of execution in these statements begins with the if statement. If the condition in the if statement is false, the condition in the immediate else if statement is evaluated.
The if-else if statements are also referred to as the if-else if ladder.
The syntax to use the if-else if statements are as follows:
Syntax:
if (condition)
{
// one or more statements;
}
else if (condition)
{
// one or more statements;
}
else
{
// one or more statements;
}
Code Snippet 15 displays the grades according to the percentage value entered by the user using the if-else if statements.
<script>
var percentage = prompt(‘Enter percentage:’,0);
if (percentage >= 60)
{
alert (‘You have obtained the A grade.’);
}
else if (percentage >= 35 && percentage < 60)
{
alert (‘You have obtained the B class.’);
}
else
{
alert (‘You have failed’);
}
</script>
The code accepts the percentage value from the user and stores it in the percentage variable. The if statement checks whether the value of the percentage variable is greater than or equal to 60. If this is true, the user has obtained the A grade. If the condition is false, the execution control is passed to the else if block. Here, the value of the percentage variable is checked as to whether it is greater than or equal to 35 and less than 60. If this is true, the user has obtained the B grade. If the condition is false, the else block is executed.
13.4.4 Nested-if Statement
The nested-if statements comprises multiple if statements within an if statement. The flow of the nested-if statements starts with the if statement, which is referred to as the outer if statement. This outer if statement consists of multiple if statements, which are referred to as the inner if statements.
The inner if statements are executed only if the condition in the outer if statement is true. Further, each of the inner if statements is executed, but only if the condition in its previous inner if statement is true.
The syntax to use the nested if statements.
Syntax:
if (condition)
{
// one or more statements;
if (condition)
{
// one or more statements;
if (condition)
{
Concepts Session 13 Operators and Statements V 1.1 © zetutorials Limited
// one or more statements;
}
}
}
Code Snippet 16 validates the username and password using the nested-if statements.
<SCRIPT>
var username = prompt(‘Enter Username:’);
var password = prompt(‘Enter Password:’);
if (username != “” && password != “”)
{
if (username == “admin” && password == “admin123”)
{
alert(‘Login Successful’);
}
else
{
alert (‘Login Failed’);
}
}
</SCRIPT>
The code accepts the username and password and stores them in the username and password variables. The if statement checks whether the values of both the variables are not empty. If they are not empty, the inner if statement is executed. The inner if statement checks whether the value of the username variable is admin and the value of the password variable is admin123. If this condition is true, the Login Successful message is displayed to the user. If the condition is false, the else block is executed.
13.4.5 switch-case Statement
A program becomes quite difficult to understand when there are multiple if statements. To simplify coding and to avoid using multiple if statements, switch-case statement can be used as a different approach to code the same logic. The switch-case statement allows comparing a variable or expression with multiple values.
The syntax to use the switch-case statement is as follows:
Syntax:
switch(expression/variable)
{
case value1:
// statements;
break;
case value2:
// statements;
break;
. . .
case valueN:
// statements;
break;
default:
// default statement
}
where,
switch: Executes a specific case statement that holds the value of the expression or the variable.
case: A value and a colon follow the case keyword. The block of a specific case statement is executed when the value of switch expression and the case value are the same. Each case block must end with the break keyword.
break: Passes the execution control to the statement existing immediately out of the switch-case statement. If there is no break statement, the next case statement is executed.
default: The execution control passes to the default block when none of the case values matches with the switch expression. The default block is the same as the else block of the if-else if statements.
Code Snippet 17 displays the salary of an employee according to the designation by using the switch-case statement.
<SCRIPT>
var designation = prompt(‘Enter designation:’);
switch (designation)
{
case ‘Manager’:
alert (‘Salary: $21000’);
break;
case ‘Developer’:
alert (‘Salary: $16000’);
break;
default:
alert (‘Enter proper designation.’);
break;
}
</SCRIPT>
The code uses the variable designation to store the designation of an employee, which is accepted from the user. The switch statement takes the value of the designation variable and this value is matched with the different case statements. If the value matches, the particular case block is executed, which displays the respective salary. If none of the case values matches with the switch variable, the default block is executed.
if-else if statement:
The if-else if statements allow you to check multiple conditions and specify a different block to be executed for each condition. The flow of these statements begins with the if statement followed by multiple else if statements and finally by an optional else block. The entry point of execution in these statements begins with the if statement. If the condition in the if statement is false, the condition in the immediate else if statement is evaluated.
The if-else if statements are also referred to as the if-else if ladder.
The syntax to use the if-else if statements are as follows:
Syntax:
if (condition)
{
// one or more statements;
}
else if (condition)
{
// one or more statements;
}
else
{
// one or more statements;
}
Code Snippet 15 displays the grades according to the percentage value entered by the user using the if-else if statements.
<script>
var percentage = prompt(‘Enter percentage:’,0);
if (percentage >= 60)
{
alert (‘You have obtained the A grade.’);
}
else if (percentage >= 35 && percentage < 60)
{
alert (‘You have obtained the B class.’);
}
else
{
alert (‘You have failed’);
}
</script>
The code accepts the percentage value from the user and stores it in the percentage variable. The if statement checks whether the value of the percentage variable is greater than or equal to 60. If this is true, the user has obtained the A grade. If the condition is false, the execution control is passed to the else if block. Here, the value of the percentage variable is checked as to whether it is greater than or equal to 35 and less than 60. If this is true, the user has obtained the B grade. If the condition is false, the else block is executed.
13.4.4 Nested-if Statement
The nested-if statements comprises multiple if statements within an if statement. The flow of the nested-if statements starts with the if statement, which is referred to as the outer if statement. This outer if statement consists of multiple if statements, which are referred to as the inner if statements.
The inner if statements are executed only if the condition in the outer if statement is true. Further, each of the inner if statements is executed, but only if the condition in its previous inner if statement is true.
The syntax to use the nested if statements.
Syntax:
if (condition)
{
// one or more statements;
if (condition)
{
// one or more statements;
if (condition)
{
Concepts Session 13 Operators and Statements V 1.1 © zetutorials Limited
// one or more statements;
}
}
}
Code Snippet 16 validates the username and password using the nested-if statements.
<SCRIPT>
var username = prompt(‘Enter Username:’);
var password = prompt(‘Enter Password:’);
if (username != “” && password != “”)
{
if (username == “admin” && password == “admin123”)
{
alert(‘Login Successful’);
}
else
{
alert (‘Login Failed’);
}
}
</SCRIPT>
The code accepts the username and password and stores them in the username and password variables. The if statement checks whether the values of both the variables are not empty. If they are not empty, the inner if statement is executed. The inner if statement checks whether the value of the username variable is admin and the value of the password variable is admin123. If this condition is true, the Login Successful message is displayed to the user. If the condition is false, the else block is executed.
13.4.5 switch-case Statement
A program becomes quite difficult to understand when there are multiple if statements. To simplify coding and to avoid using multiple if statements, switch-case statement can be used as a different approach to code the same logic. The switch-case statement allows comparing a variable or expression with multiple values.
The syntax to use the switch-case statement is as follows:
Syntax:
switch(expression/variable)
{
case value1:
// statements;
break;
case value2:
// statements;
break;
. . .
case valueN:
// statements;
break;
default:
// default statement
}
where,
switch: Executes a specific case statement that holds the value of the expression or the variable.
case: A value and a colon follow the case keyword. The block of a specific case statement is executed when the value of switch expression and the case value are the same. Each case block must end with the break keyword.
break: Passes the execution control to the statement existing immediately out of the switch-case statement. If there is no break statement, the next case statement is executed.
default: The execution control passes to the default block when none of the case values matches with the switch expression. The default block is the same as the else block of the if-else if statements.
Code Snippet 17 displays the salary of an employee according to the designation by using the switch-case statement.
<SCRIPT>
var designation = prompt(‘Enter designation:’);
switch (designation)
{
case ‘Manager’:
alert (‘Salary: $21000’);
break;
case ‘Developer’:
alert (‘Salary: $16000’);
break;
default:
alert (‘Enter proper designation.’);
break;
}
</SCRIPT>
The code uses the variable designation to store the designation of an employee, which is accepted from the user. The switch statement takes the value of the designation variable and this value is matched with the different case statements. If the value matches, the particular case block is executed, which displays the respective salary. If none of the case values matches with the switch variable, the default block is executed.
Saturday, 2 May 2015
Html tutorials session 14
Html tutorials theory
continue Statement
The continue statement is mostly used in the loop constructs. The continue statement is denoted by the continue keyword. It is used to terminate the current execution of the loop and continue with the next repetition by returning the control to the beginning of the loop. This means, the continue statement will not terminate the loop entirely, but terminates the current execution.
<script>
var result = ‘’;
for (var i = 0; i <= 15; i++)
{
if((i%2) != 0)
{
continue;
}
result = result + i + ‘\n’;
}
alert (‘Even Numbers:\n’ + result);
</script>
Arrays
Consider a scenario where you want to store the names of 100 employees within an IT department. This can be done by creating 100 variables and storing the names. However, keeping track of 100 variables is a tedious task and it results in inefficient memory utilization. The solution to this problem is to create an array variable to store the names of 100 employees.
An array is a collection of values stored in adjacent memory locations. These array values are referenced using a common array name. The values of an array variable must be of the same data type. These values that are also referred to as elements and can be accessed by using subscript or index numbers. The subscript number determines the position of an element in an array list.
JavaScript supports two types of arrays that are as follows
Single-dimensional array
Multi-dimensional array
Single-dimensional Array
In a single-dimensional array, the elements are stored in a single row in the allocated memory.
The first array element has the index number zero and the last array element has an index number one less than the total number of elements. This arrangement helps in efficient storage of data. In addition, it also helps to sort data easily and track the data length.
The array variable can be created using the Array object and new keyword along with the size of the array element.
The syntax to declare and initialize a single-dimensional array is as follows:
Syntax:
var variable_name = new Array(size); //Declaration
variable_name[index] = ‘value’;
where,
variable_name: Is the name of the variable.
size: Is the number of elements to be declared in the array.
index: Is the index position.
<script>
//Declaration using Array Object and then Initialization
var marital_status = new Array(3);
marital_status[0] = ‘Single’;
marital_status[1] = ‘Married’;
marital_status[2] = ‘Divorced’;
//Declaration and Initialization
var marital_status = new Array(‘Single’,’Married’,’Divorced’);
//Declaration and Initialization Without Array
var marital_status = [‘Single’,’Married’,’Divorced’];
</script>
Accessing Single-dimensional Arrays
Array elements can be accessed by using the array name followed by the index number specified in square brackets.
Access Array Elements Without Loops
An array element can be accessed without using loops by specifying the array name followed by the square brackets containing the index number.
Code Snippet 7 demonstrates a script that stores and displays names of the students using a single-dimensional array.
<script>
var names = new Array(“John”, “David”, “Kevin”);
alert(‘List of Student Names:\n’ + names[0] + ‘,’ + ‘ ‘ + names[1] + ‘,’ + ‘ ‘ + names[2]);
</script>
In the code, var names = new Array(“John”,”David”,”Kevin”); declares and initializes an array. The names[0] accesses the first array element which is John. The names[1] accesses the second array element which is David.
The names[2] accesses the third array element, which is Kevin.
Access Array Elements With Loops
JavaScript allows you to access array elements by using different loops. Thus, you can access each array element by putting a counter variable of the loop as the index of an element. However, this requires the count of the elements in an array. So, the length property can be used to determine the number of elements in an array.
Code Snippet 8 demonstrates the script that creates an array to accept the marks of five subjects and display the average.
<script>
var sum = 0;
var marks = new Array(5);
for(var i=0; i<marks.length; i++)
{
marks[i] = parseInt(prompt(‘Enter Marks:’, ‘’));
sum = sum + marks[i];
}
alert (‘Average of Marks: ‘ + (sum/marks.length));
</script>
In the code, var marks = new Array(5); declares an array of size 5. It displays a prompt box that accepts the marks for a subject in each iteration. Then, the code calculates and displays the average marks.
Multi-dimensional Array
Consider a scenario to store the employee IDs of 100 employees and their salary structure. The salary structure will include the basic salary, allowances, HRA, and the total gross salary. Now, if a single-dimensional array is used, then two separate arrays need to be created for storing employee IDs and salaries. However, using a multi-dimensional array, both IDs and salaries are stored in just one array.
A multi-dimensional array stores a combination of values of a single type in two or more dimensions. These dimensions are represented as rows and columns similar to those of a Microsoft Excel sheet. A two-dimensional array is an example of the multi-dimensional array.
The syntax to declare a two-dimensional array is as follows:
Syntax:
var variable_name = new Array(size); //Declaration
variable_name[index] = new Array(‘value1’,’value2’..);
where,
variable_name: Is the name of the array.
index: Is the index position.
value1: Is the value at the first column.
value2: Is the value at the second column.
Accessing Two-dimensional Arrays
Multi-dimensional arrays can be accessed by using the index of main array variable along with index of sub-array.
Access Array Elements Without Loops
Code Snippet 9 creates a two-dimensional array that displays the employee details.
Code Snippet 9:
<script>
var employees = new Array(3);
employees[0] = new Array(‘John’, ‘25’, ‘New Jersey’);
employees[1] = new Array(‘David’, ‘21’, ‘California’);
document.write(‘<H3> Employee Details </H3>’);
document.write(‘<P><B>Name: </B>’ + employees[0][0] + ‘</P>’);
document.write(‘<P><B>Location: </B>’ + employees[0][2] + ‘</ P>’);
document.write(‘<P><B>Name: </B>’ + employees[1][0] + ‘</P>’);
document.write(‘<P><B>Location: </B>’ + employees[1][2] + ‘</ P>’);
</script>
In the code, var employees = new Array(3) creates an array of size 3. The declaration employees[0] = new Array(‘John’,’23’,’New Jersey’) creates an array at the 0th row of the employees array. Similarly, employees[1] = new Array(‘David’,’21’,’California’) creates an array at the first row of the employees array.
Access Array Elements With Loops
Code Snippet 10 creates a two-dimensional array to display the product details.
<script>
var products = new Array(2);
products[0] = new Array(‘Monitor’, ‘236.75’);
products[1] = new Array(‘Keyboard’, ‘45.50’);
document.write(‘<TABLE border=1><TR><TH>Name</TH><TH>
Price</TH></TR>’);
for(var i=0; i<products.length; i++)
{
document.write(‘<TR>’);
for(var j=0; j<products[i].length; j++)
{
document.write(‘<TD>’ + products[i][j] + ‘</TD>’);
}
document.write(‘</TR>’);
}
document.write(‘</TABLE>’);
</script>
In the code, products[0] = new Array(‘Monitor’,’236.75’) creates an array at the 0th row of the products array. Similarly, products[1] = new Array(‘Keyboard’,’45.50’) creates an array at the first row of the products array. The condition, i < products.length, specifies that the counter variable i should be less than the number of rows in the array variable, products. For each row in the array, the condition, j < products[i].length specifies that the counter variable j, should be less than the number of columns specified the ith row of the array variable, products. Finally, document.write(“<TD>” + products[i][j] + “</TD>”) displays the values at the ith row and jth column of array variable, products.
Array Methods
An array is a set of values grouped together and identified by a single name. In JavaScript, the Array object allows you to create arrays. It provides the length property that allows you to determine the number of elements in an array. The various methods of the Array object allow to access and manipulate the array elements.
<script>
var flowers = new Array(‘Rose’, ‘Sunflower’, ‘Daisy’);
document.write(‘Number of flowers: ‘ + flowers.length + ‘<br/>’);
document.write(‘Flowers: ‘ + flowers.join(‘, ‘) + ‘<br/>’);
document.write(‘Orchid and Lily are Added: ‘ + flowers.push(“Orchid”, “Lily”) + ‘<br/>’);
document.write(‘Flowers (In Ascending Order): ‘ + flowers.sort() + ‘<br/>’);
document.write(‘Flowers Removed: ‘ + flowers.pop()+’<br/>’);
</script>
In the code, an array variable flowers is created, that stores the names of three flowers. The length property is used to display the number of flowers in the array variable. The join() method joins the flower names and separates them with a comma. The push() method adds orchid and lily at the end of the array and the total number of flowers in the array list is displayed as 5. The sort() method sorts the flowers in alphabetical order. The pop() method retrieves the last element that is Sunflower, from the array list.
for...in Loop
The for...in loop is an extension of the for loop. It enables to perform specific actions on the arrays of objects. The loop reads every element in the specified array and executes a block of code only once for each element in the array.
The syntax of the for...in loop is as follows:
Syntax:
for (variable_name in array_name)
{
//statements;
}
where,
variable_name: Is the name of the variable.
array_name: Is the array name.
Code Snippet 12 demonstrates how to display elements from an array using the for...in loop.
<script>
var books = new Array(‘Beginning CSS 3.0’, ‘Introduction to HTML5’, ‘HTML5 in Mobile Development’);
document.write(‘<H3> List of Books </H3>’);
for(var i in books)
{
document.write(books[i] + ‘<br/>’);
}
</script>
continue Statement
The continue statement is mostly used in the loop constructs. The continue statement is denoted by the continue keyword. It is used to terminate the current execution of the loop and continue with the next repetition by returning the control to the beginning of the loop. This means, the continue statement will not terminate the loop entirely, but terminates the current execution.
<script>
var result = ‘’;
for (var i = 0; i <= 15; i++)
{
if((i%2) != 0)
{
continue;
}
result = result + i + ‘\n’;
}
alert (‘Even Numbers:\n’ + result);
</script>
Arrays
Consider a scenario where you want to store the names of 100 employees within an IT department. This can be done by creating 100 variables and storing the names. However, keeping track of 100 variables is a tedious task and it results in inefficient memory utilization. The solution to this problem is to create an array variable to store the names of 100 employees.
An array is a collection of values stored in adjacent memory locations. These array values are referenced using a common array name. The values of an array variable must be of the same data type. These values that are also referred to as elements and can be accessed by using subscript or index numbers. The subscript number determines the position of an element in an array list.
JavaScript supports two types of arrays that are as follows
Single-dimensional array
Multi-dimensional array
Single-dimensional Array
In a single-dimensional array, the elements are stored in a single row in the allocated memory.
The first array element has the index number zero and the last array element has an index number one less than the total number of elements. This arrangement helps in efficient storage of data. In addition, it also helps to sort data easily and track the data length.
The array variable can be created using the Array object and new keyword along with the size of the array element.
The syntax to declare and initialize a single-dimensional array is as follows:
Syntax:
var variable_name = new Array(size); //Declaration
variable_name[index] = ‘value’;
where,
variable_name: Is the name of the variable.
size: Is the number of elements to be declared in the array.
index: Is the index position.
<script>
//Declaration using Array Object and then Initialization
var marital_status = new Array(3);
marital_status[0] = ‘Single’;
marital_status[1] = ‘Married’;
marital_status[2] = ‘Divorced’;
//Declaration and Initialization
var marital_status = new Array(‘Single’,’Married’,’Divorced’);
//Declaration and Initialization Without Array
var marital_status = [‘Single’,’Married’,’Divorced’];
</script>
Accessing Single-dimensional Arrays
Array elements can be accessed by using the array name followed by the index number specified in square brackets.
Access Array Elements Without Loops
An array element can be accessed without using loops by specifying the array name followed by the square brackets containing the index number.
Code Snippet 7 demonstrates a script that stores and displays names of the students using a single-dimensional array.
<script>
var names = new Array(“John”, “David”, “Kevin”);
alert(‘List of Student Names:\n’ + names[0] + ‘,’ + ‘ ‘ + names[1] + ‘,’ + ‘ ‘ + names[2]);
</script>
In the code, var names = new Array(“John”,”David”,”Kevin”); declares and initializes an array. The names[0] accesses the first array element which is John. The names[1] accesses the second array element which is David.
The names[2] accesses the third array element, which is Kevin.
Access Array Elements With Loops
JavaScript allows you to access array elements by using different loops. Thus, you can access each array element by putting a counter variable of the loop as the index of an element. However, this requires the count of the elements in an array. So, the length property can be used to determine the number of elements in an array.
Code Snippet 8 demonstrates the script that creates an array to accept the marks of five subjects and display the average.
<script>
var sum = 0;
var marks = new Array(5);
for(var i=0; i<marks.length; i++)
{
marks[i] = parseInt(prompt(‘Enter Marks:’, ‘’));
sum = sum + marks[i];
}
alert (‘Average of Marks: ‘ + (sum/marks.length));
</script>
In the code, var marks = new Array(5); declares an array of size 5. It displays a prompt box that accepts the marks for a subject in each iteration. Then, the code calculates and displays the average marks.
Multi-dimensional Array
Consider a scenario to store the employee IDs of 100 employees and their salary structure. The salary structure will include the basic salary, allowances, HRA, and the total gross salary. Now, if a single-dimensional array is used, then two separate arrays need to be created for storing employee IDs and salaries. However, using a multi-dimensional array, both IDs and salaries are stored in just one array.
A multi-dimensional array stores a combination of values of a single type in two or more dimensions. These dimensions are represented as rows and columns similar to those of a Microsoft Excel sheet. A two-dimensional array is an example of the multi-dimensional array.
The syntax to declare a two-dimensional array is as follows:
Syntax:
var variable_name = new Array(size); //Declaration
variable_name[index] = new Array(‘value1’,’value2’..);
where,
variable_name: Is the name of the array.
index: Is the index position.
value1: Is the value at the first column.
value2: Is the value at the second column.
Accessing Two-dimensional Arrays
Multi-dimensional arrays can be accessed by using the index of main array variable along with index of sub-array.
Access Array Elements Without Loops
Code Snippet 9 creates a two-dimensional array that displays the employee details.
Code Snippet 9:
<script>
var employees = new Array(3);
employees[0] = new Array(‘John’, ‘25’, ‘New Jersey’);
employees[1] = new Array(‘David’, ‘21’, ‘California’);
document.write(‘<H3> Employee Details </H3>’);
document.write(‘<P><B>Name: </B>’ + employees[0][0] + ‘</P>’);
document.write(‘<P><B>Location: </B>’ + employees[0][2] + ‘</ P>’);
document.write(‘<P><B>Name: </B>’ + employees[1][0] + ‘</P>’);
document.write(‘<P><B>Location: </B>’ + employees[1][2] + ‘</ P>’);
</script>
In the code, var employees = new Array(3) creates an array of size 3. The declaration employees[0] = new Array(‘John’,’23’,’New Jersey’) creates an array at the 0th row of the employees array. Similarly, employees[1] = new Array(‘David’,’21’,’California’) creates an array at the first row of the employees array.
Access Array Elements With Loops
Code Snippet 10 creates a two-dimensional array to display the product details.
<script>
var products = new Array(2);
products[0] = new Array(‘Monitor’, ‘236.75’);
products[1] = new Array(‘Keyboard’, ‘45.50’);
document.write(‘<TABLE border=1><TR><TH>Name</TH><TH>
Price</TH></TR>’);
for(var i=0; i<products.length; i++)
{
document.write(‘<TR>’);
for(var j=0; j<products[i].length; j++)
{
document.write(‘<TD>’ + products[i][j] + ‘</TD>’);
}
document.write(‘</TR>’);
}
document.write(‘</TABLE>’);
</script>
In the code, products[0] = new Array(‘Monitor’,’236.75’) creates an array at the 0th row of the products array. Similarly, products[1] = new Array(‘Keyboard’,’45.50’) creates an array at the first row of the products array. The condition, i < products.length, specifies that the counter variable i should be less than the number of rows in the array variable, products. For each row in the array, the condition, j < products[i].length specifies that the counter variable j, should be less than the number of columns specified the ith row of the array variable, products. Finally, document.write(“<TD>” + products[i][j] + “</TD>”) displays the values at the ith row and jth column of array variable, products.
Array Methods
An array is a set of values grouped together and identified by a single name. In JavaScript, the Array object allows you to create arrays. It provides the length property that allows you to determine the number of elements in an array. The various methods of the Array object allow to access and manipulate the array elements.
<script>
var flowers = new Array(‘Rose’, ‘Sunflower’, ‘Daisy’);
document.write(‘Number of flowers: ‘ + flowers.length + ‘<br/>’);
document.write(‘Flowers: ‘ + flowers.join(‘, ‘) + ‘<br/>’);
document.write(‘Orchid and Lily are Added: ‘ + flowers.push(“Orchid”, “Lily”) + ‘<br/>’);
document.write(‘Flowers (In Ascending Order): ‘ + flowers.sort() + ‘<br/>’);
document.write(‘Flowers Removed: ‘ + flowers.pop()+’<br/>’);
</script>
In the code, an array variable flowers is created, that stores the names of three flowers. The length property is used to display the number of flowers in the array variable. The join() method joins the flower names and separates them with a comma. The push() method adds orchid and lily at the end of the array and the total number of flowers in the array list is displayed as 5. The sort() method sorts the flowers in alphabetical order. The pop() method retrieves the last element that is Sunflower, from the array list.
for...in Loop
The for...in loop is an extension of the for loop. It enables to perform specific actions on the arrays of objects. The loop reads every element in the specified array and executes a block of code only once for each element in the array.
The syntax of the for...in loop is as follows:
Syntax:
for (variable_name in array_name)
{
//statements;
}
where,
variable_name: Is the name of the variable.
array_name: Is the array name.
Code Snippet 12 demonstrates how to display elements from an array using the for...in loop.
<script>
var books = new Array(‘Beginning CSS 3.0’, ‘Introduction to HTML5’, ‘HTML5 in Mobile Development’);
document.write(‘<H3> List of Books </H3>’);
for(var i in books)
{
document.write(books[i] + ‘<br/>’);
}
</script>
Subscribe to:
Posts (Atom)