Skill-Enhancement-Web-Programming-munotes

Page 1

1 1
HTML5
Unit Structure :
1.0 Objectives
1.1 Introduction
1.2 Fundamental Elements of HTML
1.3 Formatting Text in HTML
1.4 Organizing Text in HTML
1.5 Links and URLs in HTML
1.6 Tables in HTML
1.7 Images on a Web Page
1.8 Image Formats
1.9 Image Maps
1.10 Colors
1.11 FORMs in HTML
1.12 Interactive Elements
1.13 Working with Multimedia
1.13.1 HTML elements for inserting Audio on a web page
1.13.2 HTML elements for inserting Video on a web page
1.14 Summary
1.15 Reference for further reading
1.16 Questio ns
1.0 OBJECTIVES
After completing this chapter, you will be able to:
 To understand the basic concept of HTML5.
 To understand the HTML document structure.
 To understand the h ow to create HTML elements, attributes, tags.
 To understand the h ow to create HTML list, image, table, map. munotes.in

Page 2


Skill Enhancement: Web
Programming
2  To understand the h ow to create FORMs in HTML.
 To understand the h ow to working with Multimedia.
1.1 INTRODUCTION
1.1.1 HTML
HTML stands for Hyper Text Markup Language, which is used to create
web pages and apps. HTML is made up o f a number of different elements.
HTML components specify how the content should be displayed in the
browser. Tags are used to represent HTML elements. HTML is a markup
language. Notepad was used to write the text. A web browser, such as
Google Chrome, int erprets HTML code. HTML is case insensitive (but
still lower case is generally considered easy to read) language. We can
design static web pages only with HTML.

1.1.2 HTML5
HTML5, which replaces HTML 4.01, XHTML 1.0, and XHTML 1.1, is
the next significan t revision of the HTML standard. HTML5 is a web
standard for organising and presenting content on the web. HTML5 is
essentially a term for a professional touch web technologies. The HTML
Living Standard is included, as well as JavaScript APIs for storage,
multimedia, and device access. HTML5 supports both audio and video.
HTML does not allow JavaScript to run within the web browser, whereas
HTML5 does. HTML5 allows inline mathML and SVG to be used in a
text. HTML5 adds new form controls including date and t ime, email,
number, category, title, Url, search, and more. HTML5 includes a plenty
of new elements. Time, footer, description, audio, article, canvas, shape
and so on are some of the most essential.


munotes.in

Page 3


HTML5

3 1.2 FUNDAMENTAL ELEMENTS OF HTML
Tags are the parts o f an HTML element that begin and end. They begin
with the < symbol and terminate with the > symbol. Tags are the contents
of the written inside < and >.
Between the tags, elements surround the contents. They have some type of
structure or expression to the m. A start tag, content, and end tag are the
most common elements.
There are two types of HTML tags:
 Container Elements or Paired Tags
 Empty Elements or Singular Tags
Elements form an HTML file. These elements are capable of developing
web pages and defin ing the content on those pages. A start tag
, a closing tag , and content added between them
make an element in HTML. A collection of start tag, attributes, end tag,
and content between them forms an element in HTML. All HTML
elements ca n have attributes. In HTML, an attribute offers additional
information about an element and is added within the start tag. There are
two fields in an HTML attribute: name and value.

1.2.1 HTML Document Structure
The structure of a typical HTML document i s as follows:




Tags associated to document head
munotes.in

Page 4


Skill Enhancement: Web
Programming
4

Tags associated to document body




Where
 The declaration indicates that this is an HTML5
