• What is XHTML – XHTML stands for EXtensible HyperText Markup Language. It is a cross between HTML and XML language. – XHTML is almost identical to HTML but it is stricter than HTML. XHTML is HTML defined as an XML application. It is supported by all major browsers. – Although XHTML is almost the same as HTML but It is more important to create your code correctly, because XHTML is stricter than HTML in syntax and case sensitivity. XHTML documents are well-formed and parsed using standard XML parsers, unlike HTML, which requires a lenient HTML-specific parser. • HTML Versions • Since the early days of the web, there have been many versions of HTML: Why Use XHTML?
• XHTML was developed to make HTML more extensible and increase interoperability with other data formats. There are two main reasons behind the creation of XHTML: – It creates a stricter standard for making web pages, reducing incompatibilities between browsers. So it is compatible for all major browsers. – It creates a standard that can be used on a variety of different devices without changes. • •
• •
BAD HTML • • The above HTML code doesn't follow the HTML rule although it runs. Now a day, there are different browser technologies. Some browsers run on computers, and some browsers run on mobile phones or other small devices. The main issue with the bad HTML is that it can't be interpreted by smaller devices. • So, XHTML is introduced to combine the strengths of HTML and XML. • XHTML is HTML redesigned as XML. It helps you to create better formatted code on your site. • XHTML doesn't facilitate you to make badly formed code to be XHTML compatible. Unlike with HTML (where simple errors (like missing out a closing tag) are ignored by the browser), XHTML code must be exactly how it is specified to be. Basic Syntax
• Tags – The declaration defines this document to be HTML5 – The element is the root element of an HTML page – The
element contains meta information about the document – The element specifies a title for the document – The element contains the visible page content – The
element defines a large heading – The
element defines a paragraph • •
• Page title • • •
This is a heading
•
This is a paragraph.
•
This is another paragraph.
• • • You can easily maintain, edit, convert and format your document in the long run. • Since XHTML is an official standard of the W3C, your website becomes more compatible with many browsers and it is rendered more accurately. • XHTML combines strength of HTML and XML. Also, XHTML pages can be rendered by all XML enabled browsers. • XHTML defines quality standard for your webpages and if you follow that, then your web pages are counted as quality web pages. The W3C certifies those pages with their quality stamp. • Web Browsers – The purpose of a web browser (Chrome, IE, Firefox, Safari) is to read HTML documents and display them. – The browser does not display the HTML tags, but uses them to determine how to display the document: Basic Understanding
• What is SGML? – This is Standard Generalized Markup Language (SGML) application conforming to International Standard ISO 8879. HTML is widely regarded as the standard publishing language of the World Wide Web. – This is a language for describing markup languages, particularly those used in electronic document exchange, document management, and document publishing. HTML is an example of a language defined in SGML. • What is XML? – XML stands for EXtensible Markup Language. XML is a markup language much like HTML and it was designed to describe data. XML tags are not predefined. You must define your own tags according to your needs. • XHTML – XHTML syntax is very similar to HTML syntax and almost all the valid HTML elements are valid in XHTML as well. But when you write an XHTML document, you need to pay a bit extra attention to make your HTML document compliant to XHTML. Basic Syntax
• converting existing HTML document into XHTML document − – Write a DOCTYPE declaration at the start of the XHTML document. – Write all XHTML tags and attributes in lower case only. – Close all XHTML tags properly. – Nest all the tags properly. – Quote all the attribute values. – Forbid Attribute minimization. – Replace the name attribute with the id attribute. – Deprecate the language attribute of the script tag. • XHTML document must include four tags ,
, , and • Tags are fundamental syntactic unit of HTML. • Tags are used to specify categories of content. • Most tags appears in pairs: opening tag and closing tag. • The name of the closing tag is the name of its corresponding opening tag with a slash attached to the beginning. Whatever appears in between these two tags is the content of the tag. • The opening tag and the closing tag together specify a container for the content they enclose. • The container and its content together are called an element. • An XHTML document consists of two parts, the head and the body. • Head part provides information about the document. • Body parts provides the content of the document , which itself includes tags and attributes. • Comments :- browsers ignores the XHTML comments. • Comments in the program increase the readability of the programs. • E.g. • • ...where, rootname is the root element, and [DTD] is the actual definition. • Actually, there are slight variations depending on whether your DTD is internal or external (or both), public or private. • • The keyword PUBLIC indicates that it's a public DTD (for public distribution). • The presence of URL indicates that this is an external DTD (the DTD is defined in a document located at the URL). • The identifier indicates the formal public identifier and is required when using a public DTD. – E.g. – Standard XHTML Document Structure
• Every XHTML document must begin with an xml declaration element that simply identifies the document as being one based on XML.
– First Attribute specifies the version number (still 1.0) – Second attribute defines encoding used for the document. (unicode encoding , utf-8) Example
My First Heading
My first paragraph.
Basic Text Markup
• Paragraph – Text is normally organized into paragraph in the body of a document. – XHTML standard does not allow text to be placed directly in a document. Example 1 Example 2
This is a paragraph. This paragraph
This is a paragraph. contains a lot of lines
This is a paragraph. in the source code, but the browser
Don't forget to close your HTML ignores it. tags!
Line Breaks
• element defines a line break. • Use if you want a line break (a new line) without starting a new paragraph. • < br /> the slash indicates that the tag is both an opening and closing tag. • eg.
This is a paragraph with line breaks.
Preserving whitespace
• The text inside a
element preserves both spaces and line breaks.
Headings
• In XHTML there are six levels of headings, specified by the tags
,
,
,
,
and
. •
,
,
uses font sizes that are larger than that of the default size of text. •
uses the default size and •
and
use smaller size.
Block Quotation
• A block of text to be set off from the normal flow of text in a document.
Browsers usually indent blockquote elements.
“For 50 years, WWF has been protecting the future of nature. The world's leading conservation organization, WWF works in 100 countries and is supported by 1.2 million members in the United States and close to 5 million globally.”
Font styles and sizes
• Content – based style tags – tags indicates the particular kind of text that appears in their content. – Emphasis tag - special text content. Mostly highlighted by italic font. – Strong tag - more than emphasis tag. Mostly highlighted by bold font. – Code tag - used to specify a monospace font, usually used for program code. • Non content – based style tags- – subscript character – superscript character XHTML tags are categorized in block or inline. Inline tag :- content appears on the current line. Inline tag does not implicitly include line break . Exception is br. E.g , Block tag :- breaks the current line so that its content appears on a new line. The heading and block quote tags are block tag. Character Entities
• The special character are defined as entities which are names for the character by the browser. Horizontal Rules
• Places the horizontal lines in between the document to make it easy for reading. • It is represented by
. • The browser chose the thickness, length and horizontal placement of line. The Meta Element
Meta element :- provide additional information about a document. • It has no content and all the provided information is through attribute. • Two attributes are name and content. e.g. Web search use the information provided with the meta element to categorize web document in their indices. Images
• Image : - the image is stored in a file which is specified by an XHTML request. The image is inserted into the display of the document by the browser. • Image formats:- – GIF (Graphic Inter-change format): developed by compuserve network service provider for the specific purpose of moving images. It uses 8 bit color representation for pixels. Images use the .gif or .GIF extension. Supports transparency. – JPEG (Joint photographic expert group) :uses 24 bit color for representation for pixels. It uses .jpg or .JPG or .jpeg extension. The compression algorithm used by JPEG is better at shrinking an image than the one used by GIF. Size of JPEG is smaller than GIF but it does not support transparency. – PNG (Portable Network Graphics).: provides good replacement for both GIF and JPEG because it has best characteristics of both. – But PNG file requires more space as its compression algorithm does not compromise picture clarity. • The tag :- it is a inline tag , specifies an image that is to appear in a document. • It includes two attributes: src and alt – Src :- specifies the file containing the image. – alt :- specifies text to be displayed when it is not possible to display the image. • Two optional attributes of img width and height can be included to specify the size of the rectangle for the image. • E.g. XHTML Document Validation
• XHTML Document Validation: the W3C provides a convenient Web-based way to validate XHTML document against its standard. • The URL of the service is http://validator.w3.org/ file-upload.html • The XHTML validation system is a valuable tool for producing documents that adhere to W3C standards. • The specific std against which the document is checked is given in the DOCTYPE command. Hypertext Links
• Links are used to allow readers to jump to specific parts of a Web page. • Links can be useful if your webpage is very long. • To make a bookmark, you must first create the bookmark, and then add a link to it. • When the link is clicked, the page will scroll to the location with the bookmark. • Example • First, create a bookmark with the id attribute: –
Chapter 4
• Then, add a link to the bookmark ("Jump to Chapter 4"), from within the same page: – Jump to Chapter 4 • Or, add a link to the bookmark ("Jump to Chapter 4"), from another page:
• Jump to Chapter 4 • Chapter 1 • This chapter explains ba bla bla • Chapter 2 • This chapter explains ba bla bla • Chapter 3 • This chapter explains ba bla bla • Chapter 4 • This chapter explains ba bla bla • Chapter 5 • This chapter explains ba bla bla • Chapter 6 • This chapter explains ba bla bla Lists
• HTML offers web authors three ways for specifying lists of information. All lists must contain one or more list elements. Lists may contain − –
− An unordered list. This will list items using plain bullets. – − An ordered list. This will use different schemes of numbers to list your items. –
− A definition list. This arranges your items in the same way as they are arranged in a dictionary. • Unordered Lists – An unordered list is a collection of related items that have no special order or sequence. – This list is created by using block tag
tag. – Item of a list is specified with an
tag(li-list item) – Each item in the list is marked with a bullet. HTML Unordered List
Beetroot
Ginger
Potato
Radish
• This will produce the following result − • Beetroot • Ginger • Potato • Radish • Ordered Lists – If you are required to put your items in a numbered list instead of bulleted, then HTML ordered list will be used. – This list is created by using tag. – The numbering starts at one and is incremented by one for each successive ordered list element tagged with
. HTML Ordered List
Beetroot
Ginger
Potato
Radish
• This will produce the following result − 1. Beetroot 2. Ginger 3. Potato 4. Radish • Definition Lists : HTML and XHTML supports a list style which is called definition lists where entries are listed like in a dictionary or encyclopedia. – The definition list is the ideal way to present a glossary, list of terms, or other name/value list. • Definition List makes use of following three tags. –
− Defines the start of the list –
− A term –
− Term definition –
− Defines the end of the list HTML Definition List
HTML
This stands for Hyper Text Markup Language
HTTP
This stands for Hyper Text Transfer Protocol
• This will produce the following result −
HTML This stands for Hyper Text Markup Language HTTP This stands for Hyper Text Transfer Protocol Table
• The XHTML tables allow web authors to arrange data like text, images, links, other tables, etc. into rows and columns of cells. • The XHTML tables are created using the block tag
. • The most common attribute for the
tag is border. • There are two kinds of lines in tables – Border : the line around the outside of the whole table. – Rules : the line that separate the cell from each other. – The browser has default widths for table border and rules which is assigned by the value “border” to border attribute. Otherwise, a number can be given as border’s value. –
tag - used for the table title which can immediately follow the opening
tag. –
tag - is used to create table rows. –
tag - is used to create data cells. • The elements under
are regular and left aligned by default HTML Table Header
Employee Database
Name
Salary
Ramesh Raman
5000
Shabbir Hussein
7000
• This will produce the following result − • The rowspan and colspan attributes – In many cases tables have multiple levels of row or column labels in which one label covers two or more secondary labels. – The colspan attributes specification in a table header or table data tag tells the browser to make the cell as wide as the specified number of rows below it in the table.
Report
Month
Savings
January
$100
February
$80
Sum: $180
Month
Savings
Savings for holiday!
January
$100
$50
February
$80
• The align and valign attributes – The placement of the content within a table cell can be specified with the align and valign attributes in the
,
, and
tag. – The align attribute has the possible values left, right and center for horizontal placement of the content within a cell. – The default alignment for th cell is center and for td it is left . – If align is specified in a
tag , it applies to all of the cells in the row. – If it is included in a
or
tag, it only applies to that cell. • The valign attribute of the
and
tags has the possible value top and bottom. • The default vertical alignment for both headings and data is center. • Because valign applies only to a single cell, there is never any point in specifying center.
the align and valign
column Lable 1
column Lable 2
column Lable 3
align
left
center
right
valign
top
bottom
The cellpadding and cellspacing
• The table tag has two attributes that can be used to specify the spacing between the content of a table cell and the cell’s edge and spacing between adjacent cells. • The cellpadding : – attribute specifies the space, in pixels, between the cell wall and the cell content. – This prevent text from being too close to the edge of the cell.
• The cellspacing attribute is used to specifies the distance between cells in a table.
Employee Database
Name
Salary
address
Ramesh
5000
whitefield
Shabbir
7000
kundanahalli
Table Section
• Tables naturally occur in two and sometimes three parts: header, body and footer. • These three parts can be denoted in XHTML with the thead, tbody and tfoot elements. • The header includes the column labels. • The body includes the data of the table, including the row labels. • The footer, when it appears, sometimes has the column label repeated after the body. • In some table, the footer contains total for the columns of data. • The table can have multiple body sections, in which case the browser may delimit them with thicker horizontal lines. Forms
• Most common way for a user to communicate information from a web browser server is through a form. • XHTML provides tags to generate the commonly used objects on a screen form. • These objects are called controls or widgets. • There are controls for single-line and multiple-line text collection, checkboxes, radio buttons, and menus, among other. • All control line tags are inline tags. • Text or button selection gather information from the user. • Together the value of all the controls in a form are called the form data. • Every form requires a submit button which is used to encode and send the form data to the Web server for processing. • The
Note that the form itself is not visible.
Also note that the default width of a text input field is 20 characters.
• A text control :- refers to as text box, creates a horizontal box into which the user can type a line of text. • Default size is 20 character, but size can vary among browser. • Size of text can be specified by using size attribute of . • If text is very long then the box is scrolled. • You can avoid scrolling by fixing maximum number of character by using maxlength attribute. • E.g.
• Alfred paul von frickenburger • output – Ed paul von frickenburger – The text box would collect the whole string but the string would be scrolled to the right • E.g.
Input: Alfred paul von frickenburger Output : Alfred paul von frickenbu • Password :- if the content of a text box should not be displayed when it is entered by the user, a password control can be used. • Text boxes as well as most other control elements, should be labeled. Labeling could be done by simply inserting text into the approximate places in the form. Phone: • There is no connection between the label and the control. • Control and the label can be connected by putting the control and its label in the content of a label element. • • Now, the text box and its label are encapsulated together. • Benefits of labeling : – Browser often render the text content of a label element differently to make it stand out. – If the text content of a label element is selected, the cursor is implicitly moved to the control. – the text content of a label element can be rendered by a speech synthesizer on the client machine when selected. This can be a great aid to a user with a visual disability. • Checkbox and radio controls : used to collect multiple- choice input from the user. – A checkbox control is a single button that is either on or off. – If a checkbox button is on, the value associated with the name of the button is the string assigned to its value attribute. – A checkbox button does not contribute to the form data if it is off. – Every checkbox button require a name attribute and a value attribute in its tag. – For form processing on the server, the name identifies the button and the value is its value (if it is checked).
Show checkboxes:
• Radio button :- similar to checkbox. – The difference between a group of radio buttons and a group of checkboxes is that only one radio button can be on or pressed at any time. – Every time a radio button is pressed, the button in the group that was previously on is turned off. – The type value for radio buttons is radio. – All radio buttons in a group must have the name attribute set in the tag, and all radio buttons in a group have the same name. • A radio button definition may specify which button is to be initially in the pressed, or on state. • This is indicated by including the checked attribute, set to the value checked, in the of the button’s definition. • If no radio button in a group is specified as being checked, the browser usually checks the first button in the group. • •
•
Radio Buttons
•
• •
• The
• • • • • • • • •
• Select tag with size:- – The size attribute specifies the number of visible options in a drop-down list. – If the value of the size attribute is greater than 1, but lower than the total number of options in the list, the browser will add a scroll bar to indicate that there are more options to view.
• The
HTML Forms
If you click the "Submit" button, the form-data will be sent to a page called "/action_page.php".
Assignment 1
• Print the squares of the numbers 1 - 20. Each number should be on a separate line, next to it the number 2 superscripted, an equal sign and the result. (Example: 102 = 100) • Print two paragraphs that are both indented using the command. • Print two lists with any information you want. One list should be an ordered list, the other list should be an unordered list. • Prints an h1 level heading followed by a horizontal line whose width is 100%. Below the horizontal line print a paragraph relating to the text in the heading. • Print some preformatted text of your choosing. (hint: use the
tag) • Print a long quote and a short quote. Cite the author of each quote. UNIT - 2 Introduction
• What is CSS? – CSS stands for Cascading Style Sheets – CSS describes how HTML elements are to be displayed on screen, paper, or in other media – CSS saves a lot of work. It can control the layout of multiple web pages all at once – External stylesheets are stored in CSS files • Why Use CSS? – CSS is used to define styles for your web pages, including the design, layout and variations in display for different devices and screen sizes. • CSS Solved a Big Problem – HTML was NEVER intended to contain tags for formatting a web page! – HTML was created to describe the content of a web page, like: •
This is a heading
•
This is a paragraph.
– When tags like , and color attributes were added to the HTML 3.2 specification, it started a nightmare for web developers. Development of large websites, where fonts and color information were added to every single page, became a long and expensive process. – To solve this problem, the World Wide Web Consortium (W3C) created CSS. – CSS removed the style formatting from the HTML page! Levels of Style Sheet
• The three levels of style sheet are – Inline :- apply to the content of a single element. – Document level :- style sheet apply to the whole body of the document. – External :- style sheet can apply to the bodies of any number of documents. Inline style sheet have precedence over document style sheet, which have precedence over external style sheet. • Inline CSS – An inline CSS is used to apply a unique style to a single HTML element. – An inline CSS uses the style attribute of an HTML element. – This example sets the text color of the
element to blue:
This is a Blue Heading
• Internal/ document level CSS – An internal CSS is used to define a style for a single document page. – An internal CSS is defined in the
section of an HTML page, within a
This is a heading
This is a paragraph.
• External CSS – An external style sheet is used to define the style for many HTML pages. – With an external style sheet, you can change the look of an entire web site, by changing one file! – To use an external style sheet, add a link to it in the
section of the HTML page: – An external style sheet can be written in any text editor. The file must not contain any HTML code, and must be saved with a .css extension. Css file body { color: powderblue; } h1 { color: blue; }
This is a heading
p { color: red;
This is a paragraph.
}
Selector Forms
• In CSS, selectors are patterns used to select the element(s) you want to style. • Simple selector forms – The simplest selector form is a single element name, such as h1. – In this case, the property values in the rule apply to all occurrences of the named element. – The selector could be a list of elements names, separated by commas, in which case the property values apply to all occurrences of all the named elements. – h1 {font-size: 24pt;} – h2, h3 {font-size: 20pt;} • Contextual/descendent selector – Style can only apply to elements in certain positions in the document. – This is done by listing the element hierarchy in the selector, with only whitespace separating the element names. • Body b em {font-size: 14pt;} • Class selectors – Class selector specifies different occurrences of the same tag to use different style specifications. P.normal {property-value list} P.warning {property-value list}
------
------
• Generic selectors – Class of style specifications that applies to the content of more than one kind of tag. – The generic class is defined without a tag name. – It starts with period. .sale { property – value list}
Body of the document
weekend sale
…..
…
• Id selector – An id selector allows the application of a style to one specific element. – The general form of id selector is – #specific-id {property-value list} – E.g. • #section14 {font-size: 20}
•
1.4 claico cats
• Universal Selector:- – The universal selector denoted by an asterisk (*) applies its style to all elements in the document. * {color: red;} – Makes all elements in the document red. – Not often useful. • What are Pseudo-classes? – CSS pseudo-classes are used to add special effects to some selectors. – You do not need to use JavaScript or any other script to use those effects. For example, it can be used to: • Style an element when a user mouses over it • Style visited and unvisited links differently • Style an element when it gets focus – A simple syntax of pseudo-classes is as follows −
selector:pseudo-class {property: value} • The most commonly used pseudo-classes are as follows −
Value Description :link Use this class to add special style to an unvisited link. :visited Use this class to add special style to a visited link. :hover Use this class to add special style to an element when you mouse over it. :active Use this class to add special style to an active element. :focus Use this class to add special style to an element while the element has focus. :first-child Use this class to add special style to an element that is the first child of some other element. :lang Use this class to specify a language to use in a specified element. • While defining pseudo-classes in a block, following points should be noted − – a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective. – a:active MUST come after a:hover in the CSS definition in order to be effective. – Pseudo-class names are not case-sensitive. – Pseudo-class are different from CSS classes but they can be combined.
Note: a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.
Note: a:active MUST come after a:hover in the CSS definition in order to be effective.
Property value Forms
• CSS1 includes 60 different properties in seven categories: – Font – Lists – Alignment of text – Margins – colors – Backgrounds – borders • Property values can appear in a variety of forms. • Keyword property value :- used when there are only few possible values and they are predefined. E.g small, large and medium. • Number values:- used when no meaningful units can be attached to a numeric property value. • Length value • Percentage value • URL value • Color Font Properties
• The font-family property is used to change the face of a font. • The font-style property is used to make a font italic or oblique. • The font-variant property is used to create a small-caps effect. • The font-weight property is used to increase or decrease how bold or light a font appears. • The font-size property is used to increase or decrease the size of a font. • The font property is used as shorthand to specify a number of other font properties. • Set the Font Family – Following is the example, which demonstrates how to set the font family of an element. Possible value could be any font family name. • •
• •
This text is rendered in either georgia, garamond, or the default serif font depending on which font you have at your system.
• • • It will produce the following result −
This text is rendered in either georgia, garamond, or the default serif font depending on which font you have at your system. • Set the Font Style – Following is the example, which demonstrates how to set the font style of an element. Possible values are normal, italic and oblique.
This text will be rendered in italic style
It will produce the following result −
This text will be rendered in italic style • Set the Font Variant – The following example demonstrates how to set the font variant of an element. Possible values are normal and small-caps.
This text will be rendered as small caps
It will produce the following result −
This text will be rendered as small caps • Set the Font Weight – The following example demonstrates how to set the font weight of an element. The font-weight property provides the functionality to specify how bold a font is. Possible values could be normal, bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800, 900. •
This font is bold.
This font is bolder.
This font is 500 weight.
It will produce the following result − • This font is bold. • This font is bolder. • This font is 500 weight. • Set the Font Size • The following example demonstrates how to set the font size of an element. The font-size property is used to control the size of fonts. Possible values could be xx-small, x-small, small, medium, large, x-large, xx-large, smaller, larger, size in pixels or in %.
This font size is 20 pixels
This font size is small
This font size is large
• It will produce the following result
• This font size is 20 pixels • This font size is small • This font size is large • Set the Font Size Adjust – The following example demonstrates how to set the font size adjust of an element. This property enables you to adjust the x-height to make fonts more legible. Possible value could be any number.
This text is using a font-size-adjust value.
It will produce the following result −
This text is using a font-size-adjust value. • Set the Font Stretch – The following example demonstrates how to set the font stretch of an element. This property relies on the user's computer to have an expanded or condensed version of the font being used. – Possible values could be normal, wider, narrower, ultra-condensed, extra-condensed, condensed, semi-condensed, semi-expanded, expanded, extra- expanded, ultra-expanded.
If this doesn't appear to work, it is likely that your computer doesn't have a condensed or expanded version of the font being used.
• It will produce the following result − If this doesn't appear to work, it is likely that your computer doesn't have a condensed or expanded version of the font being used. • Shorthand Property – You can use the font property to set all the font properties at once. For example −
Applying all the properties on the text at once.
• It will produce the following result −
Applying all the properties on the text at once. • Text Decoration :- The text decoration property is used specify some special features of text. • Possible Values – none − No decoration should be added to the inline text. – underline − An underline is drawn beneath the inline text. – overline − An overline is drawn above the inline text. – line-through − A line should be drawn through the middle of the inline text. – blink − The inline text should blink on and off, analogous to the BLINK element introduced by Netscape.
This is heading 1
This is heading 2
This is heading 3
This is heading 4
This is heading 5
• The letter-spacing property :- increases or decreases the space between characters in a text.
This is heading 1
This is heading 2
This is heading 3
List properties
• Lists are very helpful in conveying a set of either numbered or bullet points. • The CSS list properties allow you to: – Set different list item markers for ordered lists – Set different list item markers for unordered lists – Set an image as the list item marker • We have the following CSS properties, which can be used to control lists: • The list-style-type allows you to control the shape or appearance of the marker. • The list-style-image specifies an image for the marker rather than a bullet point or number. • The list-style-type property allows you to control the shape or style of bullet point in the case of unordered lists and the style of numbering characters in ordered lists.
Example of unordered lists:
Coffee
Tea
Coca Cola
Coffee
Tea
Coca Cola
Example of ordered lists:
Coffee
Tea
Coca Cola
Coffee
Tea
Coca Cola
• The list-style-image property – The list-style-image allows you to specify an image so that you can use your own bullet style.
image of plane
Coffee
Tea
Coca Cola
Alignment of text
• The first line of a paragraph can be indented using the text – indent property. • This property takes either a length or a percentage value.
The first line of a paragraph can be indented using the text – indent property. This property takes either a length or a percentage value.
• The text-align property , for which the possible keyword values are left, right and justify is used to arrange text horizontally.
CSS text-align Example
May, 2014
In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since. 'Whenever you feel like criticizing anyone,' he told me, 'just remember that all the people in this world haven't had the advantages that you've had.'
Note: Resize the browser window to see how the value "justify" works.
• Float property :- it is used to specify that text should flow around some element. • The possible values for float are left, right and none which is the default.
The float Property
In this example, the image will float to the right in the text, and the text in the paragraph will wrap around the image.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor.
Color
• Color group :- – Three levels of collections of colors might be used by an XHTML document. – The smallest useful set of colors includes only those that have standard names and are guaranteed to be correctly displayable by all browsers on all color monitors. – This collection of sixteen colors is called the named colors. – A larger set of color, called the Web palette, includes 216 colors • Color properties:- – The color property is used to specify the foreground color of XHTML elements. !DOCTYPE html>
This is heading 1
This is an ordinary paragraph. Notice that this text is red. The default text-color for a page is defined in the body selector.
This is a paragraph with class="ex". This text is blue.
• The background-color property is used to set the background color of an element where the element could be the whole body of the document.
The background-color Property
The background color can be specified with a color name.
• The
and Tags:- – The
tag defines a division or a section in an HTML document. – The
element is often used as a container for other HTML elements to style them with CSS or to perform certain tasks with JavaScript.
This is some text.
This is a heading in a div element
This is some text in a div element.
This is some text.
• :- provides special font properties to some part of the paragraph. • It can give different font size and color to word or phase in a line.
My mother has blue eyes and my father has dark green eyes.
The Box Model
• Virtually all the documents can have borders. • These borders have various styles such as color and width. • The amount of space between the content of an element and its border known as padding. • The space between the border and an adjacent element known as the margin. • Explanation of the different parts: – Content - The content of the box, where text and images appear – Padding - Clears an area around the content. The padding is transparent – Border - A border that goes around the padding and content – Margin - Clears an area outside the border. The margin is transparent
Demonstrating the Box Model
The CSS box model is essentially a box that wraps around every HTML element. It consists of: borders, padding, margins, and the actual content.
This text is the actual content of the box. We have added a 25px padding, 25px margin and a 25px green border. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
UNIT - 3
The basic of JavaScript Overview of JavaScript • JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. • JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers. • The ECMA-262 Specification defined a standard version of the core JavaScript language. – JavaScript is a lightweight, interpreted programming language. – Designed for creating network-centric applications. – Complementary to and integrated with Java. – Complementary to and integrated with HTML. – Open and cross-platform • Javascript can be divided into three parts – The core - it is the heart of the language, including its operators, expressions, statements and subprograms. – Client-side javascript :- is a collection of object that support control of a browser and interactions with users. – Server side :- it is a collection of objects that make the language useful on a web server. Advantages of JavaScript • The merits of using JavaScript are − – Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server. – Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have forgotten to enter something. – Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard. – Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors. Limitations of JavaScript • We cannot treat JavaScript as a full-fledged programming language. It lacks the following important features − – Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason. – JavaScript cannot be used for networking applications because there is no such support available. – JavaScript doesn't have any multithreading or multiprocessor capabilities. – Once again, JavaScript is a lightweight, interpreted programming language that allows you to build interactivity into otherwise static HTML pages. • JavaScript can be implemented using JavaScript statements that are placed within the . • You can place the • The java script has two types of comments • // :- two adjacent slashes appears on a line , the rest of the line is considered a comment. • /* ------*/ :- both single line and multiple-line comment can be written using /* */ to terminate. • There are two issues regarding embedding JavaScript in XHTML document. 1. There are some browsers still in use that recognize the
• String: A string (or a text string) is a series of characters like "John Doe". • Strings are written with quotes. You can use single or double quotes. • All string literals are primitive values. • JavaScript Strings Strings are written with quotes. You can
use single or double quotes: Volvo XC60
JavaScript Strings
Volvo XC60
Strings are written with quotes. You can use single or double quotes:
• Booleans :- Booleans can only have two values: true or false. JavaScript Booleans Booleans can have two values: true or false:
True false
JavaScript Booleans
Booleans can have two values: true or false:
• Undefined – In JavaScript, a variable without a value, has the value undefined. The typeof is also undefined. – There is no reserve word undefined. If a variable has been explicitly declared, but not assigned a value , it has the value undefined. – If the value of an undefined variable is displayed, the word “undefined” is displayed . JavaScript The value (and the data type) of a
variable with no value is undefined. undefined
JavaScript
The value (and the data type) of a variable with no value is undefined.
• Null:- Null indicate no value. A variable is null if it has not been explicitly declared or assigned a value. • If an attempt is made to use the value of a variable whose value is null, it will cause a runtime error. • Declaring Variables :- – Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container. – Variable can be used for anything. Variables are not typed, values are. – A variable can have the value of any primitive type, or it can be a reference to any object. – The type of the value of a particular appearance of a variable in a program is determined by the interpreter. – Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows. • You can also declare multiple variables with the same var keyword as follows • Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable. operator • Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called the operator. JavaScript supports the following types of operators. – Arithmetic Operators – Comparison Operators – Logical (or Relational) Operators – Assignment Operators – Conditional (or ternary) Operators • Binary operator:- – + for addition – - for subtraction – * for multiplication – / for division – % for modulus. • Unary operators :- – + plus – - negate – -- decrement – ++ increment – E.g. If a = 7 • (++a)*3 = 24 • Where as (a++)* 3 = 21 • In both cases a is set to 8. • The math object:- The Math object provides a collection of properties of Number objects and methods that operate on Number Objects. JavaScript Math.PI Math.PI returns the ratio of a
circle's circumference to its diameter:
JavaScript Math.PI
3.141592653589793
Math.PI returns the ratio of a circle's circumference to its diameter:
• Math.round() :- Math.round(x) returns the value of x rounded to its nearest integer • Math.pow():- Math.pow(x, y) returns the value of x to the power of y • Math.sqrt() :-Math.sqrt(x) returns the square root of x • Math.abs() :- Math.abs(x) returns the absolute (positive) value of x • Math.ceil() :- Math.ceil(x) returns the value of x rounded up to its nearest integer • Math.floor() :- Math.floor(x) returns the value of x rounded down to its nearest integer • Math.sin() :- Math.sin(x) returns the sine (a value between - 1 and 1) of the angle x (given in radians). • Math.cos() :- Math.cos(x) returns the cosine (a value between -1 and 1) of the angle x (given in radians). • Math.min() and Math.max() :- Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments • Math.random() :- Math.random() returns a random number between 0 (inclusive), and 1 (exclusive) • The Number object :- the number object includes a collection of useful properties that have constant values. Property Description constructor Returns the function that created JavaScript's Number prototype MAX_VALUE Returns the largest number possible in JavaScript MIN_VALUE Returns the smallest number possible in JavaScript NEGATIVE_INFINITY Represents negative infinity (returned on overflow) NaN Represents a "Not-a-Number" value POSITIVE_INFINITY Represents infinity (returned on overflow) prototype Allows you to add properties and methods to an object • NaN(not a number) :- any arithmetic operation that results in an error or that produces a value that cannot be represented as a double-precision floating-point number, such as one that is too large (overflow), returns the value NaN. • If NaN is compared for equality against any number, the comparison fails. • To determine whether a variable has the NaN value, the predefined function isNaN() must be used. false: 123 true: 0 / 0
• The toString() :-method converts a number to a string. • The String Catenation operator :- JavaScript string are not stored or treated as array of characters rather they are unit scalar values. • The + operator can also be used to add (concatenate) strings.
JavaScript Operators
JavaScript Operators
The + operator concatenates The + operator concatenates (adds) strings.
(adds) strings. John Doe
• Implicit Type conversions :- – The JavaScript interpreter performs several different implicit type conversions called as coercions. – When value of one type is used in a position that requires a value of a different , JavaScript attempts to convert the value to the type that is required. • Adding two numbers, will return the sum, but adding a number and a string will return a string
• JavaScript Operators
Adding a number and a string, returns a
JavaScript Operators
string.
Adding a number and a string, 10 returns a string.
55 Hello5
• Explicit type conversions :- there are several different ways to force type conversions, primarily between string and numbers. String that contain numbers can be converted to numbers with the string constructor, as in the following : – var str_value = string(value) – This conversion can also be done with the toString method, which has the advantage that it can be given a parameter to specify the base of the resulting number. • For eg. – Var num = 6; – Var str_value = num.toString(); – Var str_value_binary = num.toString(2);
– In the first conversion , the result is 6. – In the second conversion , the result is 110 – A number also converted to a string by concatenating it with the empty string. • String can be explicitly converted to number in a variety of ways. • The number constructor can be used as in the following : – Var number = Number(aString); – The same conversion could be specified by subtracting zero from the string as in the following: – Var number = aString – 0; • Both of these conversions has following restriction: – The number in the string cannot be followed by any character except a space. JavaScript has two predefined string functions that do not have this problem These two , parseInt and parseFloat are not string methods, so they are not called through String objects; however, they operate on the string given as parameters. 1. parseInt :- this function searches the string for an integer literals. – If one is found at the beginning of the string, it is converted to a number and returned. – If string does not begin with a valid integer literal, NaN is returned.
• ParseFloat : similar to parseInt but it searches for a floating point literal, which could have a decimal point or an exponent or both.
• String properties and methods : – The String object includes property, length, and large collection of methods. – String methods can always be used through String primitive values. String Length :- The length property returns the length of a string.
The length property returns the length of a string:
The length property returns the 26 length of a string:
• Finding a String in a String – The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string.
JavaScript String Methods
• JavaScript String Methods
The indexOf() method returns the The indexOf() method returns the position of the first occurrence of a position of the first occurrence of a specified text:
specified text: 7
• The substring() Method :- extracts a part of a string and returns the extracted part in a new string. • The method takes 2 parameters: the starting index (position), and the ending index (position). • The substring() cannot accept negative indexes. • Syntax :- substring(start, end)
JavaScript String Methods
• JavaScript String Methods The substr() method extract a part of
The substr() method extract a a string and returns the extracted part of a string parts in a new string: and returns the extracted parts in a Banana new string:
• A string is converted to upper case with toUpperCase() • A string is converted to lower case with toLowerCase() Convert string to upper case: hello world :- HELLO WORLD
Convert string to upper case:
• The charAt() Method – The charAt() method returns the character at a specified index (position) in a string JavaScript String Methods The charAt() method returns the
character at a given position in a string:
JavaScript String Methods
H
The charAt() method returns the character at a given position in a string:
• The typeof operator – It returns the type of its single operand. – typeof evaluates to “number”, “string”, or “boolean” if operand is of primitive type Number, String or respectively. – If the operand is an object or null, typeof evalutes to “object”. – If operand is a variable that has not been assigned a value typeof evaluates to “undefined”. Primitive
• JavaScript typeof The typeof operator returns the type of a
JavaScript typeof
variable or an expression.
The typeof operator returns the type of a variable or an expression.
string number
Object and Function
JavaScript typeof
JavaScript typeof
The typeof operator returns object for both The typeof operator returns object for both objects, arrays, and null.
objects, arrays, and null.
The typeof operator does not return object The typeof operator does not return object for for functions.
functions.
• Assignment statements :- – Similar to other programming languages. – It is denoted by = – A host of compound assignment operators such as += and /=. – Eg. a +=7; means a = a + 7 The Date Object
• The Date object :- use to represent the specific date and time and manipulate them. • It is a rich collection of methods. • The Date object is created, naturally with the new operator and the Date constructor, which has several forms. • E.g. var today = new Date(); • The Date and time properties of a Date object are in two forms, local and Coordinated Universal Time (UTC, which was formerly named Greenwich Mean Time). • Method of the Date object :- – toLocaleString :- A string of the Date information. – getDate :- the day of the month – getMonth :- the month of the year, as a number in the range of 0 to 11. – getDay :- the day of the week, as a number in the range of 0 to 6. – getFullYear :- the year – getTime :- the number of milliseconds since January 1, 1970. – getHours :- the number of the hour, as a number in the range of 0 to 23. – getMinutes :- the number of the minute, as a number in the range of 0 to 59. – getSeconds :- the number of the second, as a number in the range of 0 to 59. – getMilliseconds :- the number of the millisecond, as a number in the range of 0 to 59.
JavaScript new Date()
JavaScript new Tue Sep 25 2018 12:09:28 Date()
GMT-0400 (Eastern Daylight Time)
Screen output and keyboard Input
• JavaScript models the XHTML document with the Document object. • The window in which the browser displays an XHTML document is modeled with the Window object. • The Window object includes two properties, document and Window. • The document object has several properties and methods. • document.write():- used to create a script output. • alert() :- open a dialog window and display its parameter in that window. It also displays an OK button. – The parameter string to alert is not XHTML code. It is a plain text. – Therefore , the string parameter to alert may include \n but never include .
My First Web Page
My first paragraph.
• confirm() Method :- – The confirm() method displays a dialog box with a specified message, along with an OK and a Cancel button. – A confirm box is often used if you want the user to verify or accept something. – The confirm() method returns true if the user clicked "OK", and false otherwise.
Click the button to display a confirm box.
confirm("Press a button!");
• The prompt() method displays a dialog box that prompts the user for input. • A prompt box is often used if you want the user to input a value before entering a page. • When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. • The prompt() method returns the input value if the user clicks "OK". If the user clicks "cancel" the method returns null.
• alert, prompt, and confirm cause the browser to wait for a user response. • In case of alert, the OK button must pressed for the JavaScript interpreter to continue. • The prompt and confirm method wait for either OK or Cancel to be pressed. Control Statements
• Control expressions • Selection Statements :- Use if to specify a block of code to be executed, if a specified condition is true
Output :- 10 • The else Statement :- Use the else statement to specify a block of code to be executed if the condition is false.
• Output :- 55 Use the switch statement to select one of many code blocks to be executed.
Wednesday
• The For Loop – The for loop has the following syntax: for (statement 1; statement 2; statement 3) { code block to be executed }
• Statement 1 is executed (one time) before the execution of the code block. • Statement 2 defines the condition for executing the code block. • Statement 3 is executed (every time) after the code block has been executed. BMW Volvo Saab
Ford
• The While Loop :- The while loop loops through a block of code as long as a specified condition is true.
JavaScript while
• Output The number is 8 The number is 9 • The Do/While Loop • The do/while loop is a variant of the while loop. This loop will execute the
JavaScript do ... while
code block once, before checking if the condition is The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 Object Creation and Modification
• Object are often created with a new expression, which must include a call to a constructor method. • In JavaScript, the new operator creates a blank object, or one with no properties. • JavaScript object do not have type. • The constructor both creates and initialized the properties. • The following statement creates an object that initially has no properties. – var my_object = new object(); – The properties of an object are accessed using dot notation, in which the first word is the object name and the second is the property name. – Properties are not actually variables – they are just the names of values. – The number of properties in a JavaScript object is dynamic. – At any time during interpretation, properties can be added to or deleted from an object. – A property for an object is created by assigning a value to that property. – var my_car = new object(); • Create and initialize the make property – My_car.make = “Ford”; • Create and initialize model – my_car.model = “Countour SVT”; • This code creates a new object, my_car, with two properties, make and model. • Output John is 50 years old.
• Another way to create object and its properties: • Object Literal
• Created new object that has properties of my_car with properties of its own. • JavaScript Properties – Properties are the values associated with a JavaScript object. – A JavaScript object is a collection of unordered properties. – Properties can usually be changed, added, and deleted, but some are read only. • Accessing JavaScript Properties – The syntax for accessing the property of an object is: – objectName.property // person.age or – objectName["property"] // person["age"]
JavaScript Object Properties
There are two different ways to access an object property:
JavaScript Object Properties
You can use .property or ["property"].
There are two different ways to access an object property:
• JavaScript for...in Loop – JavaScript has a loop
statement , for ….in ,
JavaScript Object Properties
that is perfect for listing the properties of an compound statement
OUTPUT: • JavaScript Object Properties Name:fname value :John Name:lname value :Doe Name:age value :25 • Deleting Properties – The delete keyword
deletes a property from
JavaScript Object Properties
an object:
You can delete object properties.
• OUTPUT access a property of an object that does not exist, the value undefined is used. Array
• In JavaScript , arrays are objects . • An array is a special variable, which can hold more than one value at a time. • An array can hold many values under a single name, and you can access the values by referring to an index number. • Array elements can be primitive values or references to other objects, including other array. • JavaScript array have dynamic length. Array object creation
• Array can be created in two distinct ways. 1. Using a array literal array is a easiest way to create a JavaScript Array. Eg. Var my_list_2 = {1, 2, “three”, “four”}; 2. Create an object with the new operator and a call to a constructor var my_list = new Array (1, 2, “three”, “four”); Array
JavaScript Arrays Saab,Volvo,BMW • Characteristics of Array object: – You access an array element by referring to the index number.
– Array indexes start with 0. – [0] is the first element. [1] is the second element.
JavaScript Arrays
JavaScript array elements are accessed using numeric indexes (starting from 0).
Output: • JavaScript Arrays • JavaScript array elements are accessed using numeric indexes (starting from 0). • Saab Array Properties and Methods
• The real strength of
JavaScript Arrays
JavaScript arrays are the
The length property returns the length of an array.
number of array
elements). OUTPUT JavaScript Arrays – The length property is The length property returns the length of an array. 4 always one more than Banana the highest array index. Mango
JavaScript Array Methods
• Converting Arrays to Strings – The JavaScript
toString()
method toString() converts an array to a string of (comma separated) array values.
The toString() method returns an array as a comma separated string:
• Output Banana,Orange,Apple,Mango • The join() method also joins all array elements into a string. • It behaves just like toString(), but in addition you can specify the separator.
• OUTPUT JavaScript Array Methods
JavaScript Array Methods
join()
join()
The join() method joins array
The join() method joins array elements into a string.
elements into a string.
It this example we have used " * " as a separator between the elements:
It this example we have used " * " as • Popping and Pushing – When you work with arrays, it is easy to remove elements and add new elements. – This is what popping and pushing is: – Popping items out of an array, or pushing items into an array. • Popping – The pop() method removes the last element from an array: – The pop() method returns the value that was "popped out": • Pushing – The push() method adds a new element to an array (at the end): – The push() method returns the new array length:
JavaScript Array Methods
pop() and push
• JavaScript Array Methods • pop() and push()
The pop() method removes the last element • The pop() method removes the last element from an array.
from an array. • Banana,Orange,Apple,Mango Banana,Orange,Apple
• Shifting Elements – Shifting is equivalent to popping, working on the first element instead of the last. – The shift() method removes the first array element and "shifts" all other elements to a lower index. • The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements: • The unshift() method returns the new array length. • Deleting Elements – Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator delete • Splicing an Array – The splice() method can be used to add new items to an array – The first parameter (2) defines the position where new elements should be added (spliced in). – The second parameter (0) defines how many elements should be removed. – The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added. • Using splice() to Remove Elements – With clever parameter setting, you can use splice() to remove elements without leaving "holes" in the array: – The first parameter (0) defines the position where new elements should be added (spliced in). – The second parameter (1) defines how many elements should be removed. – The rest of the parameters are omitted. No new elements will be added. • Sorting an Array – The sort() method sorts an array alphabetically: • Functions : – A function definition consists of the function’s header and a compound statement that describes its actions. – This compound statement is called body of the function. A function header consists of the reserved word function, the function’s name, and a parenthesized list of parameters. • Function syntax function name(parameter1, parameter2, parameter3) { code to be executed } • Function parameters are listed inside the parentheses () in the function definition. • Function arguments are the values received by the function when it is invoked. • Inside the function, the arguments (the parameters) behave as local variables.
JavaScript Functions
This example calls a function which performs a • Local Variables calculation and returns the result:
– Variables declared be accessed from within the function. OUTPUT • JavaScript Functions • This example calls a function which performs a calculation and returns the result: • 12 Constructors
• JavaScript constructors are special methods that create and initialize the properties for newly created objects. • Every new expression must include a call to a constructor, whose name is the same as the object being created. • A constructor must be able to reference the object on which it is to operate. • JavaScript has a predefined reference variable for this purpose, named this. • When the constructor is called, this is a reference to the newly created object. • The this variable is used to construct and initialize the properties of the object.
JavaScript Object Constructors
• JavaScript Object Constructors
Pattern matching using regular expressions • There are two approaches to pattern matching in javaScript: – Based on the RegExp object – Based on methods of the String object. • In JavaScript, regular expressions are often used with the two string methods: search() and replace(). • The search() method uses an expression to search for a match, and returns the position of the match. If there is no match, search returns -1. • The replace() method returns a modified string where the pattern is replaced. !DOCTYPE html> • JavaScript String Methods • Search a string for "W3Schools", and display the position of the match:
• 6
JavaScript String Methods
Search a string for "W3Schools", and display the position of the match:
• Metacharacters can themselves be matched by being immediately preceded by a backslash. Followings are the metacharacters: \ | ( ) [ ] { } ^ $ * + ? . • A period matches any character except newline. Eg. /snow./ Matches with snowy snowe snowd . • Matching classes of character [abc], [a-h] • Circumflex character (^) is the first character in a class, it inverts the specified set. e.g. [^aeiou] Character class matches any character except the letter a,e,i,o,u. • Predefine character classes • \d [0-9] A digit • \D [^0-9] not a digit • \w [A-Z a-z_0-9] A word character • \W [^A-Z a-z 0-9] Not a word character • \s [ \r\t\n\f] A whitespace character • \S [^ \r\t\n\f] Not a whitespace character Change the color of all
elements to "red".
This is a Heading This is a paragraph. This is another paragraph. Change the color of all
elements to "red".
This is a Heading
This is a paragraph.
This is another paragraph.
Change the color of the element with id="para1", to "red". Change the color of the element with id="para1", to "red".
This is a Heading
This is a paragraph.
This is another paragraph.
Change the color of all elements with the class "colortext", to "red". Change the color of all elements with the class "colortext", to "red".
This is a Heading
This is a paragraph.
This is another paragraph.
This is also a paragraph.
Change the color of all
and
elements, to "red". Group the selectors to minimize code.
This is a heading
This is a smaller heading
This is a paragraph.
This is another paragraph.
Add an external style sheet with the URL: "mystyle.css". Add an external style sheet with the URL: "mystyle.css".
This is a Heading
This is a paragraph.
This is another paragraph.
Set "background-color: linen" for the page, using an internal style sheet.
This is a Heading
This is a paragraph.
This is another paragraph.
Set "background-color: linen" for the page, using an inline style.
This is a Heading
This is a paragraph.
This is another paragraph.
UNIT - 5
Introduction to PHP • Origin and uses of PHP – Developed by Rasmus Lerdorf, a member of Apache Group – Initially called as Personal Home Page – later changed to Hypertext preprocessor – As a server side scripting language, PHP is naturally used for form handling and database access. • Overview of PHP – PHP is server-side, XHTML embedded scripting language. – When browser request an XHTML document that includes PHP script, the Web server that provides the document call the PHP processor. – File name extension for PHP script documents are .php, .php3, or .phtml – The PHP processor has two modes of operation, copy mode and interpret mode. – It takes a PHP document file as input and produces an XHTML document file. – When the PHP processor finds XHTML code in the input file, it simply copies it to the output file. • When it encounters PHP script in the input file, it interprets it and sends any output of the script to the output file. • This implies that the output from a PHP script must be XHTML or embedded client – side script. • This new file is sent to the requesting browser. General syntactic characteristics
• PHP scripts are either embedded in XHTML document or are in files that are referenced by XHTML documents. • PHP code is embedded in XHTML document by enclosing it between the tags. • If PHP script is stored in different file , it can be brought into a document with the include construct, which takes the filename as its parameter. • The include statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement.
• Eg. Include(“table2.inc”); • This constructor causes the contents of the file table2.inc to be copied into the document where the call appears. • The PHP interpreter changes from interpreter to copy mode when an include is encountered. • All variable names in PHP begin with dollar signs ($). • PHP variable names are case sensitive. • PHP allows comment in three different ways – Single line comment :- # or // – Multiple line comment :- /* */ • PHP statements terminated with semicolons. • Braces are used to form compound statements for control structures. • PHP Reserve words. – And else global require virtual break elseif if return xor case…………………………
• Primitives, operation and expressions – PHP has four scalar types:- Boolean, integer, double and string. – Two compound types :- array and objects – Two special types :- resources and NULL • Variables :- – PHP is dynamically typed, it has no type declaration. – There is no need to declare the type of a variable. – The type of the variable is set every time it is assigned a value. – An unassigned variable, called an unbound variable, has the value NULL. – If the context specifies a number, NULL is coerced to 0, if the context specifies a string, NULL is coerced to the empty string. • Isset() function is used to check whether variable is NULL or non- null. • E.g. Isset($fruit) returns TRUE if $fruit currently has a non-NULL value, FALSE otherwise . • unset :- set the variable to unassigned state. • Error_reporting:- function used to informed when unbound variable is referenced. • Integer type :- PHP has a single integer type. – This type corresponds to the long type of C.
• Double type :- corresponds to the double type of C. – Double literals can include a decimal point, an exponent, or both. • the exponent has the usual form of an E or an e possibly signed integer literal. • String type :- character in PHP are single bytes. – There is no character type. – A single character data is represented as a string of length 1. – String literals are defined with either single (‘) or double quotes (“) delimiters. – In single-quoted string literals, escape sequences, such as \n, are not recognized as anything special, and the values of embedded variables are not substituted. This is called interpolation. – In double-quoted string literals, escape sequence are recognized, and embedded variables are replaced by their current values. • Eg :- ‘The sum is : $sum.’ • Is typed as it is • “ The sum is : $sum” where sum = 10.2 • The sum is : 10.2 • Boolean type :- only two possible values TRUE or FALSE. • Arithmetic operators and expressions: -usual collection of arithmetic operators. • String operations :- – The only string operator is the catenation operator, specified with a period (.). – String variables can be treated like array for access to individual characters. Commonly used string function – strlen() :- returns the length of a string. – strcmp():- compares two strings. – strpos() :- finds the position of the first occurrence of a string inside another string. – substr() :- returns a part of a string. – chop() :- removes whitespaces or other predefined characters from the right end of a string. – trim() :- Removes whitespace or other characters from both sides of a string – ltrim() :- Removes whitespace or other characters from the left side of a string – strtolower() :- Converts a string to lowercase letters – strtoupper() :- Converts a string to uppercase letters • Scalar type conversions • Scalar type declaration has two options − – coercive - coercive is default mode and need not to be specified. • strict - strict mode has to explicitly hinted. • Explicit type conversions : - can be specified in three different ways. 1. Using syntax of C, an expression can be cast to a different type. – E.g. (int)$sum – If the value of $sum = 4.777 the following produces 4. 2. Another way is to use one of the functions interval, doubleval, or strval. – Eg. Interval($sum) 3. Use of settype function, which takes two parameters: a variable and a string that specifies a type name. – E.g. settype($sum, interger) • Assignment operators – PHP has same set of assignment operator as its predecessor languages C and perl, including the compound assignment operators such as += and /=. • Output :- – In PHP there are two basic ways to get output: echo and print. – echo and print are more or less the same. They are both used to output data to the screen. – The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print. • The PHP echo Statement • Program 2 – The echo statement can be used with or • without parentheses: echo or echo().
Program 1 $txt1 = "Learn PHP"; $txt2 = "W3Schools.com"; PHP is Fun!"; $y = 4; echo "Hello world! "; echo "I'm about to learn PHP! "; echo "This ", "string ", "was ", "made echo "
" . $txt1 . "
"; ", "with multiple parameters."; echo "Study PHP at " . $txt2 . " "; ?> echo $x + $y; ?> Output: • PHP is Fun! • Hello world! • Output I'm about to learn PHP! – This string was made with multiple Learn PHP – Study PHP at W3Schools.com parameters. 9 • The PHP print Statement – The print statement can be used with or without parentheses: print or print().
"; print "Hello world! "; print "Study PHP at " . $txt2 . " "; print "I'm about to learn PHP!"; print $x + $y; ?> ?> Output: • Output – Learn PHP – PHP is Fun! – Study PHP at W3Schools.com – Hello world! 9 I'm about to learn PHP! Control statements • Relational operators :- – The PHP comparison operators are used to compare two values (number or string) Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or $x >= $y Returns true if $x is greater than or equal to $y equal to
<= Less than or equal $x <= $y Returns true if $x is less than or equal to $y to • Boolean operators:- The PHP logical operators are used to combine conditional statements.
Operator Name Example Result and And $x and $y True if both $x and $y are true or Or $x or $y True if either $x or $y is true xor Xor $x xor $y True if either $x or $y is true, but not both && And $x && $y True if both $x and $y are true || Or $x || $y True if either $x or $y is true ! Not !$x True if $x is not true PHP Conditional Statements • PHP - The if...else Statement :- • PHP - The if Statement :- The if statement The if....else statement executes some code if executes some code if one condition is true. a condition is true and another code if that • Syntax condition is false. – if (condition) { • Syntax code to be executed if condition is true; – if (condition) { } code to be executed if condition is true; • Program } else { – code to be executed if condition is false; }
• Program – $t = date("H"); if ($t < "20") { if ($t < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; • Output } – Have a good day! ?>