document.
 The root element of an HTML pa ge is the element.
 The html page's meta data is stored in the element.
 The element gives the HTML page a title (which appears in <br>the browser's title bar or in the tab). <br> The <body> element specifies the document's body and serves as a <br>container for all visible information, including headers, <br>paragraphs, pictures, hyperlinks, tables, lists, and so on. <br>1.2.2 Creating an HTML Document and Saving It: <br>Step 1 : Open a text editor and write HTML code (here we are using <br>Notepad) <br>Step 2 : Select File from the File Menu. <br>Step 3 : Select Save As. <br>Step 4 : Type a Name with extension .HTM or .HTML. <br>Step 5 : Select the location where you want to save the file. <br>Step 6 : Click on Save. <br>1.2.3 Viewing an HTML Document: <br>Step 1 : Navigate to the HTML file' s location. <br>Step 2 : Right -click on the HTML file and select the option to open with. <br>Step 3 : Choose a browser (Google Chrome). <br>Step 4 : The webpage will be seen. <br>1.2.4 Viewing an HTML Document in Another Way: <br>If you have Google Chrome selected as your de fault browser, you can just <br>double -click the HTML file and it will open in Chrome. munotes.in</p> </div> <div class="post"> <h2>Page 5</h2> <p> <br> HTML5 <br> <br>5 1.3 FORMATTING TEXT IN HTML <br>Formatting elements were designed to display special types of text: <br> <b> tag : It’s known as Bold text tag and used to displayed content in <br>bold. <b>……..</b> is the syntax for the <b> tag. <br> <strong> tag : It’s known as Important text tag and used to displayed <br>text as strong text. < strong >……..</ strong > is the syntax for the < <br>strong > tag. <br> <i> tag : It’s known as Italic text tag and used to displa yed content in <br>italic. <i>……..</i> is the syntax for the <i> tag. <br> <u> tag : It’s known as Underline text tag and used to displayed <br>content with underline. <u>……..</u> is the syntax for the <u> tag. <br> <em> tag : It’s known as Emphasized text tag and used to d isplayed <br>text as emphasized text. <em>……..</em> is the syntax for the <em> <br>tag. <br> <small> tag : It’s known as Smaller text tag and used for identifying <br>secondary importance such as copyright, side comments, and legal <br>notices. <small>……..</ small > is the syn tax for the < small > tag. <br> <del> tag : It’s known as Deleted text tag and used to indicate the area <br>of the document where text has been deleted/removed. <br><del>……..</del> is the syntax for the <del> tag. <br> <ins> tag : It’s known as Inserted text tag and used t o represent the <br>newly inserted text It normally appears with a text underline, however <br>this may be altered using a CSS attribute. <ins>……..</ins> is the <br>syntax for the <ins> tag. <br>Example of formatting text tags - <br> munotes.in</p> </div> <div class="post"> <h2>Page 6</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>6 <sub> tag : It’s known as Subscript text tag and used to specify text that is <br>subscripted. The text inside a <sub> has a lower baseline and a smaller <br>font than the surrounding content. The <sub> tag can be used to display <br>mathematical or chemical formulas. < sub >……..</ sub > is the syntax <br>for th e < sub > tag. <br> <sup> tag : It’s known as Superscript text tag and used to define <br>content that is written in superscript. The content included within the <br><sup> element has a higher baseline and a smaller font size than the <br>surrounding text. Mathematical for mulae and footnotes can be defined <br>with the <sup> tag. < sup >……..</ sup > is the syntax for the < sup > <br>tag. <br>Example of <sub> and <sup> tag - <br> <br> <br> tag : It’s known as Line Break tagand used to break a line and <br>display the text from the next line. The HTM L br tag can be used in <br>two ways <br> or <br/>. The closed br tag <br/> is suggested because <br>it is supported by both HTML and XHTML. <br/> is the syntax for the <br><br> tag. <br> <br> <hr> tag : It’s known as Horizontal Ruleand used to produce the <br>horizontal line. It cr eates a horizontal divide in the content. In HTML, <br>it's also known as a Horizontal Rule. <hr> is the syntax for the <hr> tag. <br>Example of <hr> and <br> tag: munotes.in</p> </div> <div class="post"> <h2>Page 7</h2> <p> <br> HTML5 <br> <br>7 <br> <br> <br> COMMENT Tag : HTML comments are not visible in the browser, <br>however they can assist in the documenta tion of your HTML source <br>code. You can use comments to describe your code, which will help <br>enormously when you go back to update the source code. If you have a <br>lot of code, this is very helpful. Comments are given between <! -- type <br>text-- > <br> <br>Example of com ments in html - <br> <br>1.4 ORGANIZING TEXT IN HTML <br>1.4.1 HTML Heading <br>A title or a subtitle that you wish to appear on the web page may be <br>defined using an HTML header tag. When you use the heading tags <br><h1>.......</h1>, the text is shown in bold on the browser, and the size of <br>the text is decided by the number of headings. When a heading is <br>displayed, the browser inserts one line before and one line after it. munotes.in</p> </div> <div class="post"> <h2>Page 8</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>8 The <h1> to <h6> tags are used to specify the six different HTML <br>headers. <br>The greatest heading tag is h1 and the lowest is h6. As a result, the <br>most significant heading is h1 and the least important is h6. <br>Example of heading tags in html - <br> <br>1.4.2 HTML Paragraph <br>A paragraph in a webpage is defined by the HTML paragraph tag. It's <br>important to note that a brows er will automatically insert an empty line <br>before and after a paragraph. The <p> element in HTML denotes the start <br>of a new paragraph. <br>When you use a lot of spaces inside the HTML p> tag, the browser <br>eliminates the excess spaces and lines when the page is shown. The <br>browser considers the number of spaces and lines to be one. < p >……..</ <br>p > is the syntax for the < p > tag. 7.5 <br>Example of paragraph tag in html - <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 9</h2> <p> <br> HTML5 <br> <br>9 <br>1.4.3 HTML Division <br>In an HTML document, the div> element denotes a division or section. <br>The <div> tag serves as a container for HTML components, which may <br>then be decorated using CSS or modified using JavaScript. The class or id <br>attribute can be used to style the <div> element. It is a block level tag <br>It's a term that refers to a collection of H TML tags that may be used to <br>build sections and apply styles to them. < div >……..</ div > is the syntax <br>for the < div > tag. <br>Example of division tag in html - <br> <br>1.4.4 Font <br>HTML5 does not support this. The font style for the text within it is <br>defined by the HTML <font> element. In an HTML document, it specifies <br>the font size, colour, and face of the text. <font>…. </font> is the syntax <br>for the <font> tag with attributes size, color and face. <br>Example of font tag in html - <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 10</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>10 1.4.5. List in HTML <br>HTML List HTML lists allow web developers to group a set of related <br>items in lists.HTML Lists are used to specify lists of information. All lists <br>may contain one or more list elements. There are three different types of <br>HTML lists: <br> Ordered List or Numbered List (ol) <br> Unor dered List or Bulleted List (ul) <br> Description List or Definition List (dl) <br>Ordered List or Numbered List: <br>By default, all list elements in ordered HTML lists are marked with <br>numbers. It's also known as a numbered list. The <ol> tag starts the <br>ordered list, while the <li> tag starts the list items. The number starts at 1 <br>and increases by 1 each time. The Kind element of the <ol> tag is used to <br>specify the type of number for list items. 1 is the default type. The TYPE <br>attribute of the <ol> tag has several opti ons. 1 -Number, I -Upper Roman, i -<br>Lower Roman, A -Upper Case, a - Lower case. <br>Example of order list in html - <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 11</h2> <p> <br> HTML5 <br> <br>11 Unordered List or Bulleted List: <br>All list items in an HTML Unordered list are marked with bullets. It's also <br>referred to as a bulleted list. The ul > tag starts the unordered list, while the <br>li> tag starts the list items. The ul> tag has a TYPE attribute that specifies <br>the type of bullet for each list item. <br>Disc is the default type. The ul> tag's TYPE attribute has the following <br>options:: <br>1.Square 2.C ircle 3.Disc <br>Example of unorder list in html - <br> <br> <br>Description List or Definition List: <br>HTML Description List is a list style that HTML and XHTML both <br>support. It's also known as a definition list, because the words are <br>listed alphabetically, like in a dicti onary. <br>The following three tags are included in the HTML definition list: <br><dl> -Defines the beginning of the list <br><dt> -Specify a term <br><dd> -Specify term definition <br></dl> -Defines the end of the list <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 12</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>12 Example of unorder list in html - <br> <br>1.5 LINKS AND URLS IN H TML <br>A link is connection between two web pages. Hyperlinks are HTML links. <br>You can jump to another document by clicking on a link. The mouse <br>arrow will change into a tiny hand when you move the mouse over a link. <br>The href property, which identifies the lin k's destination, is the most <br>important attribute of the <a> element. The section of the link text that <br>will be visible to the reader is the link text. <br>The reader will be directed to the given URL address by clicking on the <br>link text. <br>In all browsers, links will display as follows by default: <br> link : A link that has not been visited is highlighted in blue. <br> vlink : A visited link is highlighted in purple. <br> alink : An active link is highlighted in red and underlined. <br> <br>Links will open in the current window or fr ame by default. If you want the <br>link to open in a different window or frame than the one it's in, you'll need <br>to add a target attribute in <a> element <br>The following are predefined targets: <br> _blank: opens the page in a new browser window. <br> _self: the page is loaded into the current window. <br> _parent: loads the page into the frame above the one in which the <br>hyperlink is located. munotes.in</p> </div> <div class="post"> <h2>Page 13</h2> <p> <br> HTML5 <br> <br>13  _top: closes all frames and loads the page in the whole browser <br>window. <br>URL stands for Uniform Resource Locator. It refers to an intern et/web <br>address for a resource. The following elements make up a URL: <br> <br>URL having two types - A relative URL and an absolute URL. A relative <br>URL begins with the forward slash and directs the browser to stay within <br>the current site. An absolute URL is the f ull URL of the page that you link <br>to. <br>Put the <img> element within the <a> tag to use an image as a link. With <br>the SRC property, the img> element is used to display an image in an <br>HTML page. <br>Example of <a>tag in html - <br> <br>1.6 TABLES IN HTML <br>HTML tables allow we bsite designers to organise data such as text, <br>photos, links, and other tables into rows and columns of cells. The <table> <br>element is used to build HTML tables, with the <tr> tag used to produce <br>table rows and the <td> tag used to create data cells. By def ault, the items <br>under td> are regular and left aligned. The <th> element is used to specify <br>the table heading. <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 14</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>14 <table> tag: <br><table>: specifies a table. <br><tr>: specifies a row in a table. <br><th> : specifies a header cell in a table. <br><td> : specifies a cell in a table. <br><caption> : specifies the table caption. <br><colgroup> : specifies a group of one or more columns in a table for <br>formatting. <br><col> : used with <colgroup> element to specify column properties for <br>each column. <br><table> attribute: <br>border: pixels Specifie s the border width. A value of "0" means no border. <br>align: Used to define Visual alignment in right, left, centre or justify. <br>bgcolor: The background colour of the tableis defined in rgb(x,x,x) , <br>#hexcode or colorname . <br>cellpadding: The distance between th e cell borders and their contents is <br>defined in pixels or % . <br>cellspacing : The distance between cells is defined in pixels or %. <br>width : The width is defined in pixels or %. <br>Example of <table> in html - <br>munotes.in</p> </div> <div class="post"> <h2>Page 15</h2> <p> <br> HTML5 <br> <br>15 <br> <br>1.6.1 Colspan and Rowspan attributes of <table> <br>A table is divided into rows, with each row containing cells. We may need <br>the table to spread across (merge) multiple columns or rows. We can use <br>the Colspan and Rowspan attributes in this case. <br>1.Colspan <br>The colspan parameter specifies how many columns a cel l should display <br>horizontally. <br>Eg:<td colspan=2> <br>This code will merge two cells horizontally into one. <br>2.Rowspan <br>The rowspan parameter is used to define how many rows a cell should <br>display vertically. <br>Eg:<td rowspan=2> <br>This code will merge two cells vertic ally into one. <br>Before Rowspan After Rowspan. munotes.in</p> </div> <div class="post"> <h2>Page 16</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>16 <br> <br>1.7 IMAGES ON A WEB PAGE <br>The <img> tag in HTML is used to show an image on a web page. The <br>HTML <img> tag is an empty tag with just attributes; no closing tags are <br>used in the HTML image element. <br><img> has th e following attributes: <br> src: is used to indicate the image's path. <br> alt: is used to specify an image's alternate text. It is useful since it <br>tells the viewer about the picture's meaning and also because if the <br>image cannot be displayed due to a network iss ue, this alternate <br>text will be displayed. <br> height: is used to determine the image's height. <br> width: is used to specify the image's width. <br> usemap: is used to specify an image as a client -side image map. <br> ismap: is used to specify an image as a server -side ima ge map. munotes.in</p> </div> <div class="post"> <h2>Page 17</h2> <p> <br> HTML5 <br> <br>17  align: is used to specify the image alignment with value top, bottom, <br>middle, left and right. <br> border: is used to specify the width of image border. <br>Example of image in html - <br> <br>1.8 IMAGE FORMATS <br> BMP : Microsoft Windows produced the bitmap (.bmp) fo rmat, which <br>is widely used on the internet because to Internet Explorer's popularity. <br>Supports 16.7 million colours and is primarily uncompressed, making <br>it somewhat big. <br> <br> JPEG : JPEG (Joint Photographers Expert Group) is a compression <br>standard (not an ima ge format) with the extension.jpg or .jpeg , .jpg. <br>.jpg offers 16.7 million colours with a tiny file size, and is frequently <br>used for high -color photography. However, when compressed, certain <br>details are lost (lossy compression). <br> <br> GIF: GIF ( Graphic Interc hange Format ) is a popular image format <br>that loses no information when compressed (i.e lossless compression). <br>The disadvantage of.gif is that it only supports an 8 -bit colour palette, <br>which means that each picture may only have 256 colours, making it <br>unsu itable for images with numerous colours. Most importantly,.gif munotes.in</p> </div> <div class="post"> <h2>Page 18</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>18 allows for animation; a single.gif file may contain several frames, <br>which can then be played in order to produce an animation effect. <br> <br> PNG : PNG (Portable Network Graphics) is an open -source ima ge <br>format that may be used for any sort of image on the Internet. File <br>sizes are greater than.jpg (since compression is lossless). .png allows <br>for 16.7 million colour combinations and 256 transparent colours. <br>Suitable for images that just require a few col ours. Low colour depth <br>data may be compressed into very tiny files. <br>1.9 IMAGE MAPS <br>The HTML mapping image is a client -side image map with clickable areas <br>in an HTML document that act as hyperlinks. The HTML <map> tag is <br>used with the <area> tag to create a client -side image map. An image map <br>is made up of a picture with clickable regions. When you click on the <br>image, it will open to a new or previously selected location. The <map> <br>tag can include several <area> components, each of which defines the <br>area's coordinates and type. You may simply link any portion of a image <br>to other documents using the <map> tag without splitting the image. <br> <br>You must define the shape of the clickable region, and one of the <br>following values can be used: <br> rect – used to define a r ectangular region <br> circle - used to define a circular region <br> poly - used to define a polygonal region <br> default - used to define the entire region <br> <br> <br> <br> <br> <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 19</h2> <p> <br> HTML5 <br> <br>19 Example of image map in html - <br> <br>1.10 COLORS <br>Colors play a significant role in giving your website a pleas ing <br>appearance. The <body> tag can be used to set colours for the entire page, <br>or the bgcolor attribute can be used to set colours for individual tags. <br>The following attributes of the <body> tag can be used to set different <br>colours: <br> bgcolor: specifies the colour of the page's background. <br> text: specifies the colour of the body text is chosen by text. <br> alink: specifies changes colour of active or selected links. <br> link: specifies the colour of linked text is determined by the link <br>command. <br> vlink: assigns a colou r to visited links, or linked text that has already <br>been clicked. <br> munotes.in</p> </div> <div class="post"> <h2>Page 20</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>20 Methods of HTML Color Coding: <br> Color name: Color names can be specified directly, such as green, <br>blue, or red. W3C has listed 16 basic color names. Ex. Yellow, <br>Red etc. <br> <br> Hex code: Hex codes are a six -digit code that represents the <br>proportion of red, green, and blue in a colour. A hexadecimal is a 6 <br>digit representation of a color as #RRGGBB Ex. #110033, <br>#111111 etc. <br> <br> rgb(): The rgb( ) parameter is used to specify colour decimal or <br>percentage values. This property accepts three values: one for red, <br>one for green, and one for blue. The value might be a percentage or <br>an integer between 0 and 255. Ex. rgb(0,0,0), rgb(255,0,0) etc. <br>Example of colours in html -<br> <br>1.11 FORMs in HTML <br>An HTML form is a p art of a document that contains controls like text <br>fields, password fields, checkboxes, radio buttons, submit buttons, menus, <br>and so on. An HTML form allows a user to enter data that will be <br>transmitted to a server for processing, such as a user's name, em ail <br>address, password, phone number, and other information. munotes.in</p> </div> <div class="post"> <h2>Page 21</h2> <p> <br> HTML5 <br> <br>21 Syntax for creating form: <br> <br><form> attributes: <br> action: When a form is submitted, the action specifies where the form <br>data should be sent. <br> name: Specifies the name of the form. <br> method: Specifies t he HTTP method to use when delivering form -data. <br>Get or Post is the option. <br> target: Indicates where the response received after submitting the form <br>should be displayed. <br>1.12 INTERACTIVE ELEMENTS <br>Anything on a web page that the user interacts with is consi dered an <br>interactive element. Consider an interactive element to be something that <br>forces the user to take action. You can use many types of form controls to <br>collect data using an HTML form which are nothing but interactive <br>elements. <br>Some very common attri butes regarding form elements: <br> name : The name attribute is a unique identifier that is used to send <br>data via HTML form elements. <br> id : The id attribute is a unique identifier for HTML tags that allows <br>the browser to identify the element when it is displaye d. <br> value : An <input> element's value is specified via the value attribute. <br>One or more of the following form elements can be contained in the <br>HTML <form> element: <br>1) Text Input Controls <br>2) Checkboxes Controls <br>3) Radio Button Controls <br>4) Select Box Controls <br>5) File Upload boxes <br>6) Button Controls <br>7) Hidden Form Fields <br>1. <input> : munotes.in</p> </div> <div class="post"> <h2>Page 22</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>22 The input> element in HTML is the most often used form element. <br>Depending on the type attribute, an input> element can be presented in a <br>number of ways. <br>The following are the various HTML input types: <br> <input type="text"> : It specifies a single -line text input field <br> <input type="radio"> : It specifies a radio button. A user can select <br>ONE of a limited number of options using radio buttons. <br> <input type="checkbox"> : It specifies a checkbox (for s electing zero <br>or more of many choices) <br> <input type="submit"> : It specifies a submit button (for submitting <br>the form). A button for submitting form data to a form -handler is <br>defined by the <input type="submit">. <br> <input type="button"> : It specifies a click able button <br> <input type="password"> : It specifies a single -line text password field <br> <input type="reset"> : It specifies a reset button that will reset all form <br>values to their default values. <br>Example of form elements in html - <br> munotes.in</p> </div> <div class="post"> <h2>Page 23</h2> <p> <br> HTML5 <br> <br>23 2. <textarea> : <br>A multi -line text input control is defined by the <textarea> tag. The <cols> <br>and <rows> characteristics determine the size of a text area. <br>Example of <textarea> in html - <br> <br>3. <label> : Many form elements have a label defined by the <label> tag. <br>When the user focuse s on the input element, the screen -reader will read <br>out loud the label, which is beneficial for screen -reader users. <br> <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 24</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>24 Example of <label> in html - <br> <br>4. <select> : A drop -down list is created with the <select> element. In <br>most cases, the <select> element i s used in a form to collect user input. <br>The available options in the drop -down list are defined by the <option> <br>tags inside the <select> element. <br> <br> <br> <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 25</h2> <p> <br> HTML5 <br> <br>25 Example of <select> in html - <br> <br>5. <fieldset> and <legend> : In a form, the <fieldset> element is used to <br>group together relevant data. The caption for the <fieldset> element is <br>defined by the <legend> element. <br> <br> <br> <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 26</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>26 Example of <fieldset> and <legend> in html - <br> <br>1.13 WORKING WITH MULTIMEDIA <br>Almost everything that can be heard or seen may be considered <br>multimedi a (like - sound, music, images, records, videos, films, <br>animations, etc.). It is available in a variety of forms. Multimedia <br>components in many forms and types can be found on web sites. Various <br>multimedia tags in HTML allow you to add a variety of multimed ia files <br>to your website. The following are some of the tags: <br> <audio>: Use for displaying a audio file on the web page, <br> <video>: Use for displaying a video file on the web page, munotes.in</p> </div> <div class="post"> <h2>Page 27</h2> <p> <br> HTML5 <br> <br>27  <embed>: Use for embedding multimedia files on the web page, <br> <object>: Use for embedding multimedia files on the web page. <br> <iframe>: Use for embedding other web pages. <br>Media files include multimedia components such as audio and video. <br>Looking at the file extension is the most common approach to figure out <br>what type of file it is. Fo rmats and extensions for multimedia files include: <br>.wav, .mp3, .mp4, .mpg, .wmv, and .avi. <br>1.13.1 HTML elements for inserting Audio on a web page <br>Music and other audio clips are created using the HTML audio tag. The <br>HTML 5 audio element currently supports three file formats which are <br>given below: <br>a). mp3 <br>b). wav <br>c). ogg <br>HTML5 allows you to use video and audio controls. The multimedia <br>elements are played using Flash, Silverlight, and other comparable <br>technologies. <br><audio> Tag Attributes: <br> controls: It specifies the audio controls (play/pause buttons) which <br>are shown. <br> autoplay: When enabled, the audio will begin playing as soon as it is <br>ready. <br> autoplay: When enabled, the audio will begin playing as soon as it is <br>ready. When an audio file is finished, loop signals that it w ill begin <br>playing again. <br> muted: It's being used to turn off the audio output while it's muted. <br> preload: This indicates the author view that when the page loads, it <br>should upload an audio file. <br> src: This specifies the audio file's source URL. <br> <br> <br> <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 28</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>28 Example o f inserting audio - <br> <br>1.13.2 HTML elements for inserting Video on a web page <br>The <video> tag in HTML allows you to embed video in your document. <br>MP4 and OGG are the video formats that HTML supports. The <source> <br>element is used to identify media, as well as the kind of media and other <br>properties. In the video element, several source elements are allowed, and <br>the browser will use the first format it recognises. <br><video> Tag Attributes: <br> controls: It describes the video controls, which include the play/pause <br>buttons.. <br> height: It's used to change the height of the video player. <br> width: The width of the video player is specified with this attribute. <br> poster: When the video isn't playing, the poster is used to define the <br>image that appears on the screen. <br> autoplay : Th e video will start playing as soon as it is available, <br>according to autoplay. <br> loop : When the video file is ended, the loop specifies that the video <br>file will begin again from the beginning. <br> muted: This option is used to silence the visual output. <br> preload: The author is instructed to upload a video file when the page <br>loads. <br> src: This specifies the URL of the video file's source. <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 29</h2> <p> <br> HTML5 <br> <br>29 Example of inserting video - <br> <br>1.14 SUMMARY <br>In this chapter we have covered Fundamental Elements of HTML, <br>structure of html docum ent, how to Formatting Text in HTML, Organizing <br>Text in HTML. How to use Links and URLs in HTML, Tables in HTML, <br>Images on a Web Page, Image Formats, Image Maps, Colors. <br>How to create FORMs in HTML. How to insert HTML elements for <br>inserting Audio on a web page and Video on a web page. <br>1.15 REFERENCE FOR FURTHER READING <br> HTML 5 Black Book, Covers CSS 3, JavaScript, XML, XHTML, <br>AJAX, PHP and jQuery, 2ed, Dreamtech Press. <br> HTML, XHTML, and CSS Bible Fifth Edition, Steven M. Schafer, <br>WILEY <br> Learn to Master HTML 5 , scriptDemics, StarEdu Solutions Pvt Ltd. <br>1.16 QUESTIONS <br> Which tag is used to create a list that displays items with bullets? <br> How to make an image map? <br> Explain HTML document structure. <br> Explain <font> in html. <br> Explain <sub> and <sup> tags. <br> How to create HT ML elements, attributes, tags? <br> How to create HTML list, image, table, map? <br> How to create Forms in HTML? <br> How to working with Multimedia in HTML? <br> Explain HTML elements for inserting Audio on a web page. <br> Explain HTML elements for inserting Video on a web page . <br> Explain any 2 form elements with an example. <br> munotes.in</p> </div> <div class="post"> <h2>Page 30</h2> <p> 30 2 <br>CSS <br>Unit Structure : <br>2.1 Objectives <br>2.2 Introduction <br>2.3 Understanding the Syntax of CSS <br>2.4 CSS Selectors <br>2.5 Inserting CSS in an HTML Document <br>2.6 CSS properties to work with background of a Page <br>2.7 CSS properties to work with Fonts and Text Styles <br>2.8 CSS properties for positi oning an element <br>2.9 Summary <br>2.10 Reference for further reading <br>2.11 Questions <br>2.1 OBJECTIVES <br>After completing this chapter, you will be able to: <br> Understand the function of CSS in the creation of user interfaces (for <br>mobile) and websites. <br> Selectors, CSS properties, CSS code structure, CSS declarations, and <br>other fundamental CSS topics will be covered. <br>2.2 INTRODUCTION <br>Cascading Style Sheets (CSS) is an abbreviation for Cascading Style <br>Sheets. Styles determine how HTML elements are displayed. It was <br>created to allow devel opers to separate content from design in order to <br>create a well -designed HTML page. External Style Sheets can help you <br>save time and effort. CSS files contain external style sheets. In 1997, CSS <br>was created as a tool for Web designers to determine the appe arance and <br>feel of their pages. If the designer adds additional instructions, the browser <br>must determine which ones take precedence. munotes.in</p> </div> <div class="post"> <h2>Page 31</h2> <p> <br> CSS <br> <br>31 <br> <br>The official logo of the latest version CSS 3 <br>CSS is typically used in combination with HTML to customize the <br>appearance of web pages and user interfaces. CSS defines how HTML <br>elements should appear on a screen, i n print, or in other media. CSS helps <br>you save time and effort. It has the ability to control the layout of several <br>web pages at the same time. CSS files contain external stylesheets. CSS is <br>a style sheet language for the web. It can be used with any XML -based <br>markup language and is independent on HTML. <br>2.2.1 Use Of CSS <br>CSS is used to control the appearance and feel of web pages. CSS is used <br>to control the colour of text, font style, different background pictures or <br>colours, paragraph spacing, layout design , display changes for various <br>devices, and a range of other effects. CSS is simple to learn and <br>understand, yet it has a lot of power over how a web page looks. CSS is <br>commonly used in conjunction with markup languages such as HTML. <br>CSS, in simple terms, i s a declaration of a style sheet that can be used <br>repeatedly. <br>2.2.2 Features, Need and Advantages of CSS: <br>1. CSS allows for reusability. <br>2. CSS makes changing the style of a document relatively simple. <br>3. We may have a consistent layout and location of navigation a cross a <br>site by using CSS. <br>4. It helps save time. <br>5. CSS-enabled pages load quicker than non -CSS-enabled pages. Etc. <br>2.2.3 Disadvantages of CSS <br>1. CSS doesn't always operate the same way in various browsers. <br>2. CSS debugging is extremely difficult. <br>3. Requires time while the webpage is being created. <br>2.3 UNDERSTANDING THE SYNTAX OF CSS <br>The selector identifies the HTML element that needs to be styled. A <br>selector is a tool that allows you select or point to one or more specified munotes.in</p> </div> <div class="post"> <h2>Page 32</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>32 items on your page. One or more declarations are separated by semicolons <br>in the declaration block. A colon separates the name of the CSS property <br>and its value in each declaration. A semicolon always ends a CSS <br>declaration, and declaration blocks are enclosed by curly braces. <br>Selector { property : v alue ; property2 : value2;} <br>For example, the following CSS style rule specifies that, any text in h1 <br>elements should be centered and has a font color of blue. <br>h1 {text -align:center; color:blue;} <br>2.4 CSS SELECTORS <br>1. Universal Selector: Universal selector ind icate by asterisk (*) sign <br>applies to all elements in your page. It is used to set global setting like a <br>font family. <br>Example : <br>* <br>{ <br>font-family:Arial; <br>} <br>Example of Universal selector - <br> <br>2. Type Selector: Type selector is the most basic type of selector <br>which is used by the users. This selector helps the user to select any <br>HTML element on a page that matches the selector, irrespective of the <br>position of the elements in the document tree. <br> <br>Example : <br>h1 <br>{ <br> text-align: center; <br> color: red; <br>} munotes.in</p> </div> <div class="post"> <h2>Page 33</h2> <p> <br> CSS <br> <br>33 Example of Type Selector: <br> <br> <br>3. ID Selector: ID selectors are very similar to the class selectors. The <br>only difference is that ID selector can only be applied once per page, while <br>class selector can be applied as many times as required by the user. These <br>types of selectors are well supported across standards – compliant <br>browsers. <br> <br>Example : <br>#para1 <br>{ <br>font-family:Arial; <br>color:red; <br>} <br><h1 id="para1">Hello World</h1> <br><h2>Hello World</h2> <br> <br>Example of id selector: <br> <br> <br>4. Class Selector: Class selector is used to style multiple element s. It <br>is prefixed by dot (.). It is useful when you want to give the same type of <br>formatting to related or unrelated HTML element. munotes.in</p> </div> <div class="post"> <h2>Page 34</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>34 Example : <br>.a <br>{ <br> text-align: center; <br> color: red; <br>} <br> <br><P class=”.a”> Hello World</P> <br><H1 class=”.a”>How are you?</H1> <br> <br>Example of class selector: <br> <br> <br>5. Grouping & Combining Selector: Grouping & Combining <br>Selector used to group multiple selectors by separating them with a <br>comma. <br> <br>Example : <br>h1, h2, p <br>{ <br> text-align: center; <br> color: red; <br>} <br> <br><h1>Hello World!</h1> <br><h2>Smalle r heading!</h2> <br><p>This is a paragraph.</p> <br> <br> <br> <br> <br> <br> <br> <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 35</h2> <p> <br> CSS <br> <br>35 <br>Example of Grouping & Combining Selector - <br> <br> <br>2.5 INSERTING CSS IN AN HTML DOCUMENT <br>You can change the design of a website entirely with an external style <br>sheet. <br>2.5.1 Types of CSS <br>1. Inline style <br>An inline sty le rule is defined in an element's opening tag by using the <br>style attribute. Use an inline style when we want to define properties for a <br>single element in a Web page and we do not want to re -use that style. <br>The following example shows an inline style. <br><p style="font -weight: bold; font -style: italic; color: #FF0000"> <br>Example of inline style - <br> munotes.in</p> </div> <div class="post"> <h2>Page 36</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>36 2. Internal style sheet <br>CSS style rules can be defined in a style element inside the head element <br>of a Web page. In that case, the style rules apply only to elements in that <br>page. <br>The following example shows how to define and apply a CSS style rule to <br>all the h1 elements in a Web page. <br>Example of internal style sheet - <br> <br>In this Web page, any text that appears between the <h1> and </h1> tags <br>will be centered and blue . We do not have to reassign these style attributes <br>for each h1 element in the document. If we want to change the color (or <br>any property) of all text in h1 elements, we can edit one style rule. <br>3. External style sheet <br>An external style sheet is a text file that has a .css file name extension and <br>that contains only style rules. We can link a style sheet to a Web page by <br>using a link element, as shown in the following example. <br><link rel="stylesheet" type="text/css" href="myStyles.css" /> <br>This link element app lies the style rules in the external style sheet <br>myStyles.css to the current page. <br> <br> <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 37</h2> <p> <br> CSS <br> <br>37 Example of external style sheet: <br>Create s1.css as follows: <br> <br>Create demo.html and add s1.css in it with <link> tag as follows: <br> <br>2.6 CSS PROPERTIES TO WORK WITH <br>BACKGROUN D OF A PAGE <br>The CSS background property is used to specify the element's background <br>effects. The HTML elements are affected by five CSS background <br>properties: munotes.in</p> </div> <div class="post"> <h2>Page 38</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>38 1) background -color <br>2) background -image <br>3) background -repeat <br>4) background -attachment <br>5) background -position <br>1) CSS background -color <br>The element's background colour is defined using the background -color <br>property. <br>2) CSS background -image <br>The background -image attribute is used to make an image the element's <br>backdrop. <br>3) CSS background -repeat <br>The background -image a ttribute is set to repeat the background picture <br>horizontally and vertically by default. Some photos are only repeated <br>vertically or horizontally. <br>If the image is simply repeated horizontally, the background appears <br>better. <br>background -repeat: repeat -x; and background -repeat: repeat -y; are used in <br>it. <br>4) CSS background -attachment <br>The background -attachment attribute controls whether the background <br>image in the browser window is fixed or scrolls with the rest of the page. <br>The image will not move while scrollin g in the browser if the background <br>image is set to fixed. <br>background: white url('bbb.gif'); <br>background -repeat: no-repeat; <br>background -attachment: fixed; <br>5) CSS background -position <br>The background -position property is used to specify the background <br>imag e's initial location. The background image is put in the top -left corner <br>of the webpage by default. <br>The following positions can be set: <br> center <br> top <br> bottom munotes.in</p> </div> <div class="post"> <h2>Page 39</h2> <p> <br> CSS <br> <br>39  left <br> right <br>background: white url(‘rose1.jpg’); <br>background -repeat: no-repeat; <br>background -attachment : fixed; <br>background -position: center; <br>Example of CSS properties to work with background of a Page - <br> <br>2.7 CSS PROPERTIES TO WORK WITH FONTS AND <br>TEXT STYLES <br>The font property in CSS is used to customise the appearance of text. You <br>can modify the text size, colour, style, and more using the CSS font <br>property. You've previously learned how to bold or underline text. You'll <br>also learn how to use percentages to resize your font. <br>Here are some important font attributes: <br>1) CSS Font color : This property is used to change the color of the <br>text. <br>2) CSS Font family : This property is used to change the face of the <br>font. <br>3) CSS Font size : This property is used to increase or decrease the size <br>of the font. <br>4) CSS Font style : This property is used to make the font bold, italic or <br>oblique. <br>5) CSS Font variant : This property creates a small -caps effect. <br>6) CSS Font weight : This property is used to increase or decrease the <br>boldness and lightness of the font. <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 40</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>40 1) CSS Font Color <br>CSS font colour is a separate attribute in CSS, despite the fa ct that it <br>appears to be part of CSS fonts. It's used to adjust the text colour. <br>A colour can be defined in one of three ways: <br> By a color name ex. red <br> By hexadecimal value ex. 00FF11 <br> By RGB ex. rgb(0,100,255) <br>2) CSS Font Family <br>There are two types of font s in the CSS font family: <br> Generic family: It includes Serif, Sans -serif, and Monospace. <br> Font family: It specifies the font family name like Arial, New Times <br>Roman etc. <br>Serif : Serif fonts include small lines at the end of characters. Example of <br>serif: Times new roman, Georgia etc. <br>Sans -serif : A sans -serif font doesn't include the small lines at the end of <br>characters. Example of Sans -serif: Arial, Verdana etc. <br>3) CSS Font Size <br>CSS font size property is used to change the size of the font. These are the <br>possib le values that can be used to set the font size: <br> xx-small: used to display the extremely small text size. <br> x-small: used to display the extra small text size. <br> Small: used to display small text size. <br> Medium: used to display medium text size. <br> Large: used to d isplay large text size. <br> x-large: used to display extra large text size. <br> xx-large : used to display extremely large text size. <br> Smaller: used to display comparatively smaller text size. <br> Larger:used to display comparatively larger text size. <br> size in pixels or %: used to set value in percentage or in pixels. <br>4) CSS Font Style <br>The CSS Font style parameter specifies the font you wish to use. It might <br>be italic, oblique, or normal. <br> munotes.in</p> </div> <div class="post"> <h2>Page 41</h2> <p> <br> CSS <br> <br>41 5) CSS Font Variant <br>CSS font variant property specifies how to set font variant of an element. <br>It may be normal and small -caps. <br>6) CSS Font Weight <br>The font weight property in CSS specifies the font's weight and how bold <br>it is. Normal, bold, bolder, lighter, or numeric font weights are all options <br>(100, 200..... upto 900). <br>Example of CS S properties to work with Fonts and Text Styles - <br> <br>2.8 CSS PROPERTIES FOR POSITIONING AN <br>ELEMENT <br>The CSS position property is used to define an element's position. It's also <br>useful for planned animation effects and to arrange an element behind <br>another. The top, bottom, left, and right attributes can be used to position <br>an element. These properties can only be used once the position property <br>has been set. The computed position attribute of a position element can be <br>relative, absolute, fixed, or sticky. Let's have a look at the CSS positioning <br>that follows: <br>1) CSS Static Positioning <br>2) CSS Fixed Positioning <br>3) CSS Relative Positioning <br>4) CSS Absolute Positioning <br> munotes.in</p> </div> <div class="post"> <h2>Page 42</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>42 1) CSS Static Positioning <br>HTML components are placed in this position by default. It always places <br>an element i n accordance with the page's natural flow. The top, bottom, <br>left, and right attributes have no effect on it. <br>2) CSS Fixed Positioning <br>The fixed position attribute helps in the positioning of text on the browser. <br>This fixed test is positioned in relation to the browser window and will not <br>move even if the window is scrolled. <br>Example of CSS fixed position - <br> <br>3) CSS Relative Positioning <br>The relative positioning property is used to set the element relative to its <br>normal position. <br>Example of CSS Relative Positi oning - <br> <br>4) CSS Absolute Positioning <br>Absolute positioning is used to position an element in relation to the initial <br>parent element with a non -static location. The containing block is HTML <br>if no such element is detected. <br>You can position an element anywhere on a page with absolute <br>positioning. munotes.in</p> </div> <div class="post"> <h2>Page 43</h2> <p> <br> CSS <br> <br>43 Example of CSS Absolute Positioning - <br> <br>All CSS Position Properties <br>No. property description values <br>1) bottom specify the bottom <br>margin edge for a <br>positioned box. auto, length, %, inherit <br>2) Clip specify clip an <br>absolutely positioned <br>element. shape, auto, inherit <br>3) cursor specify the type of <br>cursors to be <br>displayed. url, auto, crosshair, default, <br>pointer, move, e -resize, ne -<br>resize, nw -resize, n -resize, se -<br>resize, sw -resize, s -resize, w -<br>resize, text, wait, help <br>4) Left specify a left margin <br>edge for a positioned <br>box. auto, length, %, inherit <br>5) overflow specify what happens <br>if content overflow <br>an element's box. auto, hidden, scroll, visible, <br>inherit <br>6) position specify the type of <br>positioning for an <br>element. absolute, fixed, relative, static, <br>inherit <br>7) right specify a right <br>margin edge for a <br>positioned box. auto, length, %, inherit <br>8) Top specify a top margin <br>edge for a positioned <br>box. auto, length, %, inherit <br>9) z-index specify set stack <br>order of an element . number, auto, inherit <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 44</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>44 2.9 SUMMARY <br>In this chapter we have covered Syntax of CSS, how to use CSS <br>Selectors , how to insert CSS in an HTML Document , Use of CSS <br>properties to work with background of a Page , Fonts , Text Styles and <br>positioning an element with examples. CSS is essential knowledge for <br>today's web developers and designers. <br>2.10 REFERENCE FOR FURTHER READING <br> HTML 5 Black Book, Covers CSS 3, JavaScript, XML, XHTML, <br>AJAX, PHP and j Query, 2ed, Dreamtech Press. <br> HTML, XHTML, and CSS Bible Fifth Ed ition, Steven M. Schafer, <br>WILEY <br> Learn to Master HTML 5, script Demics, Star Edu Solutions Pvt Ltd. <br>2.11 QUESTIONS <br>1. What is CSS? <br>2. What is the full form of CSS? <br>3. Why was CSS developed? <br>4. What are the advantages of using CSS? <br>5. What are the disadvantages of using CSS? <br>6. What are the types of CSS? <br>7. How to Insert CSS in an HTML Document? <br>8. Write a note on CSS selectors. <br>9. Explain CSS properties to work with background of a Page. <br>10. Explain CSS properties to work with Fonts and Text Styles. <br>11. Explain CSS properties for positioning an element. <br> <br><br> munotes.in</p> </div> <div class="post"> <h2>Page 45</h2> <p> 45 3 <br>JAVASCRIPT <br>Unit Structure <br>3.1 What is Java Script ? <br>3.2 Using JavaScript in an HTML Document <br>3.3 String Concatenation <br>3.4 Maths Book <br>3.5 JavaScript Looping Statements: <br>3.6 Confirmation Dialog Box <br>3.7 Execution of code after a delay <br>3.8 JavaScript Objects <br>3.9 Browser Object Model <br>9.10 JavaScript Form Validation <br>3.1 WHAT IS JAVASCRIPT ? <br>JavaScript is a dynamic computer programming language. It is lightweight <br>and most commonly used as a part of web pages, whose implementations <br>allow client -side script to interact with the user and ma ke dynamic pages. <br>It is an interpreted programming language with object -oriented <br>capabilities. <br>JavaScript was first known as LiveScript, but Netscape changed its name <br>to JavaScript, possibly because of the excitement being generated by Java. <br>JavaScript mad e its first appearance in Netscape 2.0 in 1995 with the <br>name LiveScript . JavaScript is a lightweight, interpreted programming <br>language. <br> Designed for creating network -centric applications. <br> Complementary to and integrated with Java. <br> Complementary to and inte grated with HTML. <br> Open and cross -platform <br>Client -Side JavaScript <br>Client -side JavaScript is the most common form of the language. The <br>script should be included in or referenced by an HTML document for the <br>code to be interpreted by the browser. munotes.in</p> </div> <div class="post"> <h2>Page 46</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>46 It means that a web page need not be a static HTML, but can include <br>programs that interact with the user, control the browser, and dynamically <br>create HTML content. <br>The JavaScript client -side mechanism provides many advantages over <br>traditional CGI server -side scripts. F or example, you might use JavaScript <br>to check if the user has entered a valid e -mail address in a form field. <br>The JavaScript code is executed when the user submits the form, and only <br>if all the entries are valid, they would be submitted to the Web Server. <br>JavaScript can be used to trap user -initiated events such as button clicks, <br>link navigation, and other actions that the user initiates explicitly or <br>implicitly. <br>Advantages of JavaScript <br>The merits of using JavaScript are − <br> Less server interaction − You can validate user input before sending <br>the page off to the server. This saves server traffic, which means less <br>load on your server. <br> Immediate feedback to the visitors − They don't have to wait for a <br>page reload to see if they have forgotten to enter something . <br> Increased interactivity − You can create interfaces that react when <br>the user hovers over them with a mouse or activates them via the <br>keyboard. <br> Richer interfaces − You can use JavaScript to include such items as <br>drag-and-drop components and sliders to giv e a Rich Interface to your <br>site visitors. <br>Limitations of JavaScript <br>We cannot treat JavaScript as a full -fledged programming language. It <br>lacks the following important features − <br> Client -side JavaScript does not allow the reading or writing of files. <br>This h as been kept for security reason. <br> JavaScript cannot be used for networking applications because there is <br>no such support available. <br> JavaScript doesn't have any multi -threading or multiprocessor <br>capabilities. <br>3.2 USING JAVASCRIPT IN AN HTML DOCUMENT <br>JavaScript can be implemented using JavaScript statements that are placed <br>within the <script>... </script> HTML tags in a web page. munotes.in</p> </div> <div class="post"> <h2>Page 47</h2> <p> <br> JavaScript <br>47 You can place the <script> tags, containing your JavaScript, anywhere <br>within your web page, but it is normally recommended that you sho uld <br>keep it within the <head> tags. <br>The <script> tag alerts the browser program to start interpreting all the <br>text between these tags as a script. A simple syntax of your JavaScript will <br>appear as follows. <br><script ...> <br>JavaScript code <br></script> <br>The script tag takes two important attributes − <br> Language − This attribute specifies what scripting language you <br>are using. Typically, its value will be javascript. Although recent <br>versions of HTML (and XHTML, its successor) have phased out <br>the use of this attribute. <br> Type − This attribute is what is now recommended to indicate the <br>scripting language in use and its value should be set to <br>"text/javascript". <br>So your JavaScript segment will look like – <br> <br><script language = "javascript" type = "text/javascript"> <br>JavaScript c ode <br></script> <br>Your First JavaScript Code <br>Let us take a sample example to print out "Hello World". We added an <br>optional HTML comment that surrounds our JavaScript code. This is to <br>save our code from a browser that does not support JavaScript. The <br>comment en ds with a "// -->". Here "//" signifies a comment in JavaScript, <br>so we add that to prevent a browser from reading the end of the HTML <br>comment as a piece of JavaScript code. Next, we call a <br>function document.write which writes a string into our HTML document . <br><html> <br><body> <br><script language ="javascript" type="text/javascript" > <br><!-- <br>document .write ("Hello World!" ) <br>//--> <br></script> <br></body> <br></html> <br> munotes.in</p> </div> <div class="post"> <h2>Page 48</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>48 This code will produce the following result − <br>Hello World! <br>Variables can be thought of as named containers. You can pla ce data into <br>these containers and then refer to the data simply by naming the container. <br>Before you use a variable in a JavaScript program, you must declare it. <br>Variables are declared with the var keyword as follows. <br><script type="text/javascript" > <br><!-- <br>var money ; <br>var name ; <br>//--> <br></script> <br>You can also declare multiple variables with the same var keyword as <br>follows − <br><script type="text/javascript" > <br><!-- <br>var money , name ; <br>//--> <br></script> <br>Note − Use the var keyword only for declaration or initialization, once for <br>the life of any variable name in a document. You should not re -declare <br>same variable twic e. <br>JavaScript Variable Scope <br>The scope of a variable is the region of your program in which it is <br>defined. JavaScript variables have only two scopes. <br> Global Variables − A global variable has global scope which <br>means it can be defined anywhere in your JavaS cript code. <br> Local Variables − A local variable will be visible only within a <br>function where it is defined. Function parameters are always local <br>to that function. <br> Within the body of a function, a local variable takes precedence <br>over a global variable with t he same name. If you declare a local <br>variable or function parameter with the same name as a global munotes.in</p> </div> <div class="post"> <h2>Page 49</h2> <p> <br> JavaScript <br>49 variable, you effectively hide the global variable. Take a look into <br>the following example. <br><html> <br><body onload =checkscope ();> <br><script type="text/javascript" > <br><!-- <br>varmyVar ="global" ;// Declare a global variable <br>function checkscope (){ <br>varmyVar ="local" ;// Declare a local variable <br>document .write (myVar ); <br>} <br>//--> <br></script> <br></body> <br></html> <br>JavaScript Variable Names <br>While naming your variables in JavaScript, keep the fo llowing rules in <br>mind. <br> You should not use any of the JavaScript reserved keywords as a <br>variable name. These keywords are mentioned in the next section. <br>For example, break or boolean variable names are not valid. <br> JavaScript variable names should not start w ith a numeral (0 -9). <br>They must begin with a letter or an underscore character. For <br>example, 123test is an invalid variable name but _123test is a valid <br>one. <br> JavaScript variable names are case -sensitive. For example, <br>Name and name are two different variabl es. <br> JavaScript Reserved Words <br> A list of all the reserved words in JavaScript are given in the <br>following table. They cannot be used as JavaScript variables, <br>functions, methods, loop labels, or any object names. <br> <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 50</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>50 abstract else instanceof switch <br>boolean enum int synchronized <br>break export interface this <br>byte extends long throw <br>case false native throws <br>catch final new transient <br>char finally null true <br>class float package try <br>const for private typeof <br>continue function protected var <br>debugger goto public void <br>default if return volatile <br>delete implements short while <br>do import static with <br>double in super <br> <br>JavaScript Operator: <br>JavaScript includes operators same as other languages. An operator <br>performs some operation on single or multiple operands (data value) and <br>produces a result. For example, in 1 + 2 , the + sign is an operator and 1 <br>is left side operand and 2 is right side operand. The + operator performs <br>the addition of two numeric values and returns a result. <br>Syntax: <br><Left operand > operator < right operand > <br><Left operand > operator <br>JavaScript includes following categories of operators. <br>1. Arithmetic Operators <br>2. Comparison Operators <br>3. Logical Operators munotes.in</p> </div> <div class="post"> <h2>Page 51</h2> <p> <br> JavaScript <br>51 4. Assignment Operators <br>5. Conditional Operators <br>6. Ternary Operator <br>Arithmetic Operators <br>Arithmetic operators are used to perform mathematical operations <br>between numeric operands. <br>Operator Description <br>+ Adds two numeric operands. <br>- Subtract right operand fro m left operand <br>* Multiply two numeric operands. <br>/ Divide left operand by right operand. <br>% Modulus operator. Returns remainder of two operands. <br>++ Increment operator. Increase operand value by one. <br>-- Decrement operator. Decrease value by one. <br> <br>The fo llowing example demonstrates how arithmetic operators perform <br>different tasks on operands. <br>Example: Arithmetic Operation <br>var x = 5, y = 10; <br>var z = x + y; //performs addition and returns 15 <br>z = y - x; //performs subtraction and returns 5 <br>z = x * y; //perfo rms multiplication and returns 50 <br>z = y / x; //performs division and returns 2 <br>z = x % 2; //returns division remainder 1 <br>The ++ and -- operators are unary operators. It works with either left or <br>right operand only. When used with the left operand, e.g., x++, it will <br>increase the value of x when the program control goes to the next <br>statement. In the same way, when it is used with the right operand, <br>e.g., ++x, it will increase the value of x there only. Therefore, x++ is <br>called post -increment, and ++x is call ed pre -increment. <br> munotes.in</p> </div> <div class="post"> <h2>Page 52</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>52 Example: Post and Pre Increment/Decrement <br>var x = 5; <br>x++; //post -increment, x will be 5 here and 6 in the next line <br>++x; //pre-increment, x will be 7 here <br>x--; //post -decrement, x will be 7 here and 6 in the next line <br>--x; //pre-decrem ent, x will be 5 here <br>3.3 STRING CONCATENATION <br>The + operator performs concatenation operation when one of the <br>operands is of string type. The following example demonstrates string <br>concatenation even if one of the operands is a string. <br>Example: + Operator with String <br>var a = 5, b = "Hello " , c = "World!" , d = 10; <br>a + b; //returns "5Hello " <br>b + c; //returns "Hello World!" <br>a + d; //returns 15 <br>b + true; //returns "Hello true" <br>c - b; //returns NaN; - operator can only used with numbers <br>Comparison Operators <br>JavaScri pt provides comparison operators that compare two operands <br>and return a boolean value true or false . <br>Operators Description <br>== Compares the equality of two operands without considering type. <br>=== Compares equality of two operands with type. <br>!= Compares in equality of two operands. <br>> Returns a boolean value true if the left -side value is greater than <br>the right -side value; otherwise, returns false. <br>< Returns a boolean value true if the left -side value is less than the <br>right -side value; otherwise, returns fa lse. <br>>= Returns a boolean value true if the left -side value is greater than <br>or equal to the right -side value; otherwise, returns false. <br><= Returns a boolean value true if the left -side value is less than or <br>equal to the right -side value; otherwise, retur ns false. <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 53</h2> <p> <br> JavaScript <br>53 The following example demonstrates the comparison operators. <br>Example: JavaScript Comparison Operators <br>var a = 5, b = 10, c = "5"; <br>var x = a; <br>a == c; // returns true <br>a === c; // returns false <br>a == x; // returns true <br>a != b; // returns true <br>a > b; // returns false <br>a < b; // returns true <br>a >= b; // returns false <br>a <= b; // returns true <br>Logical Operators <br>In JavaScript, the logical operators are used to combine two or more <br>conditions. JavaScript provides the following logical operators. <br>Operator Description <br>&& && is known as AND operator. It checks whether two operands <br>are non -zero or not (0, false, undefined, null or "" are considered <br>as zero). It returns 1 if they are non -zero; otherwise, returns 0. <br>|| || is known as OR operator. It checks whethe r any one of the two <br>operands is non -zero or not (0, false, undefined, null or "" is <br>considered as zero). It returns 1 if any one of of them is non -zero; <br>otherwise, returns 0. <br>! ! is known as NOT operator. It reverses the boolean result of the <br>operand (or condition). !false returns true, and !true returns false . <br>Example: Logical Operators <br>var a = 5, b = 10; <br>(a != b) && (a < b); // returns true <br>(a > b) || (a == b); // returns false <br>(a < b) || (a == b); // returns true <br>!(a < b); // returns false <br>!(a > b); // returns true munotes.in</p> </div> <div class="post"> <h2>Page 54</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>54 Assignment Operators <br>JavaScript provides the assignment operators to assign values to <br>variables with less key strokes. <br>Assignment operators Description <br>= Assigns right operand value to the left operand. <br>+= Sums up left and right operand values and assigns the result to the left operand. <br>-= Subtract right operand value from the left operand value and assigns the result to the left operand. <br>*= Multiply left and right operand values and assigns the result to the left operand. <br>/= Divide left operand value by right operand value and assign the result to the left operand. <br>%= Get the modulus of left operand divide by right operand and assign resulted modulus to the left operand. <br> <br>Example: Assignment operators <br>var x = 5, y = 10, z = 15; <br>x = y; //x would be 10 <br>x += 1; //x would be 6 <br>x -= 1; //x would be 4 <br>x *= 5; //x would be 25 <br>x /= 5; //x would be 1 <br>x %= 2; //x would be 1 <br>Ternary Operator <br>JavaScript provides a special operator called ternary operator :? that <br>assigns a value to a variable based on some condition. This is the short <br>form of the if else condition . <br>Syntax: <br><condition> ? <value1> :<value2>; <br>The ternary operator starts with conditional ex pression followed by <br>the ? operator. The second part (after ? and before :) will be executed if munotes.in</p> </div> <div class="post"> <h2>Page 55</h2> <p> <br> JavaScript <br>55 the condition turns out to be true. Suppose, the condition returns false , <br>then the third part (after :) will be executed. <br>Example: Ternary operator <br>var a = 10, b = 5; <br>var c = a > b? a : b; // value of c would be 10 <br>var d = a > b? b : a; // value of d would be 5 <br>Control Flow Statement: <br>JavaScript supports conditional statements which are used to perform <br>different actions based on different conditions. Here we will explain <br>the if..else statement. <br>Flow Chart of if -else <br>The following flow chart shows how the if -else statement works. <br> <br>JavaScript supports the following forms of if..else statement − <br>JavaScript supports the following forms of if..else statement − <br> if stat ement <br> if...else statement <br> if...else if... statement. <br>if statement <br>The if statement is the fundamental control statement that allows <br>JavaScript to make decisions and execute statements conditionally. munotes.in</p> </div> <div class="post"> <h2>Page 56</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>56 Syntax <br>The syntax for a basic if statement is as follows − <br>if (expression) { <br>Statement(s) to be executed if expression is true <br>} <br>Here a JavaScript expression is evaluated. If the resulting value is true, the <br>given statement(s) are executed. If the expression is false, then no <br>statement would be not executed. Mos t of the times, you will use <br>comparison operators while making decisions. <br>Example <br><html> <br><body> <br><script type="text/javascript" > <br><!-- <br>var age =20; <br> <br>if( age >18){ <br>document .write ("<b>Qualifies for driving</b>" ); <br>} <br>//--> <br></script> <br><p>Set the variable to differe nt value and then try... </p> <br></body> <br></html> <br>Output <br>Qualifies for driving <br>Set the variable to different value and then try... <br>if...else statement <br>The 'if...else' statement is the next form of control statement that allows <br>JavaScript to execute statements i n a more controlled way. <br> munotes.in</p> </div> <div class="post"> <h2>Page 57</h2> <p> <br> JavaScript <br>57 Syntax <br>if (expression) { <br>Statement(s) to be executed if expression is true <br>} else { <br>Statement(s) to be executed if expression is false <br>} <br>Here JavaScript expression is evaluated. If the resulting value is true, the <br>given statement( s) in the ‘if’ block, are executed. If the expression is false, <br>then the given statement(s) in the else block are executed. <br>Example <br>Try the following code to learn how to implement an if -else statement in <br>JavaScript. <br><html> <br><body> <br><script type="text/javascr ipt"> <br><!-- <br>var age =15; <br>if( age >18){ <br>document .write ("<b>Qualifies for driving</b>" ); <br>}else{ <br>document .write ("<b>Does not qualify for driving</b>" ); <br>} <br>//--> <br></script> <br><p>Set the variable to different value and then try... </p> <br></body> <br></html> <br>Output <br>Does not qualify for driving <br>Set the variable to different value and then try... <br>if...else if... statement <br>The if...else if... statement is an advanced form of if…else that allows <br>JavaScript to make a correct decision out of several conditions. munotes.in</p> </div> <div class="post"> <h2>Page 58</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>58 Syntax <br>The syntax o f an if -else-if statement is as follows − <br>if (expression 1) { <br>Statement(s) to be executed if expression 1 is true <br>} else if (expression 2) { <br>Statement(s) to be executed if expression 2 is true <br>} else if (expression 3) { <br>Statement(s) to be executed if expre ssion 3 is true <br>} else { <br>Statement(s) to be executed if no expression is true <br>} <br>There is nothing special about this code. It is just a series of if statements, <br>where each if is a part of the else clause of the previous statement. <br>Statement(s) are executed based on the true condition, if none of the <br>conditions is true, then the else block is executed. <br>Example <br>Try the following code to learn how to implement an if -else-if statement in <br>JavaScript. <br><html> <br><body> <br><script type="text/javascript" > <br><!-- <br>var book ="maths"; <br>if( book =="history" ){ <br>document .write ("<b>History Book</b>" ); <br>}elseif ( book =="maths" ){ <br>document .write ("<b>Maths Book</b>" ); <br>}elseif ( book =="economics" ){ <br>document .write ("<b>Economics Book</b>" ); <br>}else{ <br>document .write ("<b>Unknown Book</b>" ); munotes.in</p> </div> <div class="post"> <h2>Page 59</h2> <p> <br> JavaScript <br>59 } <br>//--> <br></script> <br><p>Set the variable to different value and then try... </p> <br></body> <br><html> <br>Output <br>3.4 MATHS BOOK <br>Set the variable to different value and then try. <br>Flow Chart <br>The following flow chart explains a switch -case statement works. <br> <br>Syntax <br>The objective of a switch statement is to give an expression to evaluate <br>and several different statements to execute based on the value of the <br>expression. The interpreter checks each case against the value of the <br>expression until a match is found. If nothing matches, a default condition <br>will be used. munotes.in</p> </div> <div class="post"> <h2>Page 60</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>60 switch (expression) { <br>case condition 1: statement(s) <br>break; <br>case condition 2: statement(s) <br>break; <br>... <br>case condition n: statement(s) <br>break; <br>default: statement(s) <br>} <br>The break statements indicate the end of a particular case. If they were <br>omitted, the interpreter would continue executing each statement in each <br>of the following cases. <br>We will explain break statement in Loop Control chapter. <br>Example <br>Try the following example to implement switch -case statement. <br><html> <br><body> <br><script type="text/javascript" > <br><!-- <br>var grade ='A'; <br>document .write ("Entering switch block<br />" ); <br>switch (grade ){ <br>case'A':document .write ("Good job<br />" ); <br>break ; <br>case'B':document .write ("Pretty good<br />" ); <br>break ; <br>case'C':document .write ("Passed<br />" ); <br>break ; <br> munotes.in</p> </div> <div class="post"> <h2>Page 61</h2> <p> <br> JavaScript <br>61 case'D':document .write ("Not so good<br />" ); <br>break ; <br>case'F':document .write ("Failed<br />" ); <br>break ; <br>default :document .write ("Unknown grade<br />" ) <br>} <br>document .write ("Exiting switch block" ); <br>//--> <br></script> <br><p>Set the variable to different value and then tr y...</p> <br></body> <br></html> <br>Output <br>Entering switch block <br>Good job <br>Exiting switch block <br>Set the variable to different value and then try... <br>Break statements play a major role in switch -case statements. Try the <br>following code that uses switch -case statement wit hout any break <br>statement. <br><html> <br><body> <br><script type="text/javascript" > <br><!-- <br>var grade ='A'; <br>document .write ("Entering switch block<br />" ); <br>switch (grade ){ <br>case'A':document .write ("Good job<br />" ); <br>case'B':document .write ("Pretty good<br />" ); <br>case'C':docum ent.write ("Passed<br />" ); munotes.in</p> </div> <div class="post"> <h2>Page 62</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>62 case'D':document .write ("Not so good<br />" ); <br>case'F':document .write ("Failed<br />" ); <br>default :document .write ("Unknown grade<br />" ) <br>} <br>document .write ("Exiting switch block" ); <br>//--> <br></script> <br><p>Set the variable to different value a nd then try... </p> <br></body> <br></html> <br>Output <br>Entering switch block <br>Good job <br>Pretty good <br>Passed <br>Not so good <br>Failed <br>Unknown grade <br>Exiting switch block <br>Set the variable to different value and then try... <br>3.5 JAVASCRIPT LOOPING STATEMENTS: <br>Very often when you write code, you want the same block of code to run a <br>number of times. You can use looping statements in you code to do this. <br>1. While statement <br>2. do…while statement <br>3. for statement <br>1. while statement: <br>The purpose of a while loop is to execute a statement or code <br>block rep eatedly as long as an expression is true. Once the <br>expression becomes false, the loop terminates. munotes.in</p> </div> <div class="post"> <h2>Page 63</h2> <p> <br> JavaScript <br>63 Flow Chart <br>The flow chart of while loop looks as follows − <br> <br>Syntax <br>The syntax of while loop in JavaScript is as follows − <br>while (expression) { <br>Statement(s ) to be executed if expression is true <br>} <br>Example <br><html> <br><body> <br><h2>JavaScript While Loop</h2> <br><p id="demo"></p> <br><script> <br>let text = ""; <br>leti = 0; <br>while (i< 10) { <br>text += "<br>The number is " + i; <br>i++; <br>} munotes.in</p> </div> <div class="post"> <h2>Page 64</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>64 document.getElementById("demo").innerHTML = text; <br></script> <br></body> <br></html> <br>OUTPUT: <br>JavaScript While Loop <br> <br>The number is 0 <br>The number is 1 <br>The number is 2 <br>The number is 3 <br>The number is 4 <br>The number is 5 <br>The number is 6 <br>The number is 7 <br>The number is 8 <br>The number is 9 <br>The do...while Loop <br>The do...while loop is similar to the while loop except that the condition <br>check happens at the end of the loop. This means that the loop will always <br>be executed at least once, even if the condition is false . <br>Flow Chart <br>The flow chart of a do-while loop would be as follows − <br> <br> <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 65</h2> <p> <br> JavaScript <br>65 Syntax <br>The syntax for do-while loop in JavaScript is as follows − <br>do { <br>Statement(s) to be executed; <br>} while (expression); <br><html> <br><body> <br><h2>JavaScript Do While Loop</h2> <br><p id="demo"></p> <br><script> <br>let text = "" <br>leti = 0; <br>do { <br>text += "<br>The number is " + i; <br>i++; <br>} <br>while (i< 10); <br>document.getElementById("demo").innerHTML = text; <br></script> <br></body> <br></html> <br>for loop: <br>The ' for' loop is the most compact form of looping. It includes the <br>following three important parts − <br> The loop initialization where we initia lize our counter to a starting <br>value. The initialization statement is executed before the loop <br>begins. <br> The test statement which will test if a given condition is true or <br>not. If the condition is true, then the code given inside the loop will <br>be executed, o therwise the control will come out of the loop. <br> The iteration statement where you can increase or decrease your <br>counter. <br> munotes.in</p> </div> <div class="post"> <h2>Page 66</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>66 Flow Chart <br>The flow chart of a for loop in JavaScript would be as follows − <br> <br>Syntax <br>The syntax of for loop is JavaScript is as follows − <br>for (initialization; test condition; iteration statement) <br>{ <br>Statement(s) to be executed if test condition is true <br>} <br><html> <br><head></head> <br><title>for loop</tit le> <br><body> <br><script type=”text/javascript”> <br>vari; <br>for(i=1;i<=10;i++) <br>{ <br>document.write(i); <br>} <br></script> <br></body> <br></html> munotes.in</p> </div> <div class="post"> <h2>Page 67</h2> <p> <br> JavaScript <br>67 Working with JavaScript jump statements: <br>The break statement "jumps out" of a loop. <br>The continue statement "jumps over" one iteration in th e loop. <br>You have already seen the break statement used in an earlier chapter of <br>this tutorial. It was used to "jump out" of a switch() statement. <br>The break statement can also be used to jump out of a loop. <br>The break statement breaks the loop and continue s executing the code <br>after the loop (if any): <br><html> <br><body> <br><p>A loop with a break.</p> <br><p id="demo"></p> <br><script> <br>var text = ""; <br>vari; <br>for (i = 0; i< 10; i++) <br> { <br>if (i === 3) <br>{ <br>break; <br>} <br>text += "The number is " + i + "<br>"; <br>} <br>document.getElementById(" demo").innerHTML = text; <br></script> <br> <br></body> <br></html> <br>A loop with a break. munotes.in</p> </div> <div class="post"> <h2>Page 68</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>68 The number is 0 <br>The number is 1 <br>The number is 2 <br>The Continue Statement <br>The continue statement breaks one iteration (in the loop), if a specified <br>condition occurs, and continues with t he next iteration in the loop. <br>This example skips the value of 3: <br><html> <br><body> <br><p>A loop which will skip the step where i = 3.</p> <br><p id="demo"></p> <br><script> <br>var text = ""; <br>vari; <br>for (i = 0; i< 10; i++) { <br>if (i === 3) { continue; } <br>text += "The number is " + i + "<br>"; <br>} <br>document.getElementById("demo").innerHTML = text; <br></script> <br></body> <br></html> <br>A loop which will skip the step where i = 3. <br>The number is 0 <br>The number is 1 <br>The number is 2 <br>The number is 4 <br>The number is 5 <br>The number is 6 <br>The number is 7 <br>The number is 8 <br>The number is 9 <br>javaScript Popup Boxes: munotes.in</p> </div> <div class="post"> <h2>Page 69</h2> <p> <br> JavaScript <br>69 JavaScript Message Boxes: alert(), confirm(), prompt() <br>Alert Box <br>An alert box is often used if you want to make sure information comes <br>through to the user. <br>When an alert box pops up, the user will have to click "OK" to proceed <br>Syntax <br>window.alert(" sometext "); <br>The window.alert() method can be written without the window prefix. <br><html> <br><head> <br><script type="text/javascript" > <br><!-- <br>function Warn (){ <br>alert("This is a warning message!" ); <br>document .write ("This is a w arning message!" ); <br>} <br>//--> <br></script> <br></head> <br> <br><body> <br><p>Click the following button to see the result: </p> <br><form> <br><input type="button" value ="Click Me" onclick ="Warn ();"/> <br></form> <br></body> <br></html> <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 70</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>70 Output <br> <br> <br>3.6 CONFIRMATION DIALOG BOX <br>A confirmation d ialog box is mostly used to take user's consent on any <br>option. It displays a dialog box with two buttons: OK and Cancel . <br>If the user clicks on the OK button, the window method confirm() will <br>return true. If the user clicks on the Cancel button, then confir m() returns <br>false. You can use a confirmation dialog box as follows. <br><html> <br><head> <br><script type="text/javascript" > <br><!-- <br>function getConfirmation (){ <br>varretVal = confirm ("Do you want to continue ?" ); <br>if(retVal ==true){ <br>document .write ("User wants to continue!" ); <br>returntrue ; <br>}else{ <br>document .write ("User does not want to continue!" ); <br>returnfalse ; <br>} <br>} <br>//--> <br></script> <br></head> <br> <br><body> munotes.in</p> </div> <div class="post"> <h2>Page 71</h2> <p> <br> JavaScript <br>71 <p>Click the following button to see the result: </p> <br><form> <br><input type="button" value ="Click Me" onclick ="getConfirmation ();"/> <br></form> <br></body> <br></html> <br> <br> <br> <br> <br> <br>Prompt Dialog Box <br>The prompt dialog box is very useful when you want to pop -up a text box <br>to get user input. Thus, it enables you to interact with the user. The user <br>needs to fill in the field and then click OK. <br>This dialog box is dis played using a method called prompt() which takes <br>two parameters: (i) a label which you want to display in the text box and <br>(ii) a default string to display in the text box. <br>This dialog box has two buttons: OK and Cancel . If the user clicks the <br>OK button, the window method prompt() will return the entered value <br>from the text box. If the user clicks the Cancel button, the window <br>method prompt() returns null. munotes.in</p> </div> <div class="post"> <h2>Page 72</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>72 <html> <br><head> <br><script type="text/javascript" > <br><!-- <br>function getValue (){ <br>varretVal = prompt ("Enter your n ame : " ,"your name here" ); <br>document .write ("You have entered : " +retVal ); <br>} <br>//--> <br></script> <br></head> <br> <br><body> <br><p>Click the following button to see the result: </p> <br><form> <br><input type="button" value ="Click Me" onclick ="getValue ();"/> <br></form> <br></body> <br></html> <br> <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 73</h2> <p> <br> JavaScript <br>73 <br> <br> <br> <br>JavaScript Functions <br>JavaScript functions are used to perform operations. We can call <br>JavaScript function many times to reuse the code. <br>Advantage of JavaScript function <br>There are mainly two advantages of JavaScript functions. <br>1. Code reusability : We can c all a function several times so it save <br>coding. <br>2. Less coding : It makes our program compact. We don’t need to <br>write many lines of code each time to perform a common task <br>Defining and invoking a JavaScript Function <br>JavaScript Function Syntax <br>The syntax of dec laring function is given below. <br>function functionName([arg1, arg2, ...argN]) <br>{ <br> //code to be executed <br>} <br>JavaScript Functions can have 0 or more arguments. <br><html> munotes.in</p> </div> <div class="post"> <h2>Page 74</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>74 <body> <br><script> <br>functionmsg(){ <br>alert("hello! this is message"); <br>} <br></script> <br><input type="button" onclick="msg()" value="call function"/> <br></body> <br></html> <br> <br> <br> <br> <br>JavaScript Function Arguments <br> munotes.in</p> </div> <div class="post"> <h2>Page 75</h2> <p> <br> JavaScript <br>75 <br> <br>Function with Return Value <br>We can call function that returns a value and use it in our program. Let’s <br>see the example of function that returns valu e. <br><html> <br><body> <br><script> <br>functiongetInfo(){ <br>return "hello How r u?"; <br>} </script> <br><script> <br>document.write(getInfo()); <br></script> <br></body> <br></html> <br> <br>JavaScript timer <br>In JavaScript, a timer is created to execute a task or any function at a <br>particular t ime. Basically, the timer is used to delay the execution of the <br>program or to execute the JavaScript code in a regular time interval. With <br>the help of timer, we can delay the execution of the code. So, the code munotes.in</p> </div> <div class="post"> <h2>Page 76</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>76 does not complete it's execution at the same time when an event triggers or <br>page loads. <br>The best example of the timer is advertisement banners on websites, which <br>change after every 2 -3 seconds. These advertising banners are changed at <br>a regular interval on the websites like Amazon. We set a time inte rval to <br>change them. In this chapter, we will show you how to create a timer. <br>JavaScript <br>offers two timer functions setInterval() and setTimeout() , which helps to <br>delay in execution of code and also allows to perform one or more <br>operations repeatedly. We will discuss both the timer functions in detail as <br>well as their examples. <br>setTimeout() <br>The setTimeout() function helps the users to delay the execution of code. <br>The setTimeout() method accepts two parameters in which one is a user -<br>defined function, and another is the time parameter to delay the execution. <br>The time parameter holds the time in milliseconds (1 second = 1000 <br>milliseconds), which is optional to pass. <br>The basic syntax of setTimeout() is: <br>1. setTimeout(function, milliseconds) <br>We will use the setTimeout() function to delay the printing of message for <br>3 seconds. The message will display on the web after 3 seconds of code <br>execution rather than immediately. Now, let's look at the code below to <br>see how it works: <br>3.7 EXECUTION OF CODE AFTER A DELAY <br><html> <br><body> <br><script> <br>Function d elay Function() { <br> //display the message on web after 3 seconds on calling delay Function <br>document.write('<h3> Welcome to JavaScript <h3>'); <br>} <br></script> <br><h4> Exam ple of delay the execution of function <h4> <br> munotes.in</p> </div> <div class="post"> <h2>Page 77</h2> <p> <br> JavaScript <br>77 <!?button for calling of user -defined delay Function having 3 seconds of <br>delay --> <br><button onclick = "set Timeout (delay Function, 3000)"> Click Here <br></button> <br></body> <br></html> <br>Output <br>The above code will execute in t wo sections. Firstly, the HTML part of the <br>code will execute, where by clicking on Click Here button the remaining <br>JavaScript code will execute after 3 seconds. See the output below: <br> <br>On clicking the Click Here button, the remaining code will execute aft er 3 <br>seconds. A message Welcome to JavaScript will display on the web after <br>3 seconds (3000 milliseconds). <br> <br>setInterval() <br>The setInterval method is a bit similar to the setTimeout() function. It <br>executes the specified function repeatedly after a time inte rval. Or we can <br>simply say that a function is executed repeatedly after a specific amount of <br>time provided by the user in this function. For example - Display updated <br>time in every five seconds. <br> munotes.in</p> </div> <div class="post"> <h2>Page 78</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>78 The basic syntax of setInterval() is: <br>setInterval(function, milliseconds) <br>Similar to setTimeout() method, it also accepts two parameters in which <br>one is a user -defined function, and another is a time -interval parameter to <br>wait before executing the function. The time -interval parameter holds the <br>amount of time in m illiseconds (1 second = 1000 milliseconds), which is <br>optional to pass. Now, see the code below how this function works: <br>Execution of code at a regular interval <br><html> <br><body> <br><script> <br>function waitAndshow() { <br> //define a date and time variable <br> var systemdate = new Date(); <br> //display the updated time after every 4 seconds <br> document.getElementById("clock") .innerHTML = systemdate .toLoca<br>leTimeString(); <br>} <br> //define time interval and call user-defined waitAnd show function <br> setInterval(waitAndshow, 4000); <br></script> <br> <h3> Updated time will show in every 4 seconds </h3> <br><h3> The current time on your computer is: <br> <br><span id="clock" ></span> </h3> <br></body> <br></html> <br> munotes.in</p> </div> <div class="post"> <h2>Page 79</h2> <p> <br> JavaScript <br>79 Cancel or Stop the timer <br>JavaScript offers two functions clear Timeout() and clear Interval() to <br>cancel or stop the timer and halt the execution of code. The set Timeout() <br>and set Interval() both return a unique IDs. These IDs are used by the clear <br>Timeout() and clear Interval() to cle ar the timer and stop the code <br>execution beforehand. They both take only one parameter, i.e., ID. <br>Example <br>In this example, we will use clear Timeout() to clear the timer set by with <br>set Timeout() function. Look at the example how clear Interval() work <br>with se t Interval(). <br>Disable the regular interval <br><html> <br><body> <br><script> <br>function waitAndshow() { <br> //define a date and time variable <br> var systemdate = new Date(); <br> //display the updated time after every 4 seconds <br> document.getElementById("c lock") .innerHTML = systemdate .toLocaleT<br>imeString(); <br>} <br> //function to disable the time interval <br>function stopClock() { <br> clearInterval(intervalID); <br>} <br> //define time interval and call user-defined waitAndshow function <br>var intervalID = setInterval (waitAndshow, 3000); <br></script> <br> <p>Current system time: <span id="clock" > </span> </p> <br> <!-- button to stop showing time in a regular interval --> <br><button onclick = "stopClock();" > Stop Clock </button> <br></body> <br></html> munotes.in</p> </div> <div class="post"> <h2>Page 80</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>80 <br> <br>3.8 JAVASCRIPT OBJECTS <br>A javaScript object is an entity having state and behavior (properties and <br>method). For example: car, pen, bike, chair, glass, keyboard, monitor etc. <br>JavaScript is an object -based language. Everything is an object in <br>JavaScript. <br>JavaScript is temp late based not class based. Here, we don't create class to <br>get the object. But, we direct create objects. <br>Creating Objects in JavaScript <br>There are 3 ways to create objects. <br>1. By object literal <br>2. By creating instance of Object directly (using new keyword) <br>3. By us ing an object constructor (using new keyword) <br>1)JavaScript Object by object literal <br>The syntax of creating object using object literal is given below: <br>object ={property1:value1,property2:value2.....propertyN:valueN} <br>As you can see, property and value is s eparated by : (colon). <br>Let’s see the simple example of creating object in JavaScript. <br><html> <br><body> <br><script> <br>emp={id:102,name:"Shyam Kumar",salary:40000} <br>document.write(emp.id+" "+emp.name+" "+emp.salary); <br></script> <br></body> munotes.in</p> </div> <div class="post"> <h2>Page 81</h2> <p> <br> JavaScript <br>81 </html> <br>Output: <br>102 Shyam Ku mar 40000 <br>2) By creating instance of Object <br>The syntax of creating object directly is given below: <br>var objectname =new Object(); <br><html> <br><body> <br><script> <br>varemp=new Object(); <br>emp.id=101; <br>emp.name="Ravi Malik"; <br>emp.salary=50000; <br>document.write(emp.id+" "+emp.name+" "+emp.salary); <br></script> <br></body> <br></html> <br>101 Ravi Malik 50000 <br>3) By using an Object constructor <br>Here, you need to create function with arguments. Each argument value <br>can be assigned in the current object by using this keyword. <br><html> <br><body> <br><script> <br>functionemp(id,name,salary){ <br>this.id=id; <br>this.name=name; <br>this.salary=salary; <br>} <br>e=new emp(103,"Vimal Jaiswal",30000); munotes.in</p> </div> <div class="post"> <h2>Page 82</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>82 document.write(e.id+" "+e.name+" "+e.salary); <br></script> <br></body> <br></html> <br>OUTPUT: <br>103 Vimal Jaiswal 30000 <br>JavaScript String Methods: <br>String Methods <br>Method Description <br>charAt(position) Returns the character at the specified position (in Number). <br>charCodeAt(position) Returns a number indicating the Unicode val ue <br>of the character at the given position (in <br>Number). <br>concat([string,,]) Joins specified string literal values (specify <br>multiple strings separated by comma) and <br>returns a new string. <br>indexOf(SearchString, Position) Returns the index of first occurrence of specified String starting from specified number index. <br>Returns -1 if not found. <br>lastIndexOf(SearchString, <br>Position) Returns the last occurrence index of specified <br>SearchString, starting from specified position. <br>Returns -1 if not found. <br>localeCompare(s tring,position) Compares two strings in the current locale. <br>match(RegExp) Search a string for a match using specified <br>regular expression. Returns a matching array. <br>replace(searchValue, <br>replaceValue) Search specified string value and replace with <br>specifie d replace Value string and return new <br>string. Regular expression can also be used as <br>searchValue. <br>search(RegExp) Search for a match based on specified regular <br>expression. <br>slice(startNumber, endNumber) Extracts a section of a string based on specified <br>starting and ending index and returns a new <br>string. <br> <br>split(separatorString, Splits a String into an array of strings by munotes.in</p> </div> <div class="post"> <h2>Page 83</h2> <p> <br> JavaScript <br>83 Method Description <br>limitNumber) separating the string into substrings based on <br>specified separator. Regular expression can also <br>be used as separator. <br>substr (start, length) Returns the characters in a string from specified starting position through the specified number of characters (length). <br>substring(start, end) Returns the characters in a string between start <br>and end indexes. <br>toLocaleLowerCase() Converts a string to lower case according to <br>current locale. <br>toLocaleUpperCase() Converts a sting to upper case according to <br>current locale. <br>toLowerCase() Returns lower case string value. <br>toString() Returns the value of String object. <br>toUpperCase() Returns uppe r case string value. <br>valueOf() Returns the primitive value of the specified <br>string object. <br> <br>RegExp Object <br>A regular expression is an object that describes a pattern of characters. <br>The JavaScript RegExp class represents regular expressions, and both <br>Strin g and RegExp define methods that use regular expressions to perform <br>powerful pattern -matching and search -and-replace functions on text. <br>Syntax <br>A regular expression could be defined with the RegExp () constructor, as <br>follows − <br>var pattern = new RegExp(pattern, attributes); <br>or simply <br>var pattern = /pattern/attributes; <br>Here is the description of the parameters − <br> pattern − A string that specifies the pattern of the regular <br>expression or another regular ex pression. <br> attributes − An optional string containing any of the "g", "i", and <br>"m" attributes that specify global, case -insensitive, and multi -line <br>matches, respectively. munotes.in</p> </div> <div class="post"> <h2>Page 84</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>84 Brackets <br>Brackets ([]) have a special meaning when used in the context of regular <br>expressions. They are used to find a range of characters. <br>Sr.No. Expression & Description <br>1 [...] <br>Any one character between the brackets. <br>2 [^...] <br>Any one character not between the brackets. <br>3 [0-9] <br>It matches any decimal digit from 0 through 9. <br>4 [a-z] <br>It matches any character from lowercase a through lowercase z. <br>5 [A-Z] <br>It matches any character from uppercase A through uppercase Z. <br>6 [a-Z] <br>It matches any character from lowercase a through uppercase Z. <br>The ranges shown above are general; you could also use the range [0 -3] to <br>match any decimal digit ranging from 0 through 3, or the range [b -v] to <br>match any lowercase character ranging from b through v. <br>Quantifiers <br>The frequency or position of bracketed character sequences and single <br>characters can be deno ted by a special character. Each special character <br>has a specific connotation. The +, *, ?, and $ flags all follow a character <br>sequence. <br> <br> <br> <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 85</h2> <p> <br> JavaScript <br>85 Sr.No. Expression & Description <br>1 p+ <br>It matches any string containing one or more p's. <br>2 p* <br>It matches any string containing zero or more p's. <br>3 p? <br>It matches any string containing at most one p. <br>4 p{N} <br>It matches any string containing a sequence of N p's <br>5 p{2,3} <br>It matches any string containing a sequence of two or three <br>p's. <br>6 p{2, } <br>It matches any string conta ining a sequence of at least two p's. <br>7 p$ <br>It matches any string with p at the end of it. <br>8 ^p <br>It matches any string with p at the beginning of it. <br>Examples <br>Following examples explain more about matching characters. <br>Sr.No. Expression & Description <br>1 [^a-zA-Z] <br>It matches any string not containing any of the characters ranging <br>from a through z and A through Z. <br>2 p.p <br>It matches any string containing p, followed by any character, in <br>turn followed by another p. munotes.in</p> </div> <div class="post"> <h2>Page 86</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>86 3 ^.{2}$ <br>It matches any string containing exa ctly two characters. <br>4 <b>(.*)</b> <br>It matches any string enclosed within <b> and </b>. <br>5 p(hp)* <br>It matches any string containing a p followed by zero or more <br>instances of the sequence hp. <br>Literal characters <br>Sr.No. Character & Description <br>1 Alphanumeric <br>Itself <br>2 \0 <br>The NUL character ( \u0000) <br>3 \t <br>Tab ( \u0009 <br>4 \n <br>Newline ( \u000A) <br>5 \v <br>Vertical tab ( \u000B) <br>6 \f <br>Form feed ( \u000C) <br>7 \r <br>Carriage return ( \u000D) <br>8 \xnn <br>The Latin character specified by the hexadecimal number nn; for <br>example, \x0A is t he same as \n <br>9 \uxxxx <br>The Unicode character specified by the hexadecimal number xxxx; <br>for example, \u0009 is the same as \t <br>10 \cX <br>The control character ^X; for example, \cJ is equivalent to the <br>newline character \n munotes.in</p> </div> <div class="post"> <h2>Page 87</h2> <p> <br> JavaScript <br>87 Met characters <br>A metacharacter is si mply an alphabetical character preceded by a <br>backslash that acts to give the combination a special meaning. <br>For instance, you can search for a large sum of money using the ' \d' <br>metacharacter: /([\d]+)000/ , Here \d will search for any string of <br>numerical ch aracter. <br>The following table lists a set of metacharacters which can be used in <br>PERL Style Regular Expressions. <br>Sr.No. Character & Description <br>1 . <br>a single character <br>2 \s <br>a whitespace character (space, tab, newline) <br>3 \S <br>non-whitespace character <br>4 \d <br>a digit (0 -9) <br>5 \D <br>a non -digit <br>6 \w <br>a word character (a -z, A-Z, 0-9, _) <br>7 \W <br>a non -word character <br>8 [\b] <br>a literal backspace (special case). <br>9 [aeiou] <br>matches a single character in the given set <br>10 [^aeiou] <br>matches a single character outside the given set <br>11 (foo|bar|baz) <br>matches any of the alternatives specified <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 88</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>88 Modifiers <br>Several modifiers are available that can simplify the way you work <br>with regexps, like case sensitivity, searching in multiple lines, etc. <br>Sr.No. Modifier & Description <br>1 i <br>Perform case-insensitive matching. <br>2 m <br>Specifies that if the string has newline or carriage return <br>characters, the ^ and $ operators will now match against a <br>newline boundary, instead of a string boundary <br>3 g <br>Performs a global matchthat is, find all matches rat her than <br>stopping after the first match. <br> <br>RegExp Properties <br>Here is a list of the properties associated with RegExp and their <br>description. <br>Sr.No. Property & Description <br>1 constr uctor <br>Specifies the function that creates an object's prototype. <br>2 global <br>Specifies if the "g" modifier is set. <br>3 ignoreCase <br>Specifies if the "i" modifier is set. <br>4 lastIndex <br>The index at which to start the next match. <br>5 multiline <br>Specifies if the "m" modifier is set. <br>6 source <br>The text of the pattern. <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 89</h2> <p> <br> JavaScript <br>89 In the following sections, we will have a few examples to demonstrate the <br>usage of RegExp properties. <br>RegExp Methods <br>Here is a list of the methods associated with RegExp along with their <br>description. <br>Sr.No. Method & Description <br>1 exec() <br>Executes a search for a match in its string parameter. <br>2 test() <br>Tests for a match in its string parameter. <br>3 toSource() <br>Returns an object literal representing the specified object; you <br>can use this value to create a new object. <br>4 toString() <br>Returns a string representing the specified object. <br>In the followin g sections, we will have a few examples to demonstrate the <br>usage of RegExp methods. <br>The math object provides you properties and methods for mathematical <br>constants and functions. Unlike other global objects, Math is not a <br>constructor. All the properties an d methods of Math are static and can be <br>called by using Math as an object without creating it. <br>Thus, you refer to the constant pi as Math.PI and you call <br>the sine function as Math.sin(x) , where x is the method's argument. <br>Syntax <br>The syntax to call the prop erties and methods of Math are as follows <br>varpi_val = Math.PI; <br>varsine_val = Math.sin(30); <br>Math Properties <br>Here is a list of all the properties of Math and their description. <br> <br> <br> <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 90</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>90 Sr.No. Property & Description <br>1 E \ <br>Euler's constant and the base of natural logarithms, approximately <br>2.718. <br>2 LN2 <br>Natural logarithm of 2, approximately 0.693. <br>3 LN10 <br>Natural logarithm of 10, approximately 2.302. <br>4 LOG2E <br>Base 2 logarithm of E, approximately 1.442. <br>5 LOG10E <br>Base 10 logarithm of E, approximately 0.434. <br>6 PI <br>Ratio of the circumference of a circle to its diameter, approximately <br>3.14159. <br>7 SQRT1_2 <br>Square root of 1/2; equivalently, 1 over the square root of 2, <br>approximately 0.707. <br>8 SQRT2 <br>Square root of 2, approxi mately 1.414. <br>In the following sections, we will have a few examples to demonstrate the <br>usage of Math properties. <br>Math Methods <br>Here is a list of the methods associated with Math object and their <br>description <br>Sr.No. Method & Description <br>1 abs() <br>Returns the absolute value of a number. <br>2 acos() <br>Returns the arccosine (in radians) of a number. <br>3 asin() <br>Returns the arcsine (in radians) of a number. <br>4 atan() <br>Returns the arctangent (in radians) of a number. munotes.in</p> </div> <div class="post"> <h2>Page 91</h2> <p> <br> JavaScript <br>91 5 atan2() <br>Returns the arctangent of the quotient of its arguments. <br>6 ceil() <br>Returns the smallest integer greater than or equal to a number. <br>7 cos() <br>Returns the cosine of a number. <br>8 exp() <br>Returns EN, where N is the argument, and E is Euler's constant, <br>the base of the natural logarithm. <br>9 floor() <br>Returns the largest integer less than or equal to a number. <br>10 log() <br>Returns the natural logarithm (base E) of a number. <br>11 max() <br>Returns the largest of zero or more numbers. <br>12 min() <br>Returns t he smallest of zero or more numbers. <br>13 pow() <br>Returns base to the exponent power, that is, base exponent. <br>14 rando m() <br>Returns a pseudo -random number between 0 and 1. <br>15 round() <br>Returns the value of a number rounded to the nearest integer. <br>16 sin() <br>Returns the sine of a number. <br>17 sqrt() <br>Returns the square root of a number. <br>18 tan() <br>Returns the tangent of a number. <br>19 toSource() <br>Returns the string "Math". <br> <br>The math object provides you properties and methods for mathematical <br>constants and functions. Unlike other global objects, Math is not a munotes.in</p> </div> <div class="post"> <h2>Page 92</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>92 constructor. All the properties and methods of Math are static and can be <br>called by using Math as an object without creating it. <br>Thus, you refer to the constant pi as Math.PI and you call <br>the sine function as Math.sin(x) , where x is the method's argument. <br>Syntax <br>The syntax to call the properties and methods of Math are as follows <br>varpi_val = Math.PI; <br>varsine_val = Math.sin(30); <br>Math Properties <br>Here is a list of all the properties of Math and their description. <br>Sr.No. Property & Descr iption <br>1 E \ <br>Euler's constant and the base of natural logarithms, approximately <br>2.718. <br>2 LN2 <br>Natural logarithm of 2, a pproximately 0.693. <br>3 LN10 <br>Natural logarithm of 10, approximately 2.302. <br>4 LOG2E <br>Base 2 logarithm of E, approxima tely 1.442. <br>5 LOG10E <br>Base 10 logarithm of E, approximately 0.434. <br>6 PI <br>Ratio of the circumference of a circle to i ts diameter, <br>approximately 3.14159. <br>7 SQRT1_2 <br>Square root of 1/2; equivalently, 1 over the square root of 2, <br>approximately 0.707. <br>8 SQRT2 <br>Square root of 2, approximately 1.414. <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 93</h2> <p> <br> JavaScript <br>93 JavaScript Date Object <br>Methods Description <br>getDate() It returns the integer value between 1 and 31 that <br>represent s the day for the specified date on the basis <br>of local time. <br>getDay() It returns the integer value between 0 and 6 that <br>represents the day of the week on the basis of local <br>time. <br>getFullYears() It returns the integer value that represents the year on <br>the basis of local time. <br>getHours() It returns the integer value between 0 and 23 that <br>represents the hours on the basis of local time. <br>getMilliseconds() It returns the integer value between 0 and 999 that <br>represents the milliseconds on the basis of local time. <br>getMinutes() It returns the integer value between 0 and 59 that <br>represents the minutes on the basis of local time. <br>getMonth() It returns the integer value between 0 and 11 that <br>represents the month on the basis of local time. <br>getSecond s() It returns the integer value between 0 and 60 that <br>represents the seconds on the basis of local time. <br>getUTCDate() It returns the integer value between 1 and 31 that <br>represent s the day for the specified date on the basis <br>of universal time. <br>getUTCDay() It returns the integer value between 0 and 6 that <br>represents the day of the week on the basis of <br>univers al time. <br>getUTCFullYears() It returns the integer value that represents the year on <br>the basis of universal time. <br>getUTCHours() It returns the integer value between 0 and 23 that <br>represents the hours on the basis of universal time. <br>getUTCMinutes() It returns the integer value between 0 and 59 that <br>represents the minutes on the basis of universal time. <br>getUTCMonth() It returns the integer value between 0 and 11 that <br>represents the month on the basis of universal time. munotes.in</p> </div> <div class="post"> <h2>Page 94</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>94 getUTCSeconds() It returns the integer value between 0 and 60 that <br>represents the seconds on the basis of universal time. <br>setDate() It sets the day value for t he specified date on the <br>basis of local time. <br>setDay() It sets the particular day of the week on the basis of <br>local time. <br>setFullYears() It sets the year value for the specified date on the <br>basis of local time. <br>setHours() It sets the hour value for the specified date on the <br>basis of local time. <br>setMilliseconds() It sets the millisecond value for the spe cified date on <br>the basis of local time. <br>setMinutes() It sets the minute value for the specified date on the <br>basis of local time. <br>setMonth() It sets the month value for the specifi ed date on the <br>basis of local time. <br>setSeconds() It sets the second value for the specified date on the <br>basis of local time. <br>setUTCDate() It sets the day value for the specified date on the <br>basis of universal time. <br>setUTCDay() It sets the particular day of the week on the basis of <br>universal time. <br>setUTCFullYears() It sets the year value for the specified date on the <br>basis of universal time. <br>setUTCHours() It sets the hour value for the specified date on t he <br>basis of universal time. <br>setUTCMilliseconds() It sets the millisecond value for the specified date on <br>the basis of universal time. <br>setUTCMinutes() It sets the minute value f or the specified date on the <br>basis of universal time. <br>setUTCMonth() It sets the month value for the specified date on the <br>basis of universal time. <br>setUTCSeconds() It sets the second value for the specified date on the <br>basis of universal time. munotes.in</p> </div> <div class="post"> <h2>Page 95</h2> <p> <br> JavaScript <br>95 toDateString() It returns the date portion of a Date object. <br>toISOString() It returns the date in the form ISO format string. <br>toJSON() It retu rns a string representing the Date object. It also <br>serializes the Date object during JSON serialization. <br>toString() It returns the date in the form of string. <br>toTimeString() It returns the time portion of a Date object. <br>toUTCString() It converts the specified date in the form of str ing <br>using UTC time zone. <br>valueOf() It returns the primitive value of a Date object. <br> <br>3.9 BROWSER OBJECT MODEL <br>1. Browser Object Model (BOM) <br>The Browser Object Model (BOM) is used to interact with the browser. <br>The default object of browser is window means you can call all the <br>functions of window by specifying window or directly. For example: <br>1. window.alert("hello javatpoint"); <br>is same as: <br>1. alert("hello javatpoint"); <br> <br>Fig: JavaScript’s Window Object <br>Window Object <br>The window object represents a window in browser. An object of window <br>is created automatically by the browser. <br>Window is the object of browser, it is not the object of ja vascript . The <br>javascript objects are string, array, date etc. <br>Methods of window object munotes.in</p> </div> <div class="post"> <h2>Page 96</h2> <p> <br> Skill Enhancement: Web <br>Programming <br>96 The important methods of window object are as follows: <br>Method Description <br>alert() displays the alert box containing message with ok <br>button. <br>confirm() displays the conf irm dialog box containing message <br>with ok and cancel button. <br>prompt() displays a dialog box to get input from the user. <br>open() opens the new window. <br>close() closes the current window. <br>setTimeout() performs action after specified time like calling <br>funct ion, evaluating expressions etc. <br> <br>Navigator Object Properties <br>The properties of the navigator object are the variables created inside the <br>Navigator Object. <br>We can access Navigator Object Property <br>as: navigator.propertyname where propertyname is the name of <br>property. <br>Properties Description <br>appcodename specifies the code name of the browser ( experimental <br>property - can return incorrect value ) <br>appname specifies the name of the browser ( experimental <br>property - can return incorrect value ) <br>appversion specifi es the version of browser being used <br>(experimental property - can return incorrect value ) <br>cookieEnabled specifies whether cookies are enabled or not in the <br>browser <br>platform contains a string indicating the machine type for which <br>the browser was compiled. munotes.in</p> </div> <div class="post"> <h2>Page 97</h2> <p> <br> JavaScript <br>97 Properties Description <br>useragent contains a string representing the value of user-agent header sent by the client to server in HTTP protocol <br>geolocation returns object of GeoLocation which can be used to get <br>the location information of the device. <br>onLine specifies whether th e browser is online or not. <br>language returns a string with the preferred browser language, <br>for example, en-US for English. <br>languages returns a string with all the languages supported by the <br>browser in order of user preference. <br> <br>JavaScript Object Propert y <br><html> <br><head> <br> <title>JS Navigator Object Properties


Navigator Object Example





navigator.appName: Netscape
navigator.appVersion: 5.0 (Windows NT 6.2; WOW64)
AppleWebKit/537.36
(KHTML, like Gecko) Chrome/ 37.0.2062.124 Safari/537.36
navigator.cookieEnabled: true
navigator.language: en -US
navigator.userAgent: Mozilla/5.0 (Windows NT 6.2; WOW64)
AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
navigator.platform: Win32
navigator .onLine: true
navigator.appCodeName: Mozilla
The location object contains information about the current URL.
The location object is part of the window object and is accessed through
the window.location property.
Note: There is no public standard that appl ies to the location object, but all
major browsers support it.


munotes.in

Page 99


JavaScript
99 Location Object Properties

Property Description
hash Sets or returns the anchor part (#) of a U RL
host Sets or returns the hostname and port number of a URL
hostname Sets or returns the hostname of a URL
href Sets or returns the entire URL
origin Returns the protocol, hostname and port number of a URL
pathname Sets or returns the path name of a URL
port Sets or returns the port number of a URL
protocol Sets or retur ns the protocol of a URL
search Sets or returns the querystring part of a URL
Location Object Methods
Method Description
assign() Loads a new document
reload() Reloads the current document
replace() Replaces the current document with a new one
navigator.appVersion: 5.0 (Windows NT 6.2; WOW64)
AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0. 2062.124 Safari/537.36
navigator.cookieEnabled: true
navigator.language: en -US
navigator.userAgent: Mozilla/5.0 (Windows NT 6.2; WOW64)
AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
navigator.platform: Win32
navigator.onLi ne: true munotes.in

Page 100


Skill Enhancement: Web
Programming
100
Document Object Model
The document object represents the whole html document.
When html document is loaded in the browser, it becomes a document
object. It is the root element that represents the html document. It has
properties and methods. By th e help of document object, we can add
dynamic content to our web page.
What is Document Object Model (DOM)
The Document Object Model (DOM) is an application programming
interface (API) for manipulating HTML documents.
The DOM represents an HTML document as a tree of nodes. The DOM
provides functions that allow you to add, remove, and modify parts of the
document effectively.
Note that the DOM is cross -platform and language -independent ways of
manipulating HTML and XML documents.
A document as a hierarchy of nodes
The DOM represents an HTML document as a hierarchy of nodes.
Consider the following HTML document:


JavaScript DOM


Hello DOM!




Code language: HTML, XML (xml)





munotes.in

Page 101


JavaScript
101 The following tree represe nts the above HTML document:

In this DOM tree, the document is the root node. The root node has one
child node which is the element. The element is called
the document element .
Each document can have only one document element. In an HTML
document, the document element is the element. Each markup can
be represented by a node in the tree.
A Document object represents the HTML document that is displayed in
that window. The Document object has various properties that refer to
other object s which allow access to and modification of document content.
The way a document content is accessed and modified is called
the Document Object Model , or DOM . The Objects are organized in a
hierarchy. This hierarchical structure applies to the organization of objects
in a Web document.
 Window object − Top of the hierarchy. It is the outmost element of
the object hierarchy.
 Document object − Each HTML document that gets loaded into a
window becomes a document object. The document contains the
contents of the page.
 Form object − Everything enclosed in the

...
tags
sets the form object. munotes.in

Page 102


Skill Enhancement: Web
Programming
102  Form control elements − The form object contains all the elements
defined for that object such as text fields, buttons, radio buttons,
and checkboxes.
9.10 JAVASCRIPT FORM VALIDATION
It is important to validate th e form submitted by the user because it can
have inappropriate values. So, validation is must to authenticate user.
JavaScript provides facility to validate the form on the client -side so data
processing will be faster than server -side validation. Most of the web
developers prefer JavaScript form validation.
Through JavaScript, we can validate name, password, email, date, mobile
numbers and more fields.
JavaScript Form Validation Example
In this example, we are going to validate the name and password. The
name can’t be empty and password can’t be less than 6 characters long.




action="http://www.javatpoint.com/javascriptpages/valid.jsp"
onsubmit="return validateform()" > munotes.in

Page 103


JavaScript
103 Name:

Password:





JavaScript Number Validation
Let's validate the textfield for numeric value only. Here, we are using
isNaN() function.





action="http://www.javatpoint.com/javascriptpages/valid.jsp"
onsubmit="return matchpass()">
Password:
munotes.in

Page 104


Skill Enhancement: Web
Programming
104 Re-enter Password:




JavaScript email validation
We can validate the email by the help of JavaScript.
There are many criteria that need to be follow to validate the em ail id such
as:
o email id must contain the @ and . character
o There must be at least one character before and after the @.
o There must be at least two characters after . (dot).




action="http://www.javatpoint.com/javascriptpages/valid.jsp"
onsubmit="return validateemail();">
Email:





munotes.in

Page 105

105 4
FUNDAMENTALS OF AJAX
Unit Structure
4.0 Objectives
4.1 Introduction
4.3 Ajax
4.3.1 Ajax Web Application Model
4.3.2 Working of Ajax
4.3.3 XmlHttpRequest Object
4.3.3.1 Methods
4.3.3.2 Properties
4.3.4 Handling asynchronous requests
4.0 OB JECTIVES
After going through this unit you will be able to :
 Describe the working Ajax
 Demonstrate asynchronous communication between client and
server
 Update the web page without refreshing it
 Develop more interactive, attractive and dynamic web pages
 Handle the data through cookies and sessions
4.1 INTRODUCTION
A website is a means of communication for an individual, company or any
organization with the help of internet. It not only contains information like
text, numbers, but also images and videos. Tod ay’s technological era
demands the tools which will allow the management of dynamic contents
with the help of databases. It also need the features like user friendliness
as well as increased efficiency and speed. However the user is always
attracted to the websites where the contents are well organized, eye catchy
with animation effects, presentable, and satisfy the need of the user in no
time. In order to make our web applications enriched with all the above
mentioned features we need various tools to be u sed. Whereas in this unit
we are going to learn Ajax, PHP and JQuery.
Ajax is a tool which dynamically communicates with web server with
XmlHttpRequest object which preventsreloading the unnecessary munotes.in

Page 106


Skill Enhancement: Web
Programming
106 contents. It only refreshes the specific part of a page which needs to be
reloaded. This increases the efficiency.
PHP allows to build dynamic pages with the use of various databases like
MySQL, Oracle, Sql and many more.
Jquery is nothing but a Javascript library which works on a motive “Write
Less Do More ” and provides plenty of built in animations which can be
used in our website.
So overall these thee technologies together allows us to build dynamic,
attractive and more responsive web pages.
In the consequent chapters we are going to learn all those top ics in detail.
4.2 AJAX INTRODUCTION
Ajax stands for Asynchronous Javascript and XML. It is a combination of
technologies suchas HTML, XML, Javascript and CSS for web
application development. The technology is popular at it makes the web
pages more respon sive. All this is possible because data exchange process
in client and server also can happen after the page has been loaded and
hence it is fast. It means the data can be sent to the server in background.
The reason behind this is Ajax is a Data Driven we b browser technology
independent of any web server software. This technology is used in
various web applications such as google maps, youtube, facebook, twitter
etc. Though it is a Rich Internet Application (RIA) technology it has
browser incompatibility and is supported by Javascript.
The technologies used in Ajax are
1. Javascript : It used to bind the data requests and displays the
information. It is also used for validating the data provided by the user
i.e user inputs in HTML and then sends the data t o the server.

2. DOM : Document Object Model is used for dynamic interaction and
displaying the presented information

3. CSS : CSS is an acronym for Cascading Style Sheet and is mainly
used for displaying the content and style i. e. for presentation purpose

4. XmlHttpRequest :It allows asynchronous communication between
client and server.

5. XML, HTML and XSLT :XSLT is a style sheet language for XML
which allows transformation. The purpose of these technologies is for
displaying the content in a presentable ma nner.

munotes.in

Page 107


Fundament als of Ajax

107 Applications of Ajax :
We can see the use of Ajax in various areas such as:
1. Google Autocomplete Feature:It assists to complete the keywords
while they are being typed. The keywords used to change in real time,
whereas the page remains the same.

Eg: In the below screen in the search box the keyword entered is
places but it is showing various suggestion starting from the
keyword places.

Figure 4.1 Autocomplete feature by google

2. Voting and Rating System:
Whenever we purchase anything online it u sed to ask rating for the
product. We also have seen various online voting forms. So when we
click on the rating or voting button the website updates the calculation
but the whole page remains unchanged.

3. Chat Rooms:
Some websites uses built in chat room w hich provides s support
services by enabling the communication with their customer support
officer. However there is no need to explore the page at the same time
because Ajax sends and receives new message without reloading the
page.

4. Twitter’s Trending No tification:
Twitter has recently used AJAX for their updates. Whenever new
tweets are made regarding trending topic; Twitter updates the new
figures without affecting the main page.

5. Form Validation : The credentials such as user Id and Password can
be validated using Ajax
So we can see that applications such as google maps, twitter, Gmail,
Youtube, Google Suggest, Facebooketc are using this technology.
munotes.in

Page 108


Skill Enhancement: Web
Programming
108 Advantages of Ajax :
1. Easy and Simple: Ajax is very easy to understand if the user is having
strong kn owledge of Javascript
2. Speed : It allows to reduce the server traffic and therby increase the
speed.
3. Responsive : It helps the user to create more responsive, Faster and
interactive web applications
4. Asynchronous Calls : Through asynchronous calls to the we b server it
sees how the data arrival time can be reduced
5. Form Validation : Validation is the most necessary part of any form
data. Ajax usesprompt and proper validation methods.
6. Bandwidth Usage : Ajax based applications needs very less bandwidth
as they are not refreshing the whole page. They are just reloading the
part of the page which is required to be updated.
Diadavantages of Ajax :
1. Browser Support : It does not run all browser. Rather before actual
execution we need to check the browsers which are supporting it.
2. Security and User Privacy :Issues regarding user security and privacy
are need to be taken care while developing the ajax applications.
3. Accessibility : Since all browsers does not support Javascript and
XmlHttpRequst Object, one must lo ok into the part how to make the
web applications accessible to all the users.
4. Bookmark :Since Ajax uses asynchronous calls it loads bits of contents
on the existing web page instead of reloading the contents of whole
page. Whereas the Browser history and bookmarks may not behave
correctly since URL is unchanged and only some part of it has been
changed.
5. Navigation : When the back button is pressed the user thinks that it
will switch over to the last change which he has made. However Ajax
does not support t hat.
6. Search Engine : It is possible to search Ajax features and elements
within an application but we can not search for Ajax applications.
Search Engines like google can not index Ajax pages

4.2.1 AJAX WEB APPLICATION MODEL
Web application model of Ajax uses XmlHttpRequest and Javascript for
asynchronous data communication over client server architecture.
It provides solutions to the problem of synchronous request -response
model of communication related to classical web application models
where the user is kept on wait state and thus do not provide better
experience to the user.
New approach of Ajax with regard to web applications is based on various
technologies which provides better user experience and helps to develop
interactive web applications. munotes.in

Page 109


Fundament als of Ajax

109 The app lications of Ajax rejects start -stop or click and wait actions. It
creates an intermediary layer between the user and the web server to
eliminate the refresh criteria of client server interaction.
At the beginning of the session it does not load web page i nstead the the
browser loads the Ajax engine which is written in javascript. However
each and every action of the user generates HTTP request which in turn
makes a javascript call to the Ajax Engine.
The response provided by the server contains only data but not
presentation which indicates that data required by the client is provided by
the server as the response and presentation implemented on that data with
the help of XML from Ajax Engine.
Javascript does not executes all the instructions rather it upd ates the web
page dynamically
Javascript make it possible to fill the forms and click on the buttons even
when javascriptsends request to the web server and at the same time server
is working on the requests in the background. When server completes its
processing code updates only that part of page which has changed. This is
how the client need not wait around. This is nothing but called as
asynchronous requests.

Figure 4.2 Ajax Web Application Model
munotes.in

Page 110


Skill Enhancement: Web
Programming
110 Irrespective of server Ajax does asynchronous communic ation between
client and the application. This prevents the user from waiting for the
server to complete its processing.
The Ajax engine displays the user interface and interact with server on
behalf of user
Following figure shows synchronous mode of comm unication between
client and server in traditional web applications

Figure 4.3 Synchronous Mode of Communication
Essentially Ajax is used for partial update and asynchronous
communication, the Ajax model is used for programming and not
restricted for any specifications such as specific data exchange format or
specific programming language or specific communication mechanism
Following figure shows Asynchronous mode of communication

Figure 4.4 Asynchronous Mode of Communication
This figure clarifies eve ry action done by the user results in generation of
HTTP request which takes the form of a JavaScript to call the Ajax
Engine. munotes.in

Page 111


Fundament als of Ajax

111 Ajax engine handles Data validation, Navigation and data editing in
memory on its own as compared to classical web application mo del where
responses to the user action do not involve the trip back to the server.
Ajax engine makes an asynchronous interaction with server using
JavaScript and XmlHtttpRequest Object. This communication does not
interrupt user interaction with applicati on.
4.2.2 Working of Ajax
The communication between Ajax and Web Server happens using
XmlHttpRequest Object
Following sequence show the workflow of Ajax
1. Through the User Interface user sends a request and a javascript call
goes to XmlHttpRequest Object
2. XmlHttpR equest Object then sends the HTTP request to the server
3. Server then interacts with database using programming languages
such as PHP ASP.net, JSP etc.
4. Data is retrieved
5. Server sends XML data to the XmlHttpRequest callback function
6. On the web browser content s of HTML and CSS are displayed.



Figure 4.5 Working of Ajax
In the Ajax model Ajax Engine is involved between client and server
which eliminates the process of communication from user to server and
then again back from server to user. The Ajax Engine is written in
Javascript. It handles user from by communicating to user and handles
server side by itself. This is how eradicates waiting time faced by the user. munotes.in

Page 112


Skill Enhancement: Web
Programming
112 Comparison between Convention Model and Ajax Model
Sr.
No. Conventional Model Ajax Modes
1. Web Browser send HTTP
request to the server The browser creates javascript call
which results in activating
XmlHttpRequest
2. The server receives the
request processes it and
retrieves the data In the background HTTP request
is created by the browser and s ent
to the server
3. Web browser gets the
requested data which is sent
by the server The server receives, retrieves and
sends the data back to the web
browser
4. After receiving the data to the
web browser the page is to be
reloaded to make the data
appe ar The requested data is received by
the browser and without reloading
it appears on the page
5 This process is time
consuming as well as puts This process is fast as compared
to conventional model


4.2.3 XmlHttpRequest Object
All the modern browsers support s XmlHttpRequest Object which is used
to request data from the server. Following illustration will help us to
understand uses of this object

Figure 3.6 Features of XmlHttpRequest Object

munotes.in

Page 113


Fundament als of Ajax

113 This object consists of various methods and propertires.

Figure 3.7 Methods and properties of XmlHttpRequest Object
We will understand all those methods and properties one by one.
4.2.3.1 XmlHttpRequest Object Methods:
Sr.No Method Description
1. new XML
Http Request() Allows to create new
XmlHttpRequest object
2. abort() Cancels the current request
3. Get All Response
Headers() Returns header information
4. Get Response
Header() Returns specific header
information
5.
open( method,url,as
ync,user,psw ) Opens the request with
following parameter
specifications
Method : The re quest type
GET or POST
Async : true (asynchronous)
or false (synchronous
User : username
Psw : password
6. Send() Sends the request to the server Used for GET requests
7.
Send(string) Sends the request to the
server.
Used for POST requests

munotes.in

Page 114


Skill Enhancement: Web
Programming
114 4.2.3.2 XmlHttpRequ est Object Properties:
Sr. No Propery Description
1. Onreadystatechange Defines a function to be called when the
readyState property changes
2. readyState Holds the status of the XMLHttpRequest. 0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
3. responseText Returns the response data as a string
4. responseXML Returns the response data as XML data
5. Status Returns the status -number of a request
200: "OK"
403: "Forbidden"
404: "Not Found"
For a complete list go to theHttp
Messages Reference
6. statusText Returns the status -text (e.g. "OK" or "Not
Found")

4.2.4 Handling asynchronous requests using Ajax:
We already know that Ajax technology allows to make asynchr onous
HTTP request without reloading the full page. To make this process more
easy as compared to in pure javascript,JQuery libraries can be used.
JQuery’s most common Ajax shorthand methods are $.get(), $.post() and
$.load().
Whenever we specify an event and if Ajax call fails or Ajax request could
not give us the requested result in certain time period in that case we can
rely on other function provided by JQuery i.e. $.ajax(). This function is
used to perform an asynchronous HTTP request.
Following is the syntax of the $.ajax() function
$.ajax(url [ , settings])
$.ajax([settings])
The url is the location where we want rich with the help of ajax call.
Whereas settings allows to make configurations for the Ajax request.
munotes.in

Page 115


Fundament als of Ajax

115 Following are some of the setting parameters of $.ajax()
Sr.No Setting Description
1. accepts Specifies the type of response will get in
return to the request sent
2. async Makes asynchronous request. If we want to
make synchronous request it can be set false
3. cache If this option i s set as false it forces the
requested page not to be cached by the
browser
4. beforeSend Pre request call back function
5. complete A function to be called when the request
finishes
6. contents This object determines how the library will
parse the re sponses.
7. contentType Data content type sent to the server
8. context Context this is used for all ajax related call
backs
9. converters Data type to data type converter
10. crossDomain To force a cross domain request can set this
as True
11. Data Data which is sent to the server while
making ajax request
12. dataFilter handles the raw response data of
XMLHttpRequest.
13. dataType The type of data expected back from the
server.
14. Error A function to be called if the request fails.
15. global Whether to trigger global Ajax event
handlers for this request.
16. headers An object of additional headers to send to
the server.
17. statusCode An object of numeric HTTP codes and
functions to be called when the response has
the corresponding code
18. success A function to be called if the request
succeeds
19. timeout Specifies a timeout (in milliseconds) for the
request.
munotes.in

Page 116


Skill Enhancement: Web
Programming
116 Summary:
Asynchronous JavaScript and XML (Ajax) refer to a group of
technologies that are used to develop web applications.
Ajax enables a web application user to interact with a web page without
the interruption of constant web page reloading.
Ajax is made up of various technologies such as XHTML, CSS,
Document Object Model (DOM), XMLHttpRequest object, XML, HTML,
and XSLT and Ja vaScript
XMLHttpRequest Object is used to send and receive to and from the
server in the background . It works with various methods and properties
Practice Questions:
1. Explain what is Ajax and also state the technologies through which the
ajax is made up of
2. Write advantages and limitations of ajax technology
3. Explain Ajax web application model with the help of diagram
4. Explain various modes of communication in client and server in web
applications
5. How does ajax works?
6. Write the difference between convention al model and ajax model
7. Explain XmlHttpRequest object with its methods and properties
Web References:
https://www.mageplaza.com/blog/advantages -and-disadvantages -of-
ajax.html
https://way2tutorial.com/ajax/ajax -advantages -and-disadvantages.php
https://www.sitesbay.com/ajax/ajax -featur es
https://www.ques10.com/p/29472/explain -in-detail -ajax-web-application -
model -wit-1/


munotes.in

Page 117

117 5
FUNDAMENTALS OF PHP
Unit Structure
5.1 PHP
5.1.1 Variables and Operators
5.1.2 Program Flow
5.1.3 Working with arrays
5.1.4 Files and Directories
5.1.5 Working with Database
5.1.6 Cookies, Sessions, and Headers
5.1 PHP
PHP. It is a recursive acro nym of Hypertext Preprocessor. It is developed
by RasmusLerdorf in the year 1994
PHP is an open source, object oriented, interpreted, server side scripting
language embedded in HTML which allows to develop dynamic web
pages. Software Applications are devel oped using this language. To bring
the dynamism in this language it is integrated with various popular
databases such MySQL, Oracle, Microsoft SQL server, Sybase,
PostgreSQL etc. PHP is simple and easy to learn as the syntax of PHP is
very similar to c la nguage. PHP is faster than any other scripting
languages such as ASP or JSP
Following are the features of PHP:

Figure 5.8 Features of PHP munotes.in

Page 118


Skill Enhancement: Web
Programming
118 1. Familiarity : The person having programming background can easily
understand syntax of PHP as the syntax is inherite d by C language.

2. Simplicity: Like C language there is no need to include any libraries. It
provides lot many predefined functions which helps to secure the
data.PHP programs can be written without creating classes.

3. Efficiency: PHP supports object oriented programming and it also
supports session management which makes it more efficient as it does
not require unnecessary memory allocation.

4. Security: PHP’s predefined function sets supports trusted data
encryption options and thereby provides security.

5. Open Source :PHP is an open source programming language so you
can download freely there is no need to buy a licence or anything.

6. Flexible: PHP cam be embedded with various languages such as
HTML, JAVA SCRIPT, WML, XML, and many others. PHP scripts
can run o n any devices ie scripts are executed on the server and the
result is sent to the browser of a device. Hence PHP is flexible.

7. Cross Platform : PHP scripts can be executed on any operating system
such as windows, Linux, Mac, Solaris etc.
PHP Installation
Various AMP (Apache, MySQL and PHP) software stacks are available
for PHP installations such as
1. WAMP : Used in Windows
2. LAMP : Used in Linux
3. MAMP : Used in Mac
4. SAMP : Used in Solaris
5. FAMP : Used in FreeBSD
6. XAMPP : It is cross platform and is used as ac ronym for (Cross,
Apache, MySQL, PHP and Perl) It can be used in any operating
system. It also includes the components such as FileZilla,
OpenSSL, Webalizer, Mercury Mail, etc.
Now we will see how to install XAMPP in our computer having Windows
operating System

munotes.in

Page 119


Fundamentals of PHP

119 Step 1 : Download the software using link
https://www.apachefriends.org/download.html
Step 2 : Run the exe. To allow the installation we have to deactivate the
antivirus software

Step 3 : Deactivate User Account Control

Step 4 : Start the setup wizard

munotes.in

Page 120


Skill Enhancement: Web
Programming
120 Step 5 : Select software components

Step 6 : Select the installation folder





munotes.in

Page 121


Fundamentals of PHP

121 Setp7 : Start installation process

Step 8 : Complete the installation





munotes.in

Page 122


Skill Enhancement: Web
Programming
122 Step 9 :Open the control panel

Here we can activate the required services. The default port for Apache
server is 80.
After activating the services we can start writing the php program and
execute it. The things to be noted that The PHP file should be saved with
an extension .php and ar e always to be saved htdocs folder. As per step no
6 we can see that xampp folder is getting created in C drive so you will be
able to find the htdocs folder in C:/xampp/htdocs path .
To view the program execution
We have to perform following steps
1. Open t he browser and type localhost:80/ and press enter as it the
default port for apache server.
2. It will show the dashboard



3. To execute a program click on address bar and remove dashboard
and type name of your php file and press enter. The output will be
displayed in the browser.
munotes.in

Page 123


Fundamentals of PHP

123
5.1.1 Variables and Operators
Basic PHP Syntax
A PHP script starts with
Single line comments will be written using // symbol or # symbol.
However multiline comments are written within /* */ symbols
Rules to be kept in mind while declaring variables
1. A variable should always start with an alphabet or an underscore
character only and may have (A -Z, a-z,0 to 9 and an underscore) in it
2. In PHP variable name always starts with $ symbol. Eg : $a=10;
3. A variable name c an not start with number
4. Names of the variable are case sensitive eg $sname and $SNAME
will be considered as different variables
PHP Datatypes

PHP Datatypes
PHP supports various data types. However whenever we define any
variable with a value it used to consider the type of variable will be which
is matching the value of the variable
Eg. If it is written as $a=10 then it automatically considered as datatype of
variable will be integer. If we write $a=”mystring” then it considers the
datatype of variable a as string.
var_dump() function allows us to check the datatype of the variables.. munotes.in

Page 124


Skill Enhancement: Web
Programming
124 Eg. The code snippet given below shows us the result as int(10)

Here we will see all the datatypes briefly:
1. Integer : This datatype considers only non fractional posit ive or
negative whole numbers they are ranging from -2,147,483,648 and
2,147,483,647. It is declared as $age=21;
2. Float : This datatype allows to store floating point real numbers means
decimal values. It is declared as float $weight=15.30;
3. String : Strin g is nothing but a group of single characters stored in
consecutive memory locations. The value of string variable is written
in double quotations. Eg: $name=”nisha”;
4. Boolean : This datatype used to represent only two possible states i.e.
True or Fa lse. They are normally used while testing the conditions.Eg :
$x=true;
5. Array : The datatype array is having capacity to store multiple similar
datatype values inside one single variable. It is declared as
Eg :$flowers=array(“lily”, “Jasmine”, “lot us”);
6. Object : Under object oriented programming classes and objects are
two main concepts . A class defines structure of the object and and
object is instance of the class. When the individual objects are created,
they inherit all the properties and behavi ors from the class, but each
object will have different values for the properties.
7. Null : Whenever we want to create any variable without value or we
have to remove the value of existing variable then null datatype is
used.
munotes.in

Page 125


Fundamentals of PHP

125 Eg $x=”nisha”;
$x=null;
8. Resou rce : This datatype allows to store references to functions and
resources external to PHP
PHP Operators

Figure PHP Operators
1. Arithmetic operators

Sr. No. Operator Name Example Description
1 + Addition $a + $b Calculates Sum of
operands
2 - Subtraction $a - $b Calculates Difference of
operands
3 * Multiplication $a * $b Calculates Product of
operands
4 / Division $a / $b Calculates Quotient of
operands
5 % Modulus $a % $b Calculates Remainder of
operands
6 ** Exponentiation $a ** $b Calculates $ a raised to the
power $b



munotes.in

Page 126


Skill Enhancement: Web
Programming
126 2. AssignentOpeators
Sr.No Operator Name Example Description

1 = Assign $a = $b Assigns the value of RHS Operand to
LHS Operand

2 += Add and then
Assign $a += $b Evaluates as $a = $a + $bt
3 -= Subtract and then
Assign $a -= $b Evaluates as $a = $a - $b
4 *= Multiply and then
Assign $a *= $b Evaluates as $a = $a * $b
5 /= Divide and then
Assign
(quotient) $a /= $b Evaluates as $a = $a / $b
6 %= Divide and then
Assign
(remainder) $a %=
$b Evaluates as $a = $a % $b

3. Comparison Operators
Sr.No. Operator Name Example Description
1 == Equal $a == $b Returns TRUE if $a is exactly equal
to $b
2 === Identical $a ===
$b Returns TRUE if $a is exactly equal
to $b, and if their datatype is also
same
3 !== Not identical $a != =
$b Returns TRUE if $a is not equal to
$b, and they are not of same data type
4 != Not equal $a != $b Returns TRUE if $a is not equal to $b
5 <> Not equal $a <> $b Returns TRUE if $a is not equal to $b
6 < Less than $a < $b Returns TRUE if $a is less t han $b

7 > Greater than $a > $b Returns TRUE if $a is greater than $b
8 <= Less than or
equal to $a <= $b Returns TRUE if $a is less than or
equal $b

9 >= Greater than or
equal to $a >= $b Returns TRUE if $a is greater than or
equal $b

10 <=> Spaces hip $a
<=>$b Returns -1 if $a is less than $b Returns 0 if $a is equal $b Returns 1 if $a is greater than $b
munotes.in

Page 127


Fundamentals of PHP

127 4. Increment / Decrement Operators
Sr.No. Operator Name Example Description

1

++ Pre
Increment ++$a Increases the value of $a by
one, then returns the value of $a

2 Post
Increment $a++ First returns the value of $a,
and then increases the value
of $a by one

3
-- Pre
Decrement --$a Decreases the value of $a by
one, and then returns the
value of $a

4 Post
Decrement $a-- First return the va lue of $a,
and then decreases the value
of $a by one


5. Logical Operatots
Sr. No. Operator Name Example Description

1 && And $a and $b Returns TRUE if both $a and
$b are true
2 || Or $a or $b Returns TRUE if either $a or
$b is true
3 xor Xor $a xo r $b Returns TRUE if either $ or
$b is true but not both
4 ! Not ! $a Returns TRUE if $a is not
true
5 and And $a and $b Returns TRUE if both $a and
$b are true
6 or Or $a or $b Returns TRUE if either $a or
$b is true
6. String Operators
Sr.No. Operator Name Example Description

1 . Concatenation $a . $b Concatenate both $a and
$b
2 .= Concatenation
and
Assignment $a .= $b First concatenate $a and
$b, then assign the
concatenated string to $a,
e.g. $a = $a . $b
munotes.in

Page 128


Skill Enhancement: Web
Programming
128 7. Conditional Operators
Sr.
No. Operator Name Example Description

1 ? : Ternary $x
= expr1 ?
expr2 : expr3 Returns the value of $x. The value of $x
is expr2 if expr1 = TRUE. The value of $x
is expr3 if expr1 = FALSE
2 ? ? Null
Coalescing $x
= expr1 ?
? expr2 Returns the value of $x. The value of $x
is expr1 if expr1 exists, and is
not NULL. If expr1 does not exist, or is
NULL, the value of $x is expr2

8. Array Operators

5.1.2 Program Flow
First we will try to understand syntax of phpprogram.with the help of
following example
Here is a code snippet which shows addition of two numbers in php Sr.
No. Operator Name Example Description
1 + Union $a + $b Returns Union of $a and $b

2 == Equality $a == $b Returns TRUE if $ a and $b have
same key/value pair

3 != Inequality $a != $b Returns TRUE if $a is not equal to
$b

4 === Identity $a === $b Returns TRUE if $a and $b have
same key/value pair of same type in
same order
5 !== Non-Identity $a !== $b Returns TRUE if $a is not identical
to $b
6 <> Inequality $a <> $b Returns TRUE if $a is not equal to
$b munotes.in

Page 129


Fundamentals of PHP

129 “



Opening
php
Single line
comment
Variable
declaration


Closing
php

In the given code snippet
PHP code is embedded with HTML. makes us understand that now we are started writing the code using php
script whereas ?> a t the end denotes that here is the end of php script. So
within block we are writing php code. In the line //Program to
print addition of two numbers you can see the symbol // which is used as a
single line comment. In PHP we can give single lin e comment using //
symbol or # symbol. If we want to give multiline comment we can write
the comment statements in /* */ block.
Then $a=10; $ b=20; are showing how we have declared the variables. So
from these lines we can understand that $ symbol is used before name of
the variables whenever we are using the variable.
However the statement echo “addition is“ .$c; is indicating that we are
printing the addition of a and b. Here . (dot) is the operator which is used
for concatenation purp ose.
PHP supports various programming structures such as Simple If, Nested
If, Decision Making using ternary operators, Switch case, iterative
Statements etc. munotes.in

Page 130


Skill Enhancement: Web
Programming
130

Figure PHP Programming Structure
Conditional Analysis :
This is the way how computers can make decisions based on conditions.
In programming various structures are used such as if, if -else, if –else-if,
nested if, Ternary operators and switch case. We will try to understand all
those concepts with the help of programs
1. If -else :
Syntax :

if (cond ition)
Statement //if the condition appears to be true
else
Statements // if the condition appears to be false

Example : Write a program to print whether the number is even or odd


$n=10;
If($n%2= = 0)
echo “Entered no is Eve n”;
else
echo “Entered no is Odd”;
?>

munotes.in

Page 131


Fundamentals of PHP

131 2. Nested If
Syntax :
If (Condition)
Statement // If condition appears to be true
Else if (Condition) // if first condition is appearing to be false then
applying 2nd condition
Statement // if se cond condition appears to be true
Else
Statement // if Second condition appears to be false
Example : Write a program print whether a number is positive, negative or
zero


$n=-10;
if($n>0)
echo "entered number is positive";
else if ($n<0)
echo "Entered number is negative";
else
echo "Enter number is zero";
?>



3. Ternary operators
Syntax
(condition) ? :false>
munotes.in

Page 132


Skill Enhancement: Web
Programming
132 Example : Write a program to print whe ther a number is even or odd


$x = 27;

echo "Input Number: ", $x, " \n\n";

$x = $x % 2 == 0 ?1 : 0;

if ($x) {
echo "The input number is even number. \n";
} else {
echo "The input number is odd number. \n";
}
?>



4. Switch C ase
Syntax
switch (expression){
case value1:
//code to be executed
break ;
case value2:
//code to be executed
break ;
......
default :
code to be executed if all cases are not matched;
} munotes.in

Page 133


Fundamentals of PHP

133 Example : Write a prog ram to accept a day of week in number and print
respective day







Enter a number

$x=$_POST['weekdaynum'];
switch($x)
{
case 1 :
echo "sunday";
break;
case 2 :
echo "monday";
break;
case 3 :
echo "tuesday";
break;
case 4:
echo "wednesday";
break;
case 5 :
echo "thursday"; munotes.in

Page 134


Skill Enhancement: Web
Programming
134 break;
case 6:
echo "friday";
break;
case 7:
echo "saturday";
break;
default:
echo "not a proper number";
break;
}
?>


Iterative Statements :
Iterative statements are also called as looping structures. When certain
instructions are to be executed multiple times continuously in such cases
we can make use of loops. While workin g with such loops we must have
following thing such as
1. Initial value
2. Final Value
3. Condition
4. Increment / Decrement
5. Body of the Loop
In PHP we come across with 4 different types of loops which we are going
to understand with the help of examples. These loops are :
1. For () loop
Syntax
For (initial value; final value and condition; incr/decr)
{
Body of the loop;
}
Example : Write a program to print the series of number 1,2,3,…..,10 munotes.in

Page 135


Fundamentals of PHP

135

for($x=1;$x<=10;$x++)
{
echo $x;
echo "
";
}
?>



2. While () loop
Syntax
Initial value;
While (condition with final value)
{
Body of the loop;
Increment / decrement ;
}

Example : Write a program to print the series of number 1,2,3,…..,10


$x=1;
while($x<=10)
{
echo $x;
$x=$x +1;
echo "
";
}
?>




3. Do while() loop munotes.in

Page 136


Skill Enhancement: Web
Programming
136 Syntax
Initial value;
do
{
Body of the loop;
Increment / decrement ;
}
While (condition with final value);

Example : Write a program to print the series of number 1,2,3,…..,10


$x=1;
do
{
echo $x;
$x=$x+1;
echo "
";
}
while($x<=10);
?>





munotes.in

Page 137


Fundamentals of PHP

137 4. Foreach() loop : This type of loop is used in php to work with array
elements.

Syntax
foreach ($array as $key => $element)
{
Statemets to be executed;
}
Example : Write a program to print the series of number 1,2,3,…..,10


//array declaration
$no = array (1,2,3,4,5,6,7,8,9,10);

//access array elements using foreach loop
foreach ($no as $element) {
echo "$element";
echo "< /br>";
}
?>


5.1.3. Working with arrays
An array is programming structure where we can stores one or more
similar type of values in a single variable. In PHP there are 3 different
types of array such as
1. Numeric Array: The above code snippet offoreach() loop is an
example of numeric array. There are two different types of methods how
we can declare numeric arrays.
Method 1 : $x=array(1,2,3,4,5);
Method 2 :
$x[0]=1; munotes.in

Page 138


Skill Enhancement: Web
Programming
138 $x[1]=2;
$x[2]=3;
$x[3]=4;
$x[4]=5;


2. Associative Array : The function ality of associative arrays are very
similar to numeric arrays Just the difference is in their index. Associative
array will have their index as string so that one can establish a strong
association between indexes and values. These arrays can be declared as
follows
$st_marks=array(“krish” => 50, “samiksha” =>67, “Shubhra” =>90);
Here krish, samiksha and shubhra are index keys however 50, 67 and 90
are the values of the index keys.

3. Multidimensional Array : A multi -dimensional array each element in
the main array can also be an array. And each element in the sub -array can
be an array, and so on. Values in the multi -dimensional array are accessed
using multiple index.

Following example will show how multidimensional arrays can be
declared.
$st_marks = array(
"krish" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),

"samiksha" => array (
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),

"shubhra" => array (
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
); munotes.in

Page 139


Fundamentals of PHP

139 5.1.4 Files and Directories
PHP has a file system which allows the user to create file, read contents of
the file line by line, character by character, append the contents in the file
as well as delete and close the file.
We will see following functions used for handling the files
1. fopen() : This function is used to open the file.
Example
$fileop = fopen ("c:\\Shubhra \\myfile.txt", "r");
?>
Here “r” stands for file open mode .
Following table will show various modes of file opening
Sr. No. Mode Description
1 r Opens file in read-only mode. It places the file pointer
at the beginning of the fi le.

2 r+ Opens file in read-write mode. It places the file
pointer at the beginning of the file.

3 w Opens file in write-only mode. It places the file pointer
to the beginning of the file and truncates the file to zero
length. If file is not found, it creates a new file.

4 w+ Opens file in read-write mode. It places the file
pointer to the beginning of the file and truncates the file
to zero length. If file is not found, it creates a new file.

5 a Opens file in write-only mode. It places the file po inter
to the end of the file. If file is not found, it creates a
new file.

6 a+ Opens file in read-write mode. It places the file
pointer to the end of the file. If file is not found, it
creates a new file.

7 x Creates and opens file in write-only mode . It places the
file pointer at the beginning of the file. If file is found,
fopen()
function returns FALSE.

8 x+ It is same as x but it creates and opens file in read-write mode. munotes.in

Page 140


Skill Enhancement: Web
Programming
140
9 c Opens file in write-only mode. If the file does not
exist, it is cr eated. If it exists, it is neither truncated (as
opposed to 'w'), nor the call to this function fails (as is
the case withx'). The file pointer is positioned on the
beginning of the file

10 c+ It is same as c but it opens file in read-write mode.


2. fclose () : This function is used to close the open file
Example
fclose($fileop);
?>
4. fread() : This function is used to read the contents of the file.This
function comes with two parameters such as resource and file size.
Example
$filenam e="c:\\Shubhra \\myfile.txt";
$fileop = fopen($filename,”r”) ;
$contents= fread($fileop, filesize($filename));
echo $contents;
fclose($fileop);
?>
5. fwrite() : This function is used to write the contents into the file.
Example
$fileop = fopen(“c: \\Shubhra \\myfile.txt”, “w”');//open file in write mode
fwrite($fileop, 'hello ');
fwrite($fileop, 'php file');
fclose($fileop);
echo "File written successfully";
?>
munotes.in

Page 141


Fundamentals of PHP

141 6. unlink() : This function is used to delete the file.
Example
unlink(“ c:\\Shubhra \\myfile.txt”);

echo "File deleted successfully";
?>
5.1.5 Working with Database
As we have already learnt that PHP helps us to create dynamic web pages.
With PHP e can connect and manipulate with various databases. However
MySQL is th e most popular database which runs on the server.
To interact with MySQL database following functions are useful.
Sr.
No Function Description
1 Mysqli_connect(hostname,
user,password) Connect the the server using
userid and password
2 Mysqli_connect_erro r() Returns and ID of error
3 Mysqli_query(conectionsring,
querystring) Allows the query string to be
consider as mysql query
4 Mysqli_select_db(database name,
connection string) Activates a MySQL database
on the server
5 Mysqli_fetch_array(resulted[res ult
type]) Fetches the result set as an
associative array

Following examples will show how we can interact with database
Prerequisites : There exists a table named users in database login with few
records in it
Database Name : Login
Table Name : Users munotes.in

Page 142


Skill Enhancement: Web
Programming
142

Figure Records of users table
Example : Considering the above data Write a PHP program to design a
page for authenticating the user.
Code:








Enter user name
Enter password


$userid=$_POST['u'];
$password=$_POST['p'];
$con=mysqli_connect("localhost","root","");
mysqli_select_db("login",$con);
$query="Select * from users where UID= '$u' and PASS= '$p';
$result=mysqli_query($query,$con);
$count=mysql_num_rows($result); munotes.in

Page 143


Fundamentals of PHP

143 if($count==0)
echo "invalid user" ;
else
echo "you have logged in successfully";
mysql_close($con);
?>


5.1.6 Cookies, Sessions, and He aders
PHP headers : header() sends a raw HTTP header. This header() must
always be called before actual output is sent either by normal HTML tags,
blank lines in a file, or from PHP. It is a very common error to read code
with include , or require , functions, or another file access function, and
have spaces or empty lines that are output before header() is called. The
same proble m exists when using a single PHP/HTML file.
Syntax
header( header , replace , http_response_code )
Sr.No. Parameter Description
1 Header It is a required parameter Specifies the
header string to send
2 Replace It is a optional parameter. It indicates
whethe r a header should replace a
previous similar header or adds a new
header of the same type. Default value
is true and it will replace the header.
However false value allows multiple
headers of same type
3 http_response_code Its an optional parameter. It fo rces the
HTTP response code to the specified
value.

PHP cookies :
Cookies are the text files stored on client computer and helps in tracking.
Following are the stepts through which users can be identified munotes.in

Page 144


Skill Enhancement: Web
Programming
144 1. Serve sends a chunk of data in the form of set of cookies to the
browser such as name, age etc.
2. Browser stores the information on client computer for future use
3. When next time request is sent by the browser to the web server,
browser sends those cookies information to the server and server uses
that info rmation for identifying the user.
PHP allows to create cookie using the function setcookie(). This function
has following arguments and they must be called before html tag
Sr.No. Argument Description

1 Name This sets the name of the cookie and is stored
in an environment variable called
HTTP_COOKIE_VARS. This variable is
used while accessing cookies.
2 Value This sets the value of the named variable and
is the content that you actually want to store.
3 Expiry This specify a future time in seconds sin ce
00:00:00 GMT on 1st Jan 1970. After this
time cookie will become inaccessible. If this
parameter is not set then cookie will
automatically expire when the Web Browser
is closed.
4 Path This specifies the directories for which the
cookie is valid. A si ngle forward slash
character permits the cookie to be valid for all
directories.
5 Domain This can be used to specify the domain name
in very large domains and must contain at
least two periods to be valid. All cookies are
only valid for the host and dom ain which
created them.
6 Security This can be set to 1 to specify that the cookie
should only be sent by secure transmission
using HTTPS otherwise set to 0 which mean
cookie can be sent by regular HTTP.



munotes.in

Page 145


Fundamentals of PHP

145 Following example sets the cookie for name an d age and those cookies are
expired after one hour.
setcookie ("name" ,"samiksha" , time()+3600 ,"/","",0);
setcookie ("age" ,"36", time()+3600 ,"/","",0);
?>



Setting Cookies with PHP







isset() function is used to check whether cookies are set or not. Following
program will show how to check whether cookie is set or not


Accessing Cookies with PHP


if(isset($_COOKIE ["name" ]))
echo "Welcome " . $_COOKIE ["name" ]."
" ;

else
echo "cookie not found" ."
" ;
?>



munotes.in

Page 146


Skill Enhancement: Web
Programming
146 PHP sessions :
Allows to access the variable values across various pages of the website.
It creates a file in temporary directory of the server where r egistered
session variables and their values are stored.The location of the temporary
file is determined by a setting in the php.ini file called session.save_path.
Before using any session variable make sure you have setup this path.
Session_start() functi on is used to create the sessions. It is always written
in the beginning of the page. Whereas isset() function is used to check
whether session variables are set or not.
Session_destroy() function is used to destroy the session. Unset() function
is used to unset the session variables.
Following example will show creation of session variables.
session_start ();
if(isset( $_SESSION ['counter' ])){
$_SESSION ['counter' ]+=1;
}else{
$_SESSION ['counter' ]=1;
}
$msg ="You have visited this page " . $_SESSION ['counter' ];
$msg .="in this session." ;
?>


Setting up a PHP session






munotes.in

Page 147


Fundamentals of PHP

147 Summary :
php is acronym for Hypertext Preprocessor. It is a serverside scripting
laguage. The syntax of language is similar to c language and hence easy to
understand.
It is used to create dunamic web pages.
various databases can be used in the backend of the language.
PHP is also having its file system used to create files, read contents,
appe nd the contents and so on
PHP session allows to carry the values of the variable across the pages of
the website
Cookies stores chunk of data for future use.
Practice Questions
1. Write features of PHP
2. Explain PHP datatypes
3. Explain various operators supported bu PHP
4. Write a note on Sessions
5. Write a note on Cookies
6. Explain various file handling modes in PHP
7. Explain MySQL functions used while handling the database
References:
https://www.javatpoint.com/php -tutorial
https://www.w3schools.com/php/default.asp

munotes.in

Page 148

148 6
INTRODUCTIONS TO JQUERY
Unit Structure
6.1 Introduction to jQuery
6.1.1 Fundamentals
6.1.2 Selectors
6.1.3 Methods to access HTML attributes
6.1.4 Traversing Methods
6.1.5 Manipulators, Events, Effects
6.1 INTRODUCTION TO JQUERY
jQuery is a small, lightwei ght , fast, concise and a coss platform
JavaScript Library created by John Resig in 2006. The main intention
behind creating this library was “Write less, do more”. jQuery simplifies
HTML document traversing, event handling, animating, and Ajax calls
and Document Object Model manipulations. jQuery is acting as a
JavaScript toolkit designed to simplify various tasks by writing less code.
Features of jQuery

Figure Features of jQuery
munotes.in

Page 149


Introductions to jQuery

149 1. Document Object Manipulation : Due to jQuery it is easy to select
DOM elements and manipulate their contents by using cross -browser
open source selector engine called Sizzle.
2. Event Handling : jQuery allows to capture various events such as a
user clicking on the link and there is no need to clutter the HTML code
with because of event handlers.
3. Ajax Support: jQuery also helps to develop responsive websites with
the help of Ajax technology
4. Animation: jQuery have its own number of animations effects which
can be used on website to make them more eye catchy
5. Lightweight : It is a very lightweight and hence fast library
6. Cross browser support : jQuery has a cross browser support and it
works with number of browsers.

Methods to add jQuery
There are two methods to add jQuery in a website
1. Downloading the jQuery library from jQuery.co m : While
downloading there are two different versions are available ie. Production
version which is a compressed one and used for live websites and the
another version is Development version which is used for testing and
developmet as it is uncompressed a nd helps us to read the code.
When we download jquery -2.1.3.min.js file from
https://jquery.com/download/ link and store it in a directory of a website
we will be able to jquery library in HTML. Following c oderefelects how
jquery library is included in HTML


The jQuery Example




Hello




2. Including jQuery from a CDN (Content Delivery Network) : jQuery
library can be inc luded directly into HTML code from Content Delivery
Network. Google and Microsoft provides latest versions for such type of
content delivery
The following code displays usage of jQuery library from Google CDN


The jQuery Example




Hello





munotes.in

Page 151


Introductions to jQuery

151 6.1.1 Fundamentals
The jQuery library enables to manipulate an HTML page after it is
displayed by the browser. It also allows us to use various animation effects
and develops interactive web pages. It also p rovides tools for
communication with a server without reloading the page. To do all those
things . First, we should be aware of jQuery basics, and at how we can
use jQuery to perform its core functionality:
1. Meaning of $ : The jQuery library provides jQue ry () function which
allows us to select the elements using CSS selectors. We can do this by
writing
varlistItems = jQuery( 'li' ); however the function jQuery() can be
shortened and can be written as varlistItems = $( 'li' ); When we
call $() function an d pass a selector to it, it creates a new jQuery object. In
javascript, functions are acting as objects also so they also have methods
and properties as well .

2. $(document).ready() : Before using jQuery on our page we should
make ensure that page is in re ady state for being get manipulated.
$(document).ready() accomplish this by putting the code in this function

3. Other ways to create jQuery Object : In addition to passing simple
select $() there are some other ways to create jQuery object

Sr.No. Way to c reate a jQuery
object Code
1 Creating jQuery object
from DOM element $( document.body.children[0] );
2 creating a jQuery object
from a list of DOM
elements $( [ window, document ] );
3 making a selection in the
context of a DOM
element varfirstBodyChil d =
document.body.children[0];
$( 'li', firstBodyChild )
4 making a selection within
a previous selection var paragraph = $( 'p' );
$( 'a', paragraph );

4. Creating new elements: When we pass HTML code snippet to $() it
creates a new element in memory. Th at means the element will get created
but it will not be placed on the page until we place it on the page.
Following are some ways how we can create elements

munotes.in

Page 152


Skill Enhancement: Web
Programming
152 Sr.No. Way to create a jQuery
Element Code
1 creating a new


element with no content $( '

' );
2 creating a new


element with content $( '

Hello!

' );
3 creates a new

with
content and class $( '

Hello!' );
4 passing an object with
information and
creating an object $( '

', {
html: 'Hello!',
'class': 'greet'
});

6.1.2 Selectors :
jQuery selector is a function which makes use of expressions and finds out
matching elements from a Document Object Model. Following are some
criteria mentioned in the table. These items can be used alone or with
comb ination of other selectors. All jQuery selectors start with a dollor
sign and parenthesis e.g. $(). It is known as the factory function.
Sr. No Seelector Description
1 Tag Name Represents a tag name available in DOM e.g.
$(‘p’) selects all paragraphs in

tag in the
document
2 Tag ID Shows a tag available with the given ID in the
DOM. For example $('#someid') selects the
single element in the document that has an ID of
some -id.
3 Tag Class Shows a tag available with the given class in the
DOM. For ex ample $('.some -class') selects all theelements in the document that have a class of
someclass.

Following example will illustrate the use of tag selector where all the
paragraphs are set with background color teal

munotes.in

Page 153


Introductions to jQuery

153

First jQuery Example




This is first paragraph.


This is second paragraph.


This is third paragraph.




Using Selectotrs :
Selectors are very useful and require at each step while mak ing use of
jQuery. They helps us to get the exact element which is needed from
HTML document.
Sr.No Selector Description
1 Name Selects all elements which match with the given
element Name.
2 #ID Selects a single element which matches with the
given ID.
3 .class Selects all elements which matches with the given
Class.
4 Universal
(*) Selects all elements available in a DOM.
5 Multiple
Elements
X,Y,Z Selects the combined results of all the specified
selectors X,Y or Z

Following table gives informatio n about different jQuery selectors with
the help of examples
munotes.in

Page 154


Skill Enhancement: Web
Programming
154 Sr.No. Selector Example Description
1 * $("*") selects all elements.
2 #id $("#firstname") selects the element with
id="firstname"
3 .class $(".primary") selects all elements with
class="prim ary"
4 class,.class $(".primary,.sec
ondary") selects all elements with the
class "primary" or
"secondary"
5 element $("p") selects all p elements.
6 el1,el2,el3 $("h1,div,p") selects all h1, div, and p
elements.
7 :first $("p:first") selects the first p element
8 :last $("p:last") selectsthe last p element
9 :even $("tr:even") selects all even tr elements
10
:odd $("tr:odd") selects all odd tr elements
11 :first -child $("p:first -child") Selects all p elements that are
the first child of their paren t
12 :first -of-type $("p:first -of-
type") selects all p elements that are
the first p element of their
parent
13 :last-child $("p:last -child") selects all p elements that are
the last child of their parent
14 :last-of-type $("p:last -of-
type") selects all p elements that are
the last p element of their
parent
15 :nth-child(n) $("p:nth -
child(2)") Selects all p elements that are
the 2nd child of their parent
16 :nth-last-
child(n) $("p:nth -last-
child(2)") Selects all p elements that are
the 2nd child of the ir parent,
counting from the last child
17 :nth-of-
type(n) $("p:nth -of-
type(2)") Selects all p elements that are
the 2nd p element of their
parent munotes.in

Page 155


Introductions to jQuery

155 18 :nth-last-of-
type(n) $("p:nth -last-of-
type(2)") Selects all p elements that are
the 2nd p element of the ir
parent, counting from the last
child
19 :only -child $("p:only -
child") Selects all p elements that are
the only child of their parent
20 :only -of-type $("p:only -of-
type") Selects all p elements that are
the only child, of its type, of
their parent
21 parent > child $("div > p") Selects all p elements that are
a direct child of a div element 22 parent
descendant $("div p") Selects all p elements that are
descendants of a div element
23 element +
next $("div + p") It selects the p element that
are next to each div elements
24 element ~
siblings $("div ~ p") It selects all p elements that
are siblings of a div element
25 :eq(index) $("ulli:eq(3)") Selects the fourth element in
a list (index starts at 0)
26 :gt(no) $("ulli:gt(3)") Select the list eleme nts with
an index greater than 3
27 :lt(no) $("ulli:lt(3)") Select the list elements with
an index less than 3
28 :not(selector) $("input:not(:em
pty)") Select all input elements that
are not empty
29 :header $(":header") Select all header elements h1,
h2 ...
30 :animated $(":animated") Select all animated elements
31 :focus $(":focus") Select the element that
currently has focus
32 :contains(text
) $(":contains('He
llo')") Select all elements which
contains the text "Hello"
33 :has(selector) $("div:has (p)") Select all div elements that
have a p element
34 :empty $(":empty") Select all elements that are
empty munotes.in

Page 156


Skill Enhancement: Web
Programming
156 35 :parent $(":parent") Select all elements that are a
parent of another element
36 :hidden $("p:hidden") Select all hidden p elements
37 :visible $("table:visible"
) Select all visible tables
38 :root $(":root") Selects the document's root
element
39 :lang(languag
e) $("p:lang(de)") Select all p elements with a
lang attribute value starting
with "de"
40 [attribute] $("[href]") Select all elemen ts with a
href attribute
41 [attribute=val
ue] $("[href='default
.htm']") Select all elements with a
href attribute value equal to
"default.htm"
42 [attribute!=va
lue] $("[href!='defaul
t.htm']") Selects all elements with a
href attribute value not equal
to "default.htm"
43 [attribute$=v
alue] $("[href$='.jpg']
") Selects all elements with a
href attribute value ending
with ".jpg"
44 [attribute|=val
ue] $("[title|='Tomo
rrow']") Select all elements with a
title attribute value equal to
'Tomorrow', or starting w ith
'Tomorrow' followed by a
hyphen
45 [attribute^=va
lue] $("[title^='Tom']
") Select all elements with a
title attribute value starting
with "Tom"
46 [attribute~=v
alue] $("[title~='hello'
]") Select all elements with a
title attribute value
containing the specific word
"hello"
47 [attribute*=v
alue] $("[title*='hello'
]") Select all elements with a
title attribute value
containing the word "hello"
48 :input $(":input") Selects all input elements
49 :text $(":text") Selects all input elements
with type="te xt" munotes.in

Page 157


Introductions to jQuery

157 50 :password $(":password") Selects all input elements
with type="password"
51 :radio $(":radio") Selects all input elements
with type="radio"
52 :checkbox $(":checkbox") Itwill select all input
elements with
type="checkbox"
53 :submit $(":submit") Selects all input elements
with type="submit"
54 :reset $(":reset") Selects all input elements
with type="reset"
55 :button $(":button") Selects all input elements
with type="button"
56 :image $(":image") Selects all input elements
with type="image"
57 :file $(":file") Selects all input elements
with type="file"
58 :enabled $(":enabled") Selects all enabled input
elements
59 :disabled $(":disabled") Selects all disabled input
elements
60 :selected $(":selected") Selects all selected input
elements
61 :checked $(":checked") Selects all checked input
elements

6.1.3 Methods to access HTML attributes
The following table displays all the methods which can be used to
manipulate HTML documents
Sr.No Method Description
1 addClass() Adds one or more than one class names to
selected elements
2 after() Inserts the content after selected elements
3 append() Inserts the content at the end of selected
elements munotes.in

Page 158


Skill Enhancement: Web
Programming
158 4 appendTo() Inserts the HTML elements at the end of
selected elements
5 attr() Sets or returns attributes/values of selected
elements
6 before() Inserts the content before selected elements
7 clone() Makes a copy of selected elements
8 css() Sets or returns one or more style properties
for selected elements
9 detach() Removes selected elements (keeps data and
events)
10 empty() Removes all child nodes and content from
selected elements
11 hasClass() Checks if any of the selected elements have a
specified class name
12 height() Sets or returns the height of selected
elements
13 html() Sets or returns the content of selected
elements
14 innerHeight() Returns the height of an element (includes
padding, but not border)
15 innerWidth() Returns the width of an element (includes
padding, but not border)
16 insertAfter() Inserts HTML elements after selected
elemen ts
17 insertBefore() Inserts HTML elements before selected
elements
18 offset() Sets or returns the offset coordinates for
selected elements (relative to the document)
19 offsetParent() Returns the first positioned parent element
20 outerHeig ht() Returns the height of an element (includes
padding and border)
21 outerWidth() Returns the width of an element (includes
padding and border)
22 position() Returns the position (relative to the parent
element) of an element munotes.in

Page 159


Introductions to jQuery

159 23 prepend() Inserts content at the beginning of selected
elements
24 prependTo() Inserts HTML elements at the beginning of
selected elements
25 prop() Sets or returns properties/values of selected
elements
26 remove() Removes the selected elements (including
data and events)
27 removeAttr() Removes one or more attributes from
selecte d elements
28 removeClass() Removes one or more classes from selected
elements
29 removeProp() Removes a property set b y the prop() method
30 replaceAll() Replaces selected elements with new HTML
elements
31 replaceWith() Replaces selecte d elements with new content
32 scrollLeft() Sets or returns the horizontal scrollbar
position of selected elements
33 scroll Top() Sets or returns the vertical scrollbar position
of selected elements
34 text() Sets or returns the text content of selected
elements
35 toggleClass() Toggles between adding/removing one or
more classes from selected elements
36 unwrap() Removes the parent element of the selected
elements
37 val() Sets or returns the value attribute of the
selected elements (for form elements)
38 width() Sets or returns the width of selected elements
39 wrap() Wraps HTML element(s) around each
selected element
40 wrapAll() Wraps HTML element(s) around all selected
elements
41 wrapInner() Wraps HTML element(s) around the content
of each selected element
munotes.in

Page 160


Skill Enhancement: Web
Programming
160 6.1.4 Traversing Methods
jQueryTraversing means moving through and is used to find or select the
HTML elements on the basi s of their relation with the other elements. It
starts with one selection and move through that selection only until it
reaches to its destination . The following image focuses HTML page as a
tree structure. With jQuery traversing one can easily move up, d own and
sideway directions in the tree

Figure HTML Page DOM Tree
The above figure illustrates the following relationship
1.

is ancestor of all
2. is descendant of
and parent of both the

  • 3. Left side
  • is child of
      and parent of both t he as well
      as descendant of
        and

        4. Right side
      • is child of
          and parent of both the as well as
          descendant of
            and

            5. Both the are siblings of each other as well as descendant of
            left
          • ,
              and

              6. is descendan t of right
            • ,
                and


                6.1.4.1 jQuery Traversing up to the Ancestors methods

                Following are the useful jQuery methods for traversing upward directions
                to the ancestors

                1. parent() : It displays the direct parent of the element.
                Eg :
                $(document). ready (function (){
                $("span" ).parent ();
                });
                Here parent of is shown munotes.in

                Page 161


                Introductions to jQuery

                161 2. parents() : This method returns all the ancestors up to the root
                element
                Eg:
                $(document). ready (function (){
                $("span" ).parents ();
                });

                Here all parent, grandparent as well as great grand par ents of are
                shown

                3. parentsUntil() : This method returns all ancestors between given two
                arguments

                Eg:
                $(document). ready (function (){
                $("span" ).parentsUntil ("div" );
                });
                Here all parents between and

                are shown

                6.1.4.2 jQuery Traversing down to the Descendants methods:
                These methods are used to traverse in the downward direction of the DOM
                tree
                Following are useful methods

                1. children() : Displays all the direct descendants of the selected
                element
                2.
                Eg :
                $(document). ready (function (){
                $("div" ).children ();
                });
                This will display descendants of


                3. find() : Finds descendant of a selected element upto the last
                descendant

                Eg:
                $(document). ready (function (){
                $("div" ).find("span" );
                });
                This will display all the descendants of


                munotes.in

                Page 162


                Skill Enhancement: Web
                Programming
                162 6.1.4.3 jQuery Tra versing sideways to the Siblings methods :
                These methods traverse sideway across the DOM tree. Following table
                illustrates the methods used moving sideways towards the siblings
                Sr.
                No Method Description
                1 Siblings() Displays all the sibling elements of the selected element
                2 next() Displays next sibling element of the selected element.
                3 nextAll() Displays all next sibling elements of the selected
                element
                4 nextUntil() Displays all next sibling elements between two given
                arguments.
                5 prev() Displays previous sibling element of the selected
                element.
                6 prevAll() Displays all previous sibling elements of the selected
                element
                7 prevUntil() Displays all previous sibling elements between two
                given arguments.


                6.1.4.4 jQuery Traversing - Filtering :
                Filterin g traverse allows to select specific element on the basis of its
                position in a group of elements and on the basis of matching criteria.

                Sr.No Method Description
                1 Firs() Displays the first element of the specified
                elements.
                2 Last() Displays the last element of the specified
                elements.
                3 Eq() Displays an element with a specific index
                number of the selected elements
                4 Filter() Elements that do not match the specified
                criteria are removed and those that match will
                be returned.
                5 Not() Displays all el ements that do not match the
                criteria. munotes.in

                Page 163


                Introductions to jQuery

                163 Following table shows all the Filtering traverse methods

                6.1.5 Manipulators, Events, Effects

                6.1.5.1 Manipulators :
                jQuery provides various methods for DOM manipulation, Attributes
                Manipulation and Dimension manipulation
                1. DOM Manipulation Methods


                2. Attributes Manipulation Methods
                Sr. No Method Description
                1 append() Adds the content to the end of
                elementprovided by a selector.
                2 before() Adds content (new or existing DOM
                elements) before an elementprovided by
                a selector.
                3 after() Adds content (new or exist ing DOM
                elements) after an elementprovided by a
                selector.
                4 prepend() Adds content at the beginning of an
                elementprovided by a selector.
                5 remove() Removes element(s) from DOM which
                is provided by selector.
                6 replaceAll() Replaces target element with th e
                specific element.
                7 wrap() Wraps an HTML structure around each
                element which is provided by selector.
                Sr. No Method Description
                1 attr() Get or set the value of provided attribute
                of the target element
                2 prop() Get o r set the value of provided property
                of the target element
                3 html() Get or set html content to the provided
                target element
                4 text() Get or set text for the provided target
                element
                5 val() Get or set value property of the provided
                target element. munotes.in

                Page 164


                Skill Enhancement: Web
                Programming
                164 3. Dimen sion Manipulation Methods

                6.1.5.2 Events :
                In many of the Web Applications to perform a specific operation the user
                has to trigger some action. So this triggered action is called as event.
                jQuery provides methods to handle Dom Events. They are categorized into
                Form Events, Keyboard Events, Mouse Even ts, Browser Events and
                Document Load Events
                1. Form Events
                Sr.No. Jquery Method Event
                1 Blur onblur
                2 Change onchange
                3 Focus onfocus
                4 Focusin onfocusin
                5 Select onselect
                6 Submit onsubmit

                S. No. Method Description
                1 height() Get or set height of the provided
                element
                2 innerHeight() Get or set inner height (padd ing +
                element's height) of the provided
                element
                3 outerHeight() Get or set outer height (border +
                padding + element's height) of the
                provided element
                4 offset() Get or set left and top coordinates of
                the provided element
                5 position() Get the current coordinates of the
                provided element
                6 width() Get o r set the width of the provided
                element
                7 innerWidth() Get or set the inner width (padding +
                element's width) of the provided
                element
                8 outerWidth() Get or set outer width (border +
                padding + element's width) of the
                provided element
                munotes.in

                Page 165


                Introductions to jQuery

                165 2. Keyboard Events

                Sr.No. Jquery Method Event
                1 keydown onke ydown
                2 keypress onkeypress
                3 Keyup onkeyup
                4 Focusout

                3. Mouse Events
                Sr.No. Jquery Method Event
                1 Click onclick
                2 Dblclick ondblclick
                3 Mousedown onmousedown
                4 Mouseenter onmouseenter
                5 Mouseleave onmouseleave
                6 Mousemove onmousemove
                7 Mouseout onmouseout
                8 Mouseover onmouseover
                9 mouseup onmouseup
                10 toggle
                11 focusout
                12 Hover

                4. Browser Events
                Sr. No jQuery Method Event
                1 error onerror
                2 resize onresize
                3 Scroll onscroll
                munotes.in

                Page 166


                Skill Enhancement: Web
                Programming
                166 5. Document Load Events
                Sr. No. jQuery Method Event
                1 load onload
                2 unload onunload
                3 Ready Onready

                6.1.5.3 Effects:
                jQuery allows to add effects such as fading, sliding, hiding showing and
                animation on the web page to make it more attractive.


                Figure jQuery Effects
                Following table shows the complete list of j Query effect methods
                Sr. No. Method Description
                1 hide() Allows to hide the matched or selected
                elements.
                2 show() Reflects or shows the selected elements.
                3 toggle() shows or hides the matched elements. In
                other words, it toggles between the hide()
                and show() methods.
                4 fadein() Reflects the matched elements by fading it
                to opaque. In other words, it fades in the
                selected elements. munotes.in

                Page 167


                Introductions to jQuery

                167 5 fadeout() Reflects the matched elements by fading it
                to transparent. In other words, it fades out
                the selected elements .
                6 fadetoggle() Reflects or hides the matched element.
                means, toggles between the fadeIn() and
                fadeOut() methods.
                7 fadeto() Allows to adjust opacity for the matched
                element. In other words, it fades in/out the
                selected elements.
                8 slidedown() Projects the matched elements with slide.
                9 slideup() hides the matched elements with slide.
                10 slidetoggle() Reflects or hides the matched elements with
                slide. In other words, it is used to toggle
                between the slideUp() and slideDown()
                methods.
                11 animate() performs animation.
                12 delay() sets delay execution for all the queued
                functions on the selected elements.

                Summary :
                jQuery is a javascript library created with the intention Write less and do
                more. It is a toolkit which simplifies the work like document t raversing,
                event handling, animtion, making ajax calls etc.
                jQuery can be added by locally downloading or by including it from CDN.
                $() is use synonymously for jQuery()
                selectors are the functions used to find matching elements from DOM with
                the help of ex pressions
                jQuery traversing finds the HTML elements based on their relations with
                other elements. It can travel into upward, downwar and side by side
                directions
                jQuery also works for data manipulation , triggering events and animations
                Practice Questins
                1. Explain the characteristics of jQuery
                2.How jQuery objec is created explain
                3. What are selectors? explain how to use selectors
                4. List down the methods used to acces HTML attributes munotes.in

                Page 168


                Skill Enhancement: Web
                Programming
                168 5. Explain traversing with the help of its different methods
                6. Exaplain what is manipulation with its methods
                7. Explain Events with the help of its methods
                Referemces
                http://jqfundamentals.com/chapter/jquery -basics
                https://www.tutorialsteacher.com/jquery/jquery -event

                





                munotes.in