• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Web technology unit II
 

Web technology unit II

on

  • 2,252 views

 

Statistics

Views

Total Views
2,252
Views on SlideShare
2,252
Embed Views
0

Actions

Likes
0
Downloads
11
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Web technology unit II Web technology unit II Document Transcript

    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353 UNIT II Style Sheets: CSS2.1 Introduction to Cascading Style SheetsCascading Style Sheets (CSS) is a slightly misleading term, since a website might haveonly oneCSS file (style sheet), or the CSS might be embedded within an HTML file. It is better tothinkof CSS as a technology (in the singular). CSS is comprised of statements that control the / nrstyling o. e.cof HTML documents. Simply put, an HTML document should convey content. A CSS ubdocument etshould control the styling of that content. cs<div align="center"></div> <img src="this.gif" border="0" alt="" /> <table :// tpheight="200">... <td width="30"></td> htAll these examples can easily be replaced with CSS. Dont worry if you dont understandthesedeclarations yet.div {text-align: center;} img {border: 0 none;} table {height: 200px;} td{width: 30px;}An HTML file points to one or more external style sheets (or in some cases a list ofdeclarationsembedded within the head of the HTML file) which then controls the style of the HTMLdocument. These style declarations are called CSS rules.2.2 FeaturesThe latest version of Cascade Style Sheets, CSS 3, was developed to make Web designeasier but it http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353became a hot topic for a while because not all browsers supported it. However, trendschange quickly intechnology and all browser makers currently are implementing complete CSS 3 support.Making thatprocess easier for the browser manufacturers is CSS 3s modularized specification, whichallows them toprovide support for modules incrementally without having to perform major refactoringof the browsers / nrcodebases. The modularization concept not only makes the process of approvingindividual CSS 3 o. e.cmodules easier and faster, but it also makes documenting the spec easier. ubEventually, CSS 3 -- along with HTML5 -- are going to be the future of the web. You et csshould begin ://making your Web pages compatible with these latest specifications. In this article, I tp htexplore 10 of theexciting new features in CSS 3, which is going to change the way developers who usedCSS2 buildwebsites.Some of the features are:o CSS Text Shadowo CSS Selectorso CSS Rounded Cornerso CSS Border Image3 Core Syntax2.3.1 At-RulesAs we learned when we studied CSS statements, there are two types of statements. Themostcommon is the rule-sets statement, and the other is the at-rules statement. As opposed torule http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353sets, at-rules statements consist of three things: the at-keyword, @, an identifier, and adeclaration. This declaration is defined as all content contained within a set of curlybraces, or byall content up until the next semicolon.@importPerhaps the most commonly used of the at-rules, @import, is used to import an externalstylesheet into a document. It can be used to replace the LINK element, and serves the same / nrfunction, o.except that imported style sheets have a lower weight (due to having less proximity) than e.clinked ubstyle sheets. et cs<style type="text/css" media="screen"> @import url(imported.css); </style> ://@import url(addonstyles.css); @import "addonstyles.css"; tp htRelative and absolute URLs are allowed, but only one is allowed per instance of@import. Oneor more comma-separated target media may be used here.@charset@charset is used to specify the character encoding of a document, and must appear nomore thanonce. It must be the very first declaration in the external style sheet, and cannot appear inembedded style sheets. @charset is used by XML documents to define a character set.@charset "utf-8";@namespaceThe @namespace rule allows the declaration of a namespace prefix to be used byselectors in astyle sheet. If the optional namespace prefix is omitted, then the URL provided becomesthe http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353default namespace. Any @namespace rules in a style sheet must come after all @importand@charset at-rules, and come before all CSS rule-sets.@namespace foo url("http://www.example.com/");@namespace can be used together with the new CSS3 selectors (see below). It defineswhichXML namespace to use in the CSS. If the XML document doesnt have matching XMLnamespace information, the CSS is ignored. / nr@font-face o.This was removed from the CSS2.1 specification, but is still used to describe a font face e.cfor a ubdocument.. et cs@font-face { font-family: "Scarborough Light"; src: ://url("http://www.font.com/scarborough-lt"); } @font-face { font-family: tp htSantiago; src: local ("Santiago"), url("http://www.font.com/santiago.tt"),format("truetype"); unicode-range: U+??,U+100-220; font-size: all; fontfamily:sans-serif; }@mediaThis at-rule is used within a style sheet to target specific media. For example, afterdefining howan element is to be displayed (in this example for the screen), the declaration can beoverwrittenfor print, in which case we often want to hide navigation.p {font-size: 0.8em;} /* for the screen */ @media print { p {font-size:10pt;} #nav, #footer {display: none;} } @media screen, handheld { p {fontsize:14px; text-align: justify;} }The media types are as follows.all http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353aural (for speech synthesizers)handheldprintprojectionscreenbrailleembossedtty / nrtv@page o. e.cThis at-rules declaration is used to define rules for page sizing and orientation rules for ubprinting. et cs@page {size: 15cm 20cm; margin: 3cm; marks: cross;} ://You may specify how pages will format if they are first, on the left-hand side, or on the tp htright.@page :first {margin-top: 12cm;} @page :left {margin-left: 4.5cm;} @page:right {margin-right: 7cm;}@fontdefThis is an old Netscape-specific at-rule which we should ignore.CSS1 SelectorsSelectors refer to elements in an HTML document tree. Using CSS, they are pattern-matched in http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353order to apply styles to those elements. A selector consists of one or more elements,classes, orIDs, and may also contain pseudo-elements and/or pseudo-classes.Type SelectorThe type selector is the simplest selector of all, and matches all occurrences of anelement. Inthis example, all <p> tags throughout the document will have the following style applied,unless / nroverridden.p {color: #666;} o. e.cUniversal Selector ubThe universal selector, used alone, matches all elements in the document tree, and thus et cswill apply ://styles to all elements. It is in effect a wildcard. tp ht* {margin: 0; padding: 0;}In this example, all tags are reset to have no padding or margin. This, by the way, is apractice togain control over all the default padding and margin inherent in the way User Agents(UAs)display HTML.Class SelectorThe class selector matches a classname..largeFont {font-size: 1.5em;} h3.cartHeader {text-align: center;}The "largeFont" class will apply to all elements into which it is called. The "cartHeader"classwill only function as styled if called into an H3 element. This is useful if you haveanother http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353"cartHeader" declaration that you wish to override in the context of an H3 element, or ifyouwish to enforce the placement of this class.ID SelectorThe ID selector matches an ID. IDs are identifiers unique to a page. They bear aresemblance toclasses, but are used a bit differently. IDs will be treated more fully below. The first twoID / nrexamples below refer to sections of a web page, while the last refers to a specificoccurrence of o. e.can item, say, an image in a DHTML menu. IDs have a higher specificity than classes. ub#header {height: 100px;} #footer {color: #F00;} #xyz123 {font-size: 9px;} et csDescendant Selector ://A selector can itself be a chain of one or more selectors, and is thus sometimes called a tp htcompound selector. The descendant selector is the only compound selector in CSS1, andconsistsof two or more selectors and one or more white space combinators. In the examplebelow, thewhite space between the H1 and EM elements is the descendant combinator. In otherwords,white space conveys a hierarchy. (If a comma were to have intervened instead, it wouldmeanthat we were styling H1 and EM elements alike.) Selectors using combinators are usedfor moreprecise drill-down to specific points within the document tree. In this example <em> tagswillhave the color red applied to them if they are within an <h1> tag.h1 em {color: #F00;} http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Note that EM elements do not have to be immediately inside an H1 heading, that is, theydo nothave to be children, but merely descendants of their ancestor. The previous style wouldapply toan EM element in either of the following statements.<h1>This is a <em>main</em> heading</h1> <h1>This is <strong>another<em>main</em> heading</strong></h1>In the next example, the color black will be applied to all <span> tags that are / nrdescendants o.(whether directly or not) of <div> tags which are in turn descendants (whether directly or e.cnot) of ub<p> tags, no matter how deep the <p> tags are in the document tree. et csdiv p span {color: #000;} ://That is to say, this style would apply to SPAN elements inside a P element, even if they tp htaremany levels below (that is, within) the DIV element, as long as there is an intervening Pelement.The universal selector can be part of a compound selector in tandem with a combinator.p * span {font-size: 0.6em;}This would style any SPAN element that is at least a grandchild of a P element. TheSPANelement could in fact be much deeper, but it will not be styled by this declaration if it isthe child(direct descendant) of a P element.Other SelectorsOther combinators convey greater precision. They include the direct adjacent siblingcombinator http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353(+), the indirect adjacent sibling (or general) combinator (~), and the child combinator(>). Thesecombinators will be treated below because they are part of the CSS2.1 specification, andare notsupported in IE6.EXAMPLE:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0Transitional//EN" / nr"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html> o. e.c<head> ub<style type="text/css"> et csdiv.ex ://{ tp htwidth:220px;padding:10px;border:5px solid gray;margin:0px;}</style></head>2.4 STYLE SHEETS AND HTML STYLE RULETo apply a style, CSS uses the HTML document tree to match an element, attribute, orvalue inan HTML file. For an HTML page to properly use CSS, it should be well-formed andvalid, andpossess a valid doctype. If these conditions are not met the CSS match may not yield thedesired http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353results.There are two types of CSS statements: rule-sets and at-rules. A rule set, alsoknownsimply as a rule, is the more common statement, and consists of a selector and adeclarationblock, sometimes simply called a block. The selector can be an element, class, or ID, andmayinclude combinators, pseudo-elements, or pseudo-classes.Statement Type 1: Rules Sets (Rules) / nrstatement + statement blockX {declaration; declaration;} o. e.cX {property; value; property: value;} ubdiv > p {font-size: 1em; color #333;} et csStatement Type 2: At-Rules ://at-keyword + identifier + declaration tp ht@import "subs.css";The declaration block consists of the braces and everything in between. Within thedeclarationblock are declarations, which consist of properties and values. Properties are separatedfrom theirvalues (also known as styles) by colons, and declarations are delimited by semi-colons.(Properties are also known as attributes, but that terminology is not used in this documentlest weconfuse CSS properties with HTML attributes.) White space inside a declaration block isignored, which facilitates formatting the code in developer-friendly ways. For example,both ofthe following statements are valid and equivalent, though the latter slightly increasesdocumentweight. http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353h1 {color: blue; margin-top: 1em;} h1 { color: blue; margin-top: 1em; }Ensure, however, that there is no white space between a value and its unit ofmeasurement (e.g.1.2em, not 1.2 em).As opposed to rule sets, at-rules statements consist of the at-keyword"@", anidentifier, and a declaration. This declaration is defined as all the content containedwithin a setof curly braces, or by all content up until the next semicolon. Note the following two / nrexamples. o.@media print { p {font-size: 10pt;} tt {font-family: monospace;} } @import e.curl(addonstyles.css); ubOther examples of at-keywords are media, font-face, and page. At-rules will be treated et csseparately ://below. tp htPropertiesI have decided not to include a description of all CSS1 and CSS2.1 Properties (such asfont-size,text-transform, border, margin, and many others) because they are numerous and can beexamined in the Property References section of this site. Moreover, they are usedthroughout thistutorial and can be easily deduced. So we move directly to CSS1 selectors.1.5 STYLE RULE CASCADING AND INHERITANCECSS are probably wondering what exactly cascades about cascading style sheets. In thissectionwe look at the idea of cascading, and a related idea, that of inheritance. Both areimportantunderlying concepts that you will need to grasp, and understand the difference between,in order http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353to work properly with style sheets.Rule CascadeA single style sheet associated with one or more web pages is valuable, but in quite alimitedway. For small sites, the single style sheet is sufficient, but for larger sites, especiallysitesmanaged by more than one person (perhaps several teams who may never communicate)single / nrstyle sheets dont provide the ability to share common styles, and extend these styleswhere o. e.cnecessary. This can be a significant limitation. ubCascading style sheets are unlike the style sheets you might have worked with using word et csprocessors, because they can be linked together to create a hierarchy of related style ://sheets. tp htManaging style at large sites using @importImagine how the web site for a large organization, say a corporation, might be structured.Assites grow in complexity, individual divisions, departments, and workgroups becomemoreresponsible for their own section of a site. We can already see a potential problem - howdo weensure a consistent look and feel across the whole site?A dedicated web developmentteam canensure that a style guide is adhered to.SpecificityGet browser support information for specificity in the downloadable version of this guideor our http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353browser support tables.At this point it might be timely to have a quick discussion ofspecificity.Both inside a single style sheet, and in a cascade of style sheets, it should be clear thatmore thanone rule can apply to the same element. What happens when two properties in separateruleswhich both apply to an element contradict one another? Obviously they cant both apply(the text / nrof an element cant be both red and blue, for example). CSS provides a mechanism forresolving o. e.cthese conflicts, called specificity. ubSome selectors are more specific than others. For example, the class and ID selectors are et csmore ://specific than simple HTML element selectors. When two rules select the same element tp htand theproperties contradict one another, the rule with the more specific selector takesprecedence.Specificity for selectors is a little involved. Without going into the full detail, mostsituations canbe resolved with the following rules.1. ID selectors are more specific than other selectors2. Class selectors are more specific than HTML element selectors, and other selectorssuchas contextual, pseudo class and pseudo element selectors.3. Contextual selectors, and other selectors involving more than one HTML elementselector are more specific than a single element selector (and for two multiple elementselectors, the one with more elements is more specific than the one with fewer.) http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353There are times though when the two rules will have the same specificity. In this case, therulethat comes later in the cascade prevails.For example, where one rule is in an importedstylesheet, and the other in the style sheet itself, the rule in the style sheet which is importingtakesprecedence. When the two rules are in the same style sheet, it is the one furthest from thetop of / nrthe style sheet that takes precedence.While these rules seem complicated at first, they arepretty o. e.cmuch common sense, and it is uncommon that much confusion or difficulty arises for a ubdeveloper. et csStyle Inheritance ://Any HTML page comprises a number of (perhaps a large number of) elements - tp htheadings,paragraphs, lists, and so on. Often, developers use the term "tag" to refer to an element,makingreference for example to "the p tag". But the tag is simply the <p></p> part of theelement. Thewhole construction of <p>This is the content of the paragraph</p> is in fact the <p>element (as we refer to it in this guide). What many web developers dont realize (largelybecause it wasnt particularly important until style sheets came along) is that everyelement iscontained by another element, and may itself contain other elements. The technical termfor thisis the containment hierarchy of a web page.At the top of the containment hierarchy is the <html> element of the page. Every otherelement http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353on a web page is contained within the <html> element, or one of the elements containedwithinit, and so on. Similarly, many elements will be contained in paragraphs, while paragraphsarecontained in the <body>.Graphically, we can understand it like this.figure 4: the HTML containment hierarchyI said above that style sheets made it important to understand this. Why? Well, with / nrcascading o.style sheets, elements often (and with CSS2 can always be forced to) inherit properties e.cfrom the ubelements which contain them (otherwise known as their parent elements). This means et csthat if you ://give the body of the page certain properties (for example font and color) then every tp htelementwithin the page will inherit these properties- there is no need to set the font and coloragain foreach element, such as list items or paragraphs.You can always override the inheritance however. By assigning a property to an element,youoverride the inherited property.2.6 Text t properties2.6.1 CSS Font FamiliesCSS font properties define the font family, boldness, size, and the style of a text.Difference Between Serif and Sans-serif FontsOn computer screens, sans-serif fonts are considered easier to read than serif fonts.In CSS, there are two types of font family names: http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353generic family - a group of font families with a similar look (like "Serif" or"Monospace")font family - a specific font family (like "Times New Roman" or "Arial")Generic family Font family DescriptionSerifTimes New RomanGeorgiaSerif fonts have small lines at the ends on some / nrcharactersSans-serif o. e.cArial ubVerdana et cs"Sans" means without - these fonts do not have the ://lines at the ends of characters tp htMonospaceCourier NewLucida ConsoleAll monospace characters have the same widthFont FamilyThe font family of a text is set with the font-family property.The font-family propertyshouldhold several font names as a "fallback" system. If the browser does not support the firstfont, ittries the next font.Start with the font you want, and end with a generic family, to let thebrowserpick a similar font in the generic family, if no other fonts are available.Note: If the name of a font family is more than one word, it must be in quotation marks,like http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353font-family: "Times New Roman".More than one font family is specified in a comma-separatedlist:Examplep{font-family:"Times New Roman", Times, serif;}Font StyleThe font-style property is mostly used to specify italic text.This property has three values: / nrnormal - The text is shown normallyitalic - The text is shown in italics o. e.coblique - The text is "leaning" (oblique is very similar to italic, but less supported) ubExample et csp.normal {font-style:normal;} ://p.italic {font-style:italic;} tp htp.oblique {font-style:oblique;}Font SizeThe font-size property sets the size of the text.Being able to manage the text size isimportant inweb design. However, you should not use font size adjustments to make paragraphs looklikeheadings, or headings look like paragraphs.Always use the proper HTML tags, like <h1>- <h6>for headings and <p> for paragraphs.The font-size value can be an absolute, or relative size.Absolute size:Sets the text to a specified sizeDoes not allow a user to change the text size in all browsers (bad for accessibilityreasons) http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Absolute size is useful when the physical size of the output is knownRelative size:Sets the size relative to surrounding elementsAllows a user to change the text size in browsersIf you do not specify a font size, the default size for normal text, like paragraphs, is 16px(16px=1em).Set Font Size With PixelsSetting the text size with pixels, gives you full control over the text size: / nrExampleh1 {font-size:40px;} o. e.ch2 {font-size:30px;} ubp {font-size:14px;} et csSet Font Size With Em ://To avoid the resizing problem with Internet Explorer, many developers use em instead of tp htpixels.The em size unit is recommended by the W3C.1em is equal to the current font size.Thedefault text size in browsers is 16px. So, the default size of 1em is 16px.The size can be calculated from pixels to em using this formula: pixels/16=emExampleh1 {font-size:2.5em;} /* 40px/16=2.5em */h2 {font-size:1.875em;} /* 30px/16=1.875em */p {font-size:0.875em;} /* 14px/16=0.875em */All CSS Font PropertiesThe number in the "CSS" column indicates in which CSS version the property is defined(CSS1or CSS2).Property Description Values CSSfont http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Sets all the fontproperties in onedeclarationfont-stylefont-variantfont-weightfont-size/line-heightfont-family / nrcaptionicon o. e.cmenu ubmessage-box et cssmall-caption ://status-bar tp ht1inheritfont-familySpecifies the font familyfor textfamily-namegeneric-familyinherit1font-sizeSpecifies the font size oftextxx-smallx-small http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353smallmediumlargex-largexx-largesmallerlargerlength / nr%inherit o. e.c1 ubfont-style et csSpecifies the font style ://for text tp htnormalitalicobliqueinherit1font-variantSpecifies whether or nota text should bedisplayed in a small-capsfontnormalsmall-capsinherit1 http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353font-weightSpecifies the weight of afontnormalboldbolderlighter100 / nr200300 o. e.c400 ub500 et cs600 ://700 tp ht8009001inheritText Formatting and colorAll CSS Text PropertiesThe number in the "CSS" column indicates in which CSS version the property is defined(CSS1or CSS2).Property Description Values CSScolor Sets the color of a text color 1direction Sets the text directionltrrtl http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT23532line-height Sets the distance between linesnormalnumberlength%1letter-spacing Increase or decrease the space between characters / nrnormallength o. e.c1 ubtext-align Aligns the text in an element et csleft ://right tp htcenterjustify1text-decoration Adds decoration to textnoneunderlineoverlineline-throughblink1text-indent Indents the first line of text in an elementlength%1 http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353text-shadownonecolorlengthtext-transform Controls the letters in an elementnonecapitalizeuppercase / nrlowercase1 o. e.cunicode-bidi ubnormal et csembed ://bidi-override tp ht2vertical-align Sets the vertical alignment of an elementbaselinesubsupertoptext-topmiddlebottomtext-bottomlength%1white-space Sets how white space inside an element is handled http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353normalprenowrap1word-spacing Increase or decrease the space between wordsnormallength1 / nr2.7 The CSS Box ModelBLOCK DIAGRAM o. e.cAll HTML elements can be considered as boxes. In CSS, the term "box model" is used ubwhen et cstalking about design and layout. ://The CSS box model is essentially a box that wraps around HTML elements, and it tp htconsists of:margins, borders, padding, and the actual content.The box model allows us to place a border around elements and space elements inrelation toother elements.The image below illustrates the box model:Explanation of the different parts:Margin - Clears an area around the border. The margin does not have a background color,it iscompletely transparentBorder - A border that goes around the padding and content. The border is affected by thebackground color of the boxPadding - Clears an area around the content. The padding is affected by the backgroundcolor of http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353the boxContent - The content of the box, where text and images appearIn order to set the width and height of an element correctly in all browsers, you need toknowhow the box model works.Width and Height of an ElementImportant: When you specify the width and height properties of an element with CSS,you are / nrjust setting the width and height of the content area. To know the full size of the element,you o. e.cmust also add the padding, border and margin. ubThe total width of the element in the example below is 300px: et cswidth:250px; ://padding:10px; tp htborder:5px solid gray;margin:10px;Lets do the math:250px (width)+ 20px (left and right padding)+ 10px (left and right border)+ 20px (left and right margin)= 300pxImagine that you only had 250px of space. Lets make an element with a total width of250px:Examplewidth:220px;padding:10px;border:5px solid gray; http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353margin:0px;The total width of an element should always be calculated like this:Total element width = width + left padding + right padding + left border + right border +leftmargin + right marginThe total height of an element should always be calculated like this:Total element height = height + top padding + bottom padding + top border + bottomborder + / nrtop margin + bottom marginExample o. e.c<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ub"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> et cs<html> ://<head> tp ht<style type="text/css">div.ex{width:220px;padding:10px;border:5px solid gray;margin:0px;}</style></head>CSS BackgroundCSS background properties are used to define the background effects ofan element.CSS properties used for background effects: http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353background-colorbackground-imagebackground-repeatbackground-attachmentbackground-positionBackground ColorThe background-color property specifies the background color of an element.Thebackground / nrcolor of a page is defined in the body selector:Example o. e.cbody {background-color:#b0c4de;} ubThe background color can be specified by: et csname - a color name, like "red" ://RGB - an RGB value, like "rgb(255,0,0)" tp htHex - a hex value, like "#ff0000"Background ImageThe background-image property specifies an image to use as the background of anelement.By default, the image is repeated so it covers the entire element.The background image for a page can be set like this:Examplebody {background-image:url(paper.gif);}Below is an example of a bad combination of text and background image. The text isalmost notreadable:Background Image - Repeat Horizontally or VerticallyBy default, the background-image property repeats an image both horizontally andvertically. http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Some images should be repeated only horizontally or vertically, or they will look strange,likethis:Examplebody{background-image:url(gradient2.png);} / nrIf the image is repeated only horizontally (repeat-x), the background will look better:Example o. e.cbody ub{ et csbackground-image:url(gradient2.png); ://background-repeat:repeat-x; tp ht}Background Image - Set position and no-repeatWhen using a background image, use an image that does not disturb the text.Showing the image only once is specified by the background-repeat property:Examplebody{background-image:url(img_tree.png);background-repeat:no-repeat;}In the example above, the background image is shown in the same place as the text. Wewant tochange the position of the image, so that it does not disturb the text too much.Theposition of the http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353image is specified by the background-position property:Examplebody{background-image:url(img_tree.png);background-repeat:no-repeat;background-position:right top;} / nrBackground - Shorthand property o.As you can see from the examples above, there are many properties to consider when e.cdealing ubwith backgrounds. et csTo shorten the code, it is also possible to specify all the properties in one single property. ://This is tp htcalled a shorthand property.The shorthand property for background is simply "background":body {background:#ffffff url(img_tree.png) no-repeat right top;}When using the shorthand property the order of the property values are:background-colorbackground-imagebackground-repeatbackground-attachmentbackground-positionIt does not matter if one of the property values are missing, as long as the ones that arepresentare in this order.This example uses more advanced CSS. Take a look: Advanced exampleAll CSS Background Properties http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353The number in the "CSS" column indicates in which CSS version the property is defined(CSS1or CSS2).Property Description Values CSSbackgroundSets all the background propertiesin one declarationbackground-color / nrbackground-imagebackground-repeat o. e.cbackground-attachment ubbackground-position et csinherit ://1 tp htbackground-attachmentSets whether a background image isfixed or scrolls with the rest of thepagescrollfixedinherit1background-colorSets the background color of anelementcolor-rgbcolor-hexcolor-name http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353transparentinherit1background-imageSets the background image for anelementurl(URL)none / nrinherit1 o. e.cbackground-position ubSets the starting position of a et csbackground image ://left top tp htleft centerleft bottomright topright centerright bottomcenter topcenter centercenter bottomx% y%xpos yposinherit1background-repeatSets if/how a background image will http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353be repeatedrepeatrepeat-xrepeat-yno-repeatinherit12.8 NORMAL FLOW BOX LAYOUT / nrUnderstanding the box model is critical to developing web pages that dont rely on tablesfor o. e.clayout. In the early days of writing HTML, before the advent of CSS, using tables was ubthe only et csway to have discreet content in separate boxes on a page. But tables were originally ://conceived to tp htdisplay tabular information. With the advent of CSS floating and positioning, there is nolonger aneed to use tables for layout, though many years later many, if not most, sites are stillusingtables in this manner.The box model, as defined by the W3C "describes the rectangularboxesthat are generated for elements in the document tree and laid out according to the visualformatting model". Dont be confused by the term "boxes". They need not appear assquare boxeson the page. The term simply refers to discreet containers for content. In fact, everyelement in adocument is considered to be a rectangular box.Padding, Borders, Margins http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Padding immediately surrounds the content, between content and borders. A margin isthe spaceoutside of the borders. If there are no borders both paddng and margin behave in roughlythesame way, except that you can have negative margins, while you cannot have negativepadding.Also padding does not collapse like margins. See below for the section on collapsingmargins. / nrThe picture on the right illustrates padding, borders, and margins. The content area doesnot o. e.creally have a border. The line around the content merely indicates the limits of the actual ubcontent. et csTraditional vs. W3C Box Models ://So how do you declare these properties in your CSS, and how do you set the width of a tp htbox?That depends on the box model. There are actually two box models. The traditional boxmodel issupported by IE5.5 and previous versions of IE, and any version of IE in quirks mode. Itstatesthat the width of a box is the combined width of the content, its padding and its borders.Imaginea literal box that you can hold. The carboard exterior is the border. We dont care aboutthecontent inside of the box. It may fill up the box entirely or have space around it. If it hasspacearound it, that is its padding, which sits between the content and the exterior (border) ofthe box. http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353But according to this model, it does not matter what the actual content width is. Thewidth of thebox is what matters. Using the traditional model lets consider the following declaration..box {width: 200px; border: 1px solid black; padding: 10px;}In the traditional model the width of the box is 200 pixels.CSS: .wrap {width: 760px;} .menu {float: left; width 187px; padding: 6px;border-right: 1px solid #999;} .main {float: left; width 548px; padding:6px;} HTML: <div id="wrap"> <div id="menu"></div> <div id="main"></div> / nr</div> o.The math from left to right would be:menu left padding + menu content + menu right e.cpadding + ubmenu border + main left padding + main content + main right padding (or in pixels) 6 + et cs187 + 6 ://+ 1 + 6 + 548 + 6 = 760. tp htMargin CollapseVertical margins collapse when they meet. Though it may seem like a strange thing, ifyou haveassigned top and bottom margins to the P element of, say, 10px each, you will not have20px ofmargin between paragraphs, but rather 10px. This is considered to be desirable andexpectedbehavior, and not a bug. Now consider the following declaration.p {margin: 10px 0 16px;}In this case the space between paragraphs would be 16px, that is, the greater of the twovalues.Margin collapse does not occur when either box is floated, when one element uses theoverflow http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353property set to any value other than "visible", with absolutely positioned elements, withelementswhose display property is set to "inline-block", or if the child element is cleared.You canoverride margin collapse also by adding a border, of the same color as the background ifyouwant it unnoticed, or by using padding instead of margins. Eric Meyer has a nicedescription ofcollapsing margins. In sum, margin collapse is meant to prevent certain design problems, / nrand yetis not difficult to override. o. e.cDisplay Property ubThis is one of the most useful properties. The complete list of values is in the appendix of et csthis ://document, but the most useful ones follow. tp htblockBlock display provides behavior similar to a default DIV element. A line break occurs attheclose of the tag. Elements that are block by default are DIV, P, BLOCKQUOTE, H1through H6,UL, OL, LI, ADDRESS, etc. Block elements accept width, height, top and bottommargins, andtop and bottom padding. A block element constitutes a separate block box.inlineInline display creates no such line break. Elements that are inline by default are SPAN,IMG,INPUT, SELECT, EM, STRONG, etc. Inline elements do not accept width, height, topand http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353bottom padding, and top and bottom margins, which makes good sense, since they areused forpart of a line of text (i.e. of a block box).They do, however, accept left and right padding, left and right margins, and line-height.Lineheightcan then be used to approximate height. If you need to apply width, height or other blockproperties to an inline element, consider assigning the element block display and/orfloating it. / nrBlock display, of course, will force the element on to a separate line (unless the elementis o. e.cfloated). Alternatively you can assign the inline-block value to make an inline element ubtake block et csproperties (see below). ://none tp htDisplay set to none sets the element to invisible similar to the hidden value of thevisibilityproperty (see below). However, unlike the visibility property, this value takes up no spaceon thepage. This is very useful for DHTML hidden tools and for other instances when you needitemsto expand and collapse based on whether they contain content to be viewed on demand.Moreover, when you generate content, items whose display is set to none will not beincluded inthe loop. (For more on generated content, see below.) Display set to none will also behiddenfrom most screen readers. If you are trying to make something readable only for thosewith sightdisabilities, use an off-screen class like this: http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353.offScreen {position: absolute; left: -10000px; top: auto; width: 1px;height: 1px; overflow: hidden;}inline-blockThis value causes the element to generate a block element box that will be flowed withsurrounding content as if it were a single inline box. It lets you place a block inline withthecontent of its parent element. It also allows you to assign properties associated with blockdisplay, such as width and height to an element that naturally takes inline display. This / nrproperty o.is also used to trigger hasLayout in IE6, which is a difficult concept, but briefly means e.cmaking ubIE6 assume CSS certain properties. et csrun-in ://This display mode causes the element to appear as an inline element at the start of the tp htblockimmediately following it. If there is no block following a run-in element, it is displayedas anormal block instead. Currently, there seems to be no browser support for this valueexcept forIE8, but here is an example of how it is coded, and how it should look.<div style="display: run-in">Here is some run-in text on this line.</div><div style="display: block">But here is a block that follows it, so they areconjoined.</div>Lets seer if it works. Here is some run-in text on this line.But here is a block that followsit, soare they conjoined? Well, apparently not in Firefox. Oh well.list-item http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Unordered lists are traditionally used to list bulleted items vertically. But you can assignbulletsto other elements using the list-item value.div {display: list-item;}It may not make a lot of semantic sense to apply bullets to an element that is not a listitem, butat the very least its helpful that CSS is so flexible. However you use these values, ensurethat / nryour HTML is meaningful irrespective of your CSS. Because there is a wide variety ofdisplay o. e.cvalues, HTML tags can be made to display in a variety of ways, some counter to the ubnature of the et cselement. Care should be taken to maintain the implicit content of elements. Should you, ://for tp htexample, give a P element inline display? You can, but use caution. It is more likely thatyou willset the inline value for the DIV element. This seems to be more acceptable in that theDIVelement simply provides separate treatment for content, while a paragraph is visuallydemarcatedfrom other elements.2.9 Beyond the Normal FlowPositioningThe CSS positioning properties allow you to position an element. It can also place anelementbehind another, and specify what should happen when an elements content is toobig.Elements http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353can be positioned using the top, bottom, left, and right properties. However, theseproperties willnot work unless the position property is set first. They also work differently depending onthepositioning method.There are four different positioning methods.Static PositioningHTML elements are positioned static by default. A static positioned element is alwayspositioned / nraccording to the normal flow of the page.Static positioned elements are not affected bythe top, o. e.cbottom, left, and right properties. ubFixed Positioning et csAn element with fixed position is positioned relative to the browser window.It will not ://move tp hteven if the window is scrolled:Examplep.pos_fixed{position:fixed;top:30px;right:5px;}Note: Internet Explorer supports the fixed value only if a !DOCTYPE is specified.Fixedpositioned elements are removed from the normal flow. The document and otherelementsbehave like the fixed positioned element does not exist.Fixed positioned elements canoverlapother elements. http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Relative PositioningA relative positioned element is positioned relative to its normal position.Exampleh2.pos_left{position:relative;left:-20px;} / nrh2.pos_right{ o. e.cposition:relative; ubleft:20px; et cs} ://The content of a relatively positioned elements can be moved and overlap other elements, tp htbut thereserved space for the element is still preserved in the normal flow.Exampleh2.pos_top{position:relative;top:-50px;}Relatively positioned element are often used as container blocks for absolutely positionedelements.Absolute PositioningAn absolute position element is positioned relative to the first parent element that has apositionother than static. If no such element is found, the containing block is <html>: http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Exampleh2{position:absolute;left:100px;top:150px;}27 / nrAbsolutely positioned elements are removed from the normal flow. The document andother o. e.celements behave like the absolutely positioned element does not exist.Absolutely ubpositioned et cselements can overlap other elements. ://Overlapping Elements tp htWhen elements are positioned outside the normal flow, they can overlap otherelements.The zindexproperty specifies the stack order of an element (which element should be placed in frontof, or behind, the others).An element can have a positive or negative stack order:Exampleimg{position:absolute;left:0px;top:0px;z-index:-1}An element with greater stack order is always in front of an element with a lower stackorder. http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353All CSS Positioning PropertiesThe number in the "CSS" column indicates in which CSS version the property is defined(CSS1or CSS2).Property Description Values CSSbottomSets the bottom margin edge for apositioned box / nrautolength o. e.c% ubinherit et cs2 ://clip Clips an absolutely positioned element tp htshapeautoinherit2cursor Specifies the type of cursor to be displayedurlautocrosshairdefaultpointermove228e-resize http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353ne-resizenw-resizen-resizese-resizesw-resizes-resizew-resizetext / nrwaithelp o. e.cleft ubSets the left margin edge for a positioned et csbox ://auto tp htlength%inherit2overflowSpecifies what happens if content overflowsan elements boxautohiddenscrollvisibleinherit2position http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Specifies the type of positioning for anelementabsolutefixedrelativestaticinherit2 / nrrightSets the right margin edge for a positioned o. e.cbox ubauto et cslength ://% tp htinherit2topSets the top margin edge for a positionedboxautolength%inherit2z-index Sets the stack order of an elementnumberautoinherit http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353229What is CSS Float?With CSS float, an element can be pushed to the left or right, allowing other elements towrap around it.Float is very often used for images, but it is also useful when working with layouts.How Elements FloatElements are floated horizontally, this means that an element can only be floated left or / nrright, not o.up or down.A floated element will move as far to the left or right as it can. Usually this e.cmeans all ubthe way to the left or right of the containing element.The elements after the floating et cselement will ://flow around it.The elements before the floating element will not be affected. tp htIf an image is floated to the right, a following text flows around it, to the left:Exampleimg{float:right;}Floating Elements Next to Each OtherIf you place several floating elements after each other, they will float next to each other ifthereis room.Here we have made an image gallery using the float property:Example.thumbnail{float:left; http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353width:110px;height:90px;margin:5px; }2.10 SOME OTHER USEFUL STYLE PROPERTIESCSS ListsThe CSS list properties allow you to:o Set different list item markers for ordered lists30 / nro Set different list item markers for unordered listso Set an image as the list item marker o. e.cList ubIn HTML, there are two types of lists: et csunordered lists - the list items are marked with bullets ://ordered lists - the list items are marked with numbers or letters tp htWith CSS, lists can be styled further, and images can be used as the list item marker.Different List Item MarkersThe type of list item marker is specified with the list-style-type property:Exampleul.a {list-style-type: circle;}ul.b {list-style-type: square;}ol.c {list-style-type: upper-roman;}ol.d {list-style-type: lower-alpha;}Some of the property values are for unordered lists, and some for ordered lists.Values for Unordered ListsValue Descriptionnone No markerdisc Default. The marker is a filled circlecircle The marker is a circle http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353square The marker is a squareValues for Ordered ListsValue Descriptionarmenian The marker is traditional Armenian numberingdecimal The marker is a number31decimal-leading-zero The marker is a number padded by initial zeros (01, 02, 03, etc.)georgian The marker is traditional Georgian numbering (an, ban, gan, etc.) / nrlower-alpha The marker is lower-alpha (a, b, c, d, e, etc.) o.lower-greek The marker is lower-greek (alpha, beta, gamma, etc.) e.clower-latin The marker is lower-latin (a, b, c, d, e, etc.) ublower-roman The marker is lower-roman (i, ii, iii, iv, v, etc.) et csupper-alpha The marker is upper-alpha (A, B, C, D, E, etc.) ://upper-latin The marker is upper-latin (A, B, C, D, E, etc.) tp htupper-roman The marker is upper-roman (I, II, III, IV, V, etc.)Note: No versions of Internet Explorer (including IE8) support the property values"decimalleading-zero", "lower-greek", "lower-latin", "upper-latin", "armenian", or "georgian" UNLESS aDOCTYPE is specified!An Image as The List Item MarkerTo specify an image as the list item marker, use the list-style-image property:Exampleul{list-style-image: url(sqpurple.gif);}The example above does not display equally in all browsers. IE and Opera will displaythe http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353image-marker a little bit higher than Firefox, Chrome, and Safari.If you want the image-markerto be placed equally in all browsers, a crossbrowser solution is explained below.Crossbrowser SolutionThe following example displays the image-marker equally in all browsers:Exampleul{ / nrlist-style-type: none;32 o. e.cpadding: 0px; ubmargin: 0px; et cs} ://li tp ht{background-image: url(sqpurple.gif);background-repeat: no-repeat;background-position: 0px 5px;padding-left: 14px;}Example explained:For ul:o Set the list-style-type to none to remove the list item markero Set both padding and margin to 0px (for cross-browser compatibility)For li:o Set the URL of the image, and show it only once (no-repeat)o Position the image where you want it (left 0px and down 5px)o Position the text in the list with padding-left http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353List - Shorthand propertyIt is also possible to specify all the list properties in one, single property. This is called ashorthand property.The shorthand property used for lists, is the list-style property:ul{list-style: square url("sqpurple.gif");}When using the shorthand property, the order of the values are: / nrlist-style-type o.list-style-position (for a description, see the CSS properties table below) e.clist-style-image ubIt does not matter if one of the values above are missing, as long as the rest are in the et csspecified ://order. tp ht33All CSS List PropertiesThe number in the "CSS" column indicates in which CSS version the property is defined(CSS1or CSS2).Property Description Values CSSlist-style Sets all the properties for a list in one declarationlist-style-typelist-style-positionlist-style-imageinherit1list-style-image Specifies an image as the list-item markerURL http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353noneinherit1list-style-positionSpecifies if the list-item markers should appearinside or outside the content flowinsideoutside / nrinherit1 o. e.clist-style-type Specifies the type of list-item marker ubnone et csdisc ://circle tp htsquaredecimaldecimal-leading-zeroarmeniangeorgianlower-alphaupper-alphalower-greeklower-latinupper-latinlower-romanupper-romaninherit1 http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT235334CSS TablesThe look of an HTML table can be greatly improved with CSS:Company Contact CountryAlfreds Futterkiste Maria Anders GermanyBerglunds snabbköp Christina Berglund SwedenCentro comercial Moctezuma Francisco Chang MexicoErnst Handel Roland Mendel Austria / nrIsland Trading Helen Bennett UKKöniglich Essen Philip Cramer Germany o. e.cLaughing Bacchus Winecellars Yoshi Tannamuri Canada ubMagazzini Alimentari Riuniti Giovanni Rovelli Italy et csNorth/South Simon Crowther UK ://Paris spécialités Marie Bertrand France tp htThe Big Cheese Liz Nixon USAVaffeljernet Palle Ibsen DenmarkTable BordersTo specify table borders in CSS, use the border property.The example below specifies ablackborder for table, th, and td elements:Notice that the table in the example above has doubleborders. This is because both the table, th, and td elements have separate borders.Exampletable, th, td{border: 1px solid black;}35To display a single border for the table, use the border-collapse property. http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Collapse BordersThe border-collapse property sets whether the table borders are collapsed into a singleborder orseparated:table{border-collapse:collapse;} / nrtable,th, td{ o. e.cborder: 1px solid black; ub} et csTable Width and Height ://Width and height of a table is defined by the width and height properties.The example tp htbelow setsthe width of the table to 100%, and the height of the th elements to 50px:table{width:100%;}th{height:50px;}CSS CURSORSAlthough the cursors will not have the customized look in other browsers it usuallydoesnt ruin http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353anything. These browsers will simply show the normal arrow-cursor which would besame caseas if you refrained from cus tomizing cursors at all.So unless the page really doesnt workwithout the customized cursor there shouldnt be technical reasons for choosing notto.Howeverthere might be other reasons for thinking twice before adding custom cursor to yourpages. Manyusers are easily confused or irritated when a site breaks the standard user interface. / nrAdding A Customized CursorThe syntax for a customized cursor is this: o. e.c(Position the mouse over each link to see the effect) ubSelector {cursor:value} et cs36 ://For example: tp ht<html><head><style type="text/css">.xlink {cursor:crosshair}.hlink{cursor:help}</style></head><body><b><a href="mypage.htm" class="xlink">CROSS LINK</a><br><a href="mypage.htm" class="hlink">HELP LINK</a></b></body> http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353</html>2.11 CASE STUDYCase Study: Revamping an Existing SiteApril 27, 2010 32 Comments .Jacques Soudan, a client and friend I met through DivitoDesign, sent me an email with aguest post abouta case study on revamping his outdated site. Enjoy reading about his revamping project.Below is a case-study on how I used the Blueprint CSS Framework and jQuery / nrJavaScript library to o.rebuild an outdated site – somehow you helped me with it, so in return I share my work, e.choping it can be ubof future use. Thank you! et csThe website we are talking about was build back in 2001. As you would understand we ://are talking about tp hta heavily-aged website that had the following ‘problems’ or difficulties:using some CSS, but mainly tablesthe menu is a separate JS file: easy to maintain, but it doesn’t look too gooda few years ago I added the rounded corners (using JavaScript) and the redbackdrop/border, butthat doesn’t look too flashy eitherthe source is not W3C compliant (outdated code like <br> – instead of the current<br/&nsbp;>)37the footer is embedded in each page (hard to update for about 100 pages)in general, look & feel is not ‘up to date’the enquiry form uses a JavaScript file that is no longer supportedin Firefox, the banner is not centered (in IE it is…..) and looks like this (also in a table –probably http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353easy to fix, but never got to it):For a website in the modern internet world, that is not acceptable. For this reason, Icompiled a list offeatures I would like to have on the modern, good looking website.Site Features we NeedW3C compliant codeCSS and HTML in separated filesbrowser compatibility / nrrounded corners & drop shadow1 central menu file o. e.cJavaScript support (instead of using several separate scripts that (might) interfere) ubstructured design (layout without tables) et csWhere to Start? ://Last year I read this very useful article about building HTML/CSS sites using a template. tp htThis templatehas a grid CSS layout and the jQuery framework build in. I had seen those before, butwas not yet usingthem in combination with WordPress.I also found this site for dropshadow & rounded corners. As I wanted to avoid too manyjQuery plugins, Ididn’t use jQuery for the round corners. So far my experience is that jQuery roundedcorners can interferewith other plugins, needing too much work to fix (and warrant) it.For this reason, the no-Java-script solution seemed preferable. Provided, it had worked –it did not – as ituses several <divs>, it messed up the Blueprint classes, it didn’t display properly‘underneath’ the header http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353images etc. The typical pain when it comes to CSS and different techniques in differentbrowsers.So…. dropping Blueprint? Or dropping the very sleek (and easy!) rounded corners?Dilemma there…..Until playing around with Blueprint a bit more…. as it comes with grid.png, to displaythe columns fordesign purposes, which you can switch off when you go live. But then, if you can removethat backdrop, / nrwhy not adding your own???? Using my own image I had created for the initialtechnique, but thought o. e.cuseless now, it worked flawlessly! ub38 et csHere is what I did – in the Blueprint folder, there is a screen.css – just add one line and ://comment the gridline tp ht– that’s all!In your container-DIV, just add the ‘showgrid’-class: (you need that anyway, if you wantto display theBlueprint-columns):The grid.png is repeated both horizontally & vertically, but my one large image is not, soit fits perfectly –I stretched it to 1600px, as the backdrop is hardly ‘repeatable’: it is a scanned letterhead-paper with aunique texture – using only a small slice/strip and repeating that would make it lookunnatural. And I usea footer-image – including it in php, it neatly fits underneath the length of the actualcontent – not the fullbackground image of 1600px – it ‘stretches’ to the maximum height, but resizes to theneeded height. http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353I wanted to use this menu for this website. One problem though: it has no single menufile (eg. menu.php)you can add to your website. After building that menu.php file myself, the jQuery menuworked perfectly.When I created the header.php and footer.php files and included in the website usingPHP, they are easilyupdated in those 100 different pages. Depending on the page of the website, I can nowinclude different / nrimages via one page. Pretty efficient.The Template o. e.cWith all this now in place, this is how the code looks like (this is what I will use as the ub‘page-template’ et cs(there is some test copy in, to show in Blueprint columns – all the ‘body-text’ for an ://individual page is tp htplaced within the <content-div> (both <span>-classes, in blue) – everything remains inplace, nofluid/stretched text (in different browsers).<<script src="supportfiles/js/jquery.js" type="text/javascript"></script><script src="supportfiles/menu/menu.js" type="text/javascript"></script><div id="container" class="container showgrid">39<div id="header" class="span-24 prepend-top"><div class="prepend-1 span-22 append-1"></div></div><!-- end header --><div id="CONTENT" class="prepend-1 span-22 append-1 prepend-top"><div class="span-17"> http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353<h1>Main content</h1>Put your main text here (17 columns wide).</div><div class="span-5 last"><h3>Sidebar</h3>Some sidebar on the right (5 columns wide).</div></div> / nr<!-- END CONTENT --><div id="footer" class="span-24"></div> o. e.c<!-- end footer --> ub</div> et cs<!-- end container --> ://Blueprint-grid enabled: tp ht40And this is how it looks like (pictures not optimized yet):2.12 . CLIENT SIDE PROGRAMMING:JAVA SCRIPTIntroductionJavaScript is most commonly used as a client side scripting language. This means thatJavaScriptcode is written into an HTML page. When a user requests an HTML page with JavaScriptin it,the script is sent to the browser and its up to the browser to do something withit.JavaScript canbe used in other contexts than a Web browser. Netscape created server-side JavaScript asa CGIlanguagethat can do roughly the same as Perl or ASP. There is no reason why JavaScript http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353couldn’t be used to write real, complex programs. However, this site exclusively dealswith the41use of JavaScript in web browsers.I can also recommend Jeremy Keith, DOM Scripting:WebDesign with JavaScript and the Document Object Model, 1st edition, Friends of Ed,2005. This,too, is a book that doesnt delve too deeply into technology, but gives non-programmers / nrsuch as o.graphic designers/CSS wizards an excellent overview of the most common uses of e.cJavaScript - ubas well as the most common problems. et csHistory and Versions of The JavaScript language ://JavaScript is not a programming language in strict sense. Instead, it is a scripting tp htlanguagebecause it uses the browser to do the dirty work. If you command an image to be replacedbyanother one, JavaScript tells the browser to go do it. Because the browser actually doesthe work,you only need to pull some strings by writing some relatively easy lines of code. That’swhatmakes JavaScript an easy language to start with.But don’t be fooled by some beginner’s luck: JavaScript can be pretty difficult, too. Firstof all,despite its simple appearance it is a full fledged programming language: it is possible towritequite complex programs in JavaScript. This is rarely necessary when dealing with webpages, but http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353it is possible. This means that there are some complex programming structures that you’llonlyunderstand after protracted studies.Secondly, and more importantly, there are the browser differences. Though modern webbrowsers all support JavaScript, there is no sacred law that says they should supportexactly thesame JavaScript.JavaScript versions / nrThere have been several formal versions of JavaScript.1.0: Netscape 2 o. e.c1.1: Netscape 3 and Explorer 3 (the latter has bad JavaScript support, regardless of its ubversion) et cs1.2: Early Version 4 browsers ://1.3: Later Version 4 browsers and Version 5 browsers tp ht1.4: Not used in browsers, only on Netscape servers421.5: Current version.2.0: Currently under development by Brendan Eich and others.Originally, these version numbers were supposed to give support information. This-and-thatmethod would only be supported by browsers understanding JavaScript 1.something .The higherthe version number, the more nifty features the browser would support.<script language="javascript1.3" type="text/javascript"><!--complex script goes here and is executedonly by browsers that support JavaScript 1.3// --> http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353</script><script language="javascript1.0" type="text/javascript"><!--simple script goes here and is executedby all JavaScript browsers// --></script>Unfortunately Netscape 3 does not recognize the language attribute in a JavaScript / nrinclude tag.So if you do: o. e.c<script language="JavaScript1.3" src="somescript.js"></script> ubNetscape 3 loads the script, even though it doesnt support JavaScript 1.3, and shows a lot et csof error ://messages. Too bad. tp ht2.13 INTRODUCTION TO JAVA SCRIPTWhat is JavaScript?JavaScript was designed to add interactivity to HTML pagesJavaScript is a scripting languageA scripting language is a lightweight programming languageA JavaScript consists of lines of executable computer codeA JavaScript is usually embedded directly into HTML pagesJavaScript is an interpreted language (means that scripts execute without preliminarycompilation)Everyone can use JavaScript without purchasing a license43Are Java and JavaScript the Same?NO!Java and JavaScript are two completely different languages in both concept and design! http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Java (developed by Sun Microsystems) is a powerful and much more complexprogramming language - inthe same category as C and C++.What can a JavaScript Do?JavaScript gives HTML designers a programming tool - HTML authors are normally notprogrammers, but JavaScript is a scripting language with a very simple syntax! Almostanyonecan put small "snippets" of code into their HTML pages / nrJavaScript can put dynamic text into an HTML page - A JavaScript statement like this: o.document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page e.cJavaScript can react to events - A JavaScript can be set to execute when something ubhappens, et cslike when a page has finished loading or when a user clicks on an HTML element ://JavaScript can read and write HTML elements - A JavaScript can read and change the tp htcontentof an HTML elementJavaScript can be used to validate data - A JavaScript can be used to validate form databeforeit is submitted to a server. This saves the server from extra processingJavaScript can be used to detect the visitors browser - A JavaScript can be used to detectthevisitors browser, and - depending on the browser - load another page specificallydesigned forthat browserJavaScript can be used to create cookies - A JavaScript can be used to store and retrieveinformation on the visitors computer2.14 JAVASCRIPT IN PERSPECTIVEExamples http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Write text with JavascriptThe example demonstrates how to use JavaSript to write text on a web page.44Write HTML with JavascriptThe example demonstrates how to use JavaScript to write HTML tags on a web page.452.15 BASIC SYNTAXHow to Put a JavaScript Into an HTML Page / nr<html><body> o. e.c<script type="text/javascript"> ubdocument.write("Hello World!"); et cs</script> ://</body> tp ht</html>Hello World!Example ExplainedTo insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script>tag we use the"type=" attribute to define the scripting language.So, the <script type="text/javascript"> and </script> tells where the JavaScript starts andends:<html><body><script type="text/javascript">...</script></body> http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353</html>The word document.write is a standard JavaScript command for writing output to a page.By entering the document.write command between the <script> and </script> tags, thebrowser willrecognize it as a JavaScript command and execute the code line. In this case the browserwill write HelloWorld! to the page:<html> / nr<body><script type="text/javascript"> o. e.cdocument.write("Hello World!"); ub</script> et cs</body> ://</html> tp htHTML Comments to Handle Simple BrowsersBrowsers that do not support JavaScript will display JavaScript as page content.46To prevent them from doing this, and as a part of the JavaScript standard, the HTMLcomment tag can beused to "hide" the JavaScript. Just add an HTML comment tag <!-- before the firstJavaScript statement,and a --> (end of comment) after the last JavaScript statement.<html><body><script type="text/javascript"><!--document.write("Hello World!");//--> http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353</script></body></html>The two forward slashes at the end of comment line (//) is the JavaScript commentsymbol. Thisprevents JavaScript from executing the --> tag.JavaScripts in the body section will beexecutedWHILE the page loads.JavaScripts in the head section will be executed when CALLED. / nrExamplesHead section o. e.cScripts that contain functions go in the head section of the document. Then we can be ubsure that the script et csis loaded before the function is called. ://47 tp ht.2.16 JAVASCRIPT VARIABLES AND DATATYPESAs with algebra, JavaScript variables are used to hold values or expressions. A variablecan have a shortname, like x, or a more describing name like length. A JavaScript variable can also hold atext value likein carname="Volvo".Rules for JavaScript variable names:Variable names are case sensitive (y and Y are two different variables)Variable names must begin with a letter or the underscore characterNOTE: Because JavaScript is case-sensitive, variable names are case-sensitive.48Example http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353A variables value can change during the execution of a script. You can refer to a variableby its name todisplay or change its value.Declaring (Creating) JavaScript VariablesCreating variables in JavaScript is most often referred to as "declaring" variables.You can declare JavaScript variables with the var statement:var x;var carname; / nrAfter the declaration shown above, the variables has no values, but you can assign valuesto the variables o. e.cwhile you declare them: ubvar x=5; et csvar carname="Volvo"; ://Assigning Values to JavaScript Variables tp htYou assign values to JavaScript variables with assignment statements:x=5;carname="Volvo";The variable name is on the left side of the = sign, and the value you want to assign to thevariable is onthe right.After the execution of the statements above, the variable x will hold the value 5, andcarname will holdthe value Volvo.Assigning Values to Undeclared JavaScript VariablesIf you assign values to variables that has not yet been declared, the variables willautomatically bedeclared.These statements:x=5; http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353carname="Volvo";have the same effect as:var x=5;var carname="Volvo";49Redeclaring JavaScript VariablesIf you redeclare a JavaScript variable, it will not lose its original value.var x=5; / nrvar x; o.After the execution of the statements above, the variable x will still have the value of 5. e.cThe value of x is ubnot reset (or cleared) when you redeclare it. et csDataTypes ://Numbers - are values that can be processed and calculated. You dont enclose them in tp htquotationmarks. The numbers can be either positive or negative.Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript usesthestring literally; it doesnt process it. Youll use strings for text you want displayed orvalues youwant passed along.Boolean (true/false) - lets you evaluate whether a condition meets or does not meetspecifiedcriteria.Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number,whereas nullis the absence of any value.Data Types http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353TYPE EXAMPLENumbers Any number, such as 17, 21, or 54e7Strings "Greetings!" or "Fun"Boolean Either true or falseNull A special keyword for exactly that – the null value (that is, nothing)IntegersIn JavaScript, you can express integers in 3 different Bases:base 10, / nrbase 8 (octal), andbase 16 (hexadecimal). o. e.cBase 8 numbers can have digits only up to 7, so a decimal value of 18 would be an octal ubvalue of 22. et cs50 ://Similarly, hexadecimal allows digits up to F, where A is equivalent to decimal 10 and F tp htis 15. So, adecimal value of 18 would be 12 in hexadecimal notation.Converting Numbers to Different Bases TableIn order to distinguish between these three bases, JavaScript uses the following notation.Specifying bases in JavaScriptNUMBER SYSTEM NOTATIONDecimal (base 10) A normal integer without a leading 0 (zero) (ie, 752)Octal (base 8) An integer with a leading 0 (zero) (ie, 056)Hexadecimal (base 16) An integer with a leading 0x or 0X (ie, 0x5F or 0XC72)Floating Point ValuesFloating point values can include a fractional component. A floating-point literal includesa decimalinteger plus either a decimal point and a fraction expressed as another decimal number oran expression http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353indicator and a type suffix7.2945-34.22e3 means 2 x 103 => 20002E-3 means 2 x 10-3 => .002Floating point literals must, at a minimum, include a decimal integer and either thedecimal point or theexponent indicator ("e" or "E"). As with integers, floating point values can be positive or / nrnegative.Strings o. e.cTechnically, a string literal contains zero or more characters enclosed, as you know, in ubsingle or double et csquotes: ://"Hello!" tp ht‘245’"" // This example is called the empty string.NOTE: the empty string is distinct from the null value in JavaScript.51NOTE: Strings are different from other data types in JavaScript. Strings are actuallyObjects. This will becovered later on.BooleanA Boolean value is either true or false.Note: Unlike Java, C and other languages, in JavaScript Boolean values can only berepresented with trueand false. Values of 1 and 0 are not considered Boolean values in JavaScript.Null Value http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353The null value is a special value in JavaScript. The null value represents just that –Nothing. If you try toreference a variable that isn’t defined and therefore has no value, the value returned is thenull value.Likewise, with the prompt() dialog box, if the user selects the Cancel button, a null isreturned.(example)NaN (Not a Number) / nrIn addition to these values, some functions return a special value called NaN – whichmeans that the value o. e.cis not a number, parseInt() and parseFloat() are an examples of functions that return NaN ubwhen the et csargument passed to them cannot be evaluated to a number. ://Creating Values tp htIn order to make working with data types useful, you need ways to store values for lateruse. This iswhere variables come in.JavaScript StatementsA JavaScript statements is a command to the browser. The purpose of the command is totell the browserwhat to do.This JavaScript statement tells the browser to write "Hello Dolly" to the web page:document.write("Hello Dolly");It is normal to add a semicolon at the end of each executable statement. Most peoplethink this is a goodprogramming practice, and most often you will see this in JavaScript examples on theweb. http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353The semicolon is optional (according to the JavaScript standard), and the browser issupposed to interpretthe end of the line as the end of the statement. Because of this you will often seeexamples without thesemicolon at the end.JavaScript CodeJavaScript code (or just JavaScript) is a sequence of JavaScript statements.52 / nrEach statement is executed by the browser in the sequence they are written. o.This example will write a header and two paragraphs to a web page: e.c<script type="text/javascript"> ubdocument.write("<h1>This is a header</h1>"); et csdocument.write("<p>This is a paragraph</p>"); ://document.write("<p>This is another paragraph</p>"); tp ht</script>JavaScript BlocksJavaScript statements can be grouped together in blocks.Blocks start with a left curly bracket {, and ends with a right curly bracket }.The purpose of a block is to make the sequence of statements execute together.This example will write a header and two paragraphs to a web page:<script type="text/javascript">{document.write("<h1>This is a header</h1>");document.write("<p>This is a paragraph</p>");document.write("<p>This is another paragraph</p>");}</script> http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353The example above is not very useful. It just demonstrates the use of a block. Normally ablock is used togroup statements together in a function or in a condition (where a group of statementsshould be executedif a condition is met).You will learn more about functions and conditions in later chapters.Where to Put the JavaScriptJavaScripts in a page will be executed immediately while the page loads into the browser. / nrThis is not o.always what we want. Sometimes we want to execute a script when a page loads, other e.ctimes when a user ubtriggers an event. et csScripts in the head section: Scripts to be executed when they are called, or when an event ://is triggered, tp htgo in the head section. When you place a script in the head section, you will ensure thatthe script isloaded before anyone uses it.<html><head><script type="text/javascript">53....</script></head>Scripts in the body section: Scripts to be executed when the page loads go in the bodysection. Whenyou place a script in the body section it generates the content of the page.<html> http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353<head></head><body><script type="text/javascript">....</script></body>Scripts in both the body and the head section: You can place an unlimited number of / nrscripts in your o.document, so you can have scripts in both the body and the head section. e.c<html> ub<head> et cs<script type="text/javascript"> ://.... tp ht</script></head><body><script type="text/javascript">....</script></body>Using an External JavaScriptSometimes you might want to run the same JavaScript on several pages, without havingto write the samescript on every page.To simplify this, you can write a JavaScript in an external file. Save the externalJavaScript file with a .jsfile extension. http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Note: The external script cannot contain the <script> tag!To use the external script, point to the .js file in the "src" attribute of the <script> tag:<html><head><script src="xxx.js"></script>54</head><body> / nr</body></html> o. e.c2.17 JAVASCRIPT STATEMENTS ubA JavaScript statement is a command to the browser. The purpose of the command is to et cstell the browser ://what to do. tp htThis JavaScript statement tells the browser to write "Hello Dolly" to the web page:document.write("Hello Dolly");It is normal to add a semicolon at the end of each executable statement. Most peoplethink this is a goodprogramming practice, and most often you will see this in JavaScript examples on theweb.The semicolon is optional (according to the JavaScript standard), and the browser issupposed to interpretthe end of the line as the end of the statement. Because of this you will often seeexamples without thesemicolon at the end.Note: Using semicolons makes it possible to write multiple statements on one line.JavaScript CodeJavaScript code (or just JavaScript) is a sequence of JavaScript statements. http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Each statement is executed by the browser in the sequence they are written.This example will write a header and two paragraphs to a web page:<script type="text/javascript">document.write("<h1>This is a header</h1>");document.write("<p>This is a paragraph</p>");document.write("<p>This is another paragraph</p>");</script>2.18 JAVASCRIPT OPERATORS / nr= is used to assign values.+ is used to add values. o. e.cThe assignment operator = is used to assign values to JavaScript variables. ub55 et csThe arithmetic operator + is used to add values together. ://y=5; tp htz=2;x=y+z;The value of x, after the execution of the statements above is 7.JavaScript Arithmetic OperatorsArithmetic operators are used to perform arithmetic between variables and/or values.Given that y=5, the table below explains the arithmetic operators:Operator Description Example Result+ Addition x=y+2 x=7- Subtraction x=y-2 x=3* Multiplication x=y*2 x=10/ Division x=y/2 x=2.5% Modulus (division remainder) x=y%2 x=1++ Increment x=++y x=6-- Decrement x=--y x=4 http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353JavaScript Assignment OperatorsAssignment operators are used to assign values to JavaScript variables.Given that x=10 and y=5, the table below explains the assignment operators:Operator Example Same As Result= x=y x=5+= x+=y x=x+y x=1556-= x-=y x=x-y x=5 / nr*= x*=y x=x*y x=50/= x/=y x=x/y x=2 o. e.c%= x%=y x=x%y x=0 ubThe + Operator Used on Strings et csThe + operator can also be used to add string variables or text values together. ://To add two or more string variables together, use the + operator. tp httxt1="What a very";txt2="nice day";txt3=txt1+txt2;After the execution of the statements above, the variable txt3 contains "What a veryniceday".To add a space between the two strings, insert a space into one of the strings:txt1="What a very ";txt2="nice day";txt3=txt1+txt2;or insert a space into the expression:txt1="What a very";txt2="nice day";txt3=txt1+" "+txt2;After the execution of the statements above, the variable txt3 contains: http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353"What a very nice day"Adding Strings and NumbersThe rule is: If you add a number and a string, the result will be a string!Examplex=5+5;document.write(x);57x="5"+"5"; / nrdocument.write(x);x=5+"5"; o. e.cdocument.write(x); ubx="5"+5; et csdocument.write(x); ://If you add a number and a string, the result will be a string. tp htComparison and Logical operators are used to test for true or false.Comparison OperatorsComparison operators are used in logical statements to determine equality or differencebetween variablesor values. Given that x=5, the table below explains the comparison operators:Operator Description Example== is equal to x==8 is false=== is exactly equal to (value and type) x===5 is truex==="5" is false!= is not equal x!=8 is true> is greater than x>8 is false< is less than x<8 is true>= is greater than or equal to x>=8 is false<= is less than or equal to x<=8 is true http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353How Can it be UsedComparison operators can be used in conditional statements to compare values and takeaction dependingon the result:if (age<18) document.write("Too young");58You will learn more about the use of conditional statements in the next chapter of thistutorial. / nrLogical Operators o.Logical operators are used in determine the logic between variables or values. e.cGiven that x=6 and y=3, the table below explains the logical operators: ubOperator Description Example et cs&& and (x < 10 && y > 1) is true ://|| or (x==5 || y==5) is false tp ht! not !(x==y) is trueConditional OperatorJavaScript also contains a conditional operator that assigns a value to a variable based onsome condition.Syntaxvariablename=(condition)?value1:value2Examplegreeting=(visitor=="PRES")?"Dear President ":"Dear ";If the variable visitor has the value of "PRES", then the variable greeting will be assignedthe value"Dear President " else it will be assigned "Dear".Conditional statements in JavaScript are used to perform different actions based ondifferent conditions.Examples http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353If statementHow to write an if statement.59Conditional StatementsVery often when you write code, you want to perform different actions for differentdecisions. You canuse conditional statements in your code to do this.In JavaScript we have the following conditional statements: / nrif statement - use this statement if you want to execute some code only if a specifiedcondition is o. e.ctrue ubif...else statement - use this statement if you want to execute some code if the condition is et cstrue ://and another code if the condition is false tp htif...else if....else statement - use this statement if you want to select one of many blocks ofcodeto be executedswitch statement - use this statement if you want to select one of many blocks of code tobeexecutedIf StatementYou should use the if statement if you want to execute some code only if a specifiedcondition is true.Syntaxif (condition)60{code to be executed if condition is true http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353}2.19 JAVASCRIPT LITERAL VALUESLiteral values are the ones you type into mathematical or string expressions. For example23 (an integer),12.32E23 (a floating point), or flopsy the Hamster (a string).String literals can be enclosed by either single or double quotes. For example:literal string"literal string" / nrliteral string with "double quotes" inside o.There are five special characters you can use in literal strings. These are listed in the table e.cbelow. ubReference Meaning et csb Backspace ://f Form Feed tp htn New Liner Carriage Returnt Tab2.10 JAVASCRIPT FUNCTIONSA function will be executed by an event or by a call to the function.JavaScript FunctionsTo keep the browser from executing a script when the page loads, you can put your scriptinto afunction.A function contains code that will be executed by an event or by a call to thefunction.You may61call a function from anywhere within a page (or even from other pages if the function isembedded in an http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353external .js file).Functions can be defined both in the <head> and in the <body> sectionof a document.However, to assure that a function is read/loaded by the browser before it is called, itcould be wise to putfunctions in the <head> section.How to Define a FunctionSyntaxfunction functionname(var1,var2,...,varX) / nr{some code o. e.c} ubThe parameters var1, var2, etc. are variables or values passed into the function. The { and et csthe } defines ://the start and end of the function. tp htNote: A function with no parameters must include the parentheses () after the functionname.Note: Do not forget about the importance of capitals in JavaScript! The word functionmust be written inlowercase letters, otherwise a JavaScript error occurs! Also note that you must call afunction with theexact same capitals as in the function name.JavaScript Function Example<html><head><script type="text/javascript">function displaymessage(){alert("Hello World!"); http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353}</script></head><body><form><input type="button" value="Click me!" onclick="displaymessage()" /></form></body> / nr</html> o.If the line: alert("Hello world!!") in the example above had not been put within a e.cfunction, it would have ubbeen executed as soon as the page was loaded. Now, the script is not executed before a et csuser hits the input ://button. The function displaymessage() will be executed if the input button is clicked. tp ht62You will learn more about JavaScript events in the JS Events chapter.The return StatementThe return statement is used to specify the value that is returned from the function.So,functions that aregoing to return a value must use the return statement.The example below returns theproduct of twonumbers (a and b):Example<html><head><script type="text/javascript">function product(a,b){ http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353return a*b;}</script></head><body><script type="text/javascript">document.write(product(4,3));</script> / nr</body></html> o. e.cFunction with a parameter ubHow to pass a variable to a function, and use the variable in the function. et cs<html> ://<head> tp ht<script type="text/javascript">function myfunction(txt){alert(txt);}</script></head>63<body><form><input type="button" onclick="myfunction(Hello)" value="Call function"></form><p>By pressing the button above, a function will be called with "Hello" as a parameter.The function will http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353alert the parameter.</p></body></html>OutputBy pressing the button above, a function will be called with "Hello" as a parameter. Thefunction willalert the parameter2.21 OBJECTS / nrJavaScript Objects represent self contained entities consisting of variables (calledproperties in object o. e.cterminology) and functions (called methods) that can be used to perform tasks and store ubcomplex data. et csJavaScript objects fall into three categories: Built-in Objects, Custom Objects and ://Document Object tp htModel (DOM) Objects. Built-in objects are objects that are provided with JavaScript tomake your life asa JavaScript developer easier. In many of the examples given in this book we have usedthedocument.write() mechanism to write text to the current web page. Whether you knew itor not, you havebeen using the write() method of the JavaScript built-in document object when you haverun these scripts.Document Object Model (DOM) Objects provide the foundation for creating dynamicweb pages. TheDOM provides the ability for a JavaScript script to access, manipulate, and extend thecontent of a webpage dynamically (i.e. without having to reload the page). The DOM essentially presentsthe web page as http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353a tree hierarchy of objects representing the contents and elements of the web page. Theseobjects, in turn,contain properties and methods that allow you to access and change parts of the webpage. Customobjects are objects that you, as a JavaScript developer, create and use.Creating a Custom JavaScript ObjectCreating a custom JavaScript object is quite similar to constructing a function. The syntaxis as follows: / nrfunction object(parameter1, parameter2, parameter3,...){ o. e.cthis.property1 = parameter1; ubthis.property2 = parameter2; et csthis.property3 = parameter3; ://this.method1 = function1; tp htthis.method2 = function2;this.method3 = function3;64}In the above outline object refers to the name of the object - this can be any valid (andhopefullydescriptive) name you choose to use. The parameters define the values that you will passinto the objectwhen you instantiate it later.Creating and Using Object InstancesIn the previous section we learned how to create an object definition. It is important tonote that, at thispoint, we have only described what the object will do (we have basically createdblueprint of the object), http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353we have not actually created an object we can work with (this is known as an objectinstance). Objectinstances are created using the new keyword and are assigned to an object variable thatwill be used toreference the object. For example, in the following script we will create a new instance ofthe car objectwith the name myCar:carObject = new car ("Ford", "Focus", "Red"); / nrWe have also passed through parameters to initialize the properties of the object (make,model and color). o. e.cNext we need to understand how to call a method on an object and access an object ubproperty. This is et csachieved by using what is called dot notation on the name of the object instance: ://To access a property: tp htobjectInstance.propertyNameTo call a method of an object:objectInstance.methodName()In our example we have a method called displayCar() to display the 3 properties of theobject. Followingthe above dot notation syntax we can call this method as follows:carObject.displayCar()We can also access a property, for example the color as follows:document.write ("The make property of myCar is " + myCar.make );Finally, we can also change one of the properties of an object instance:myCar.make = "BMW";Lets now bring all of this together in a complete example within an HTML page:<html>65 http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353<head><title>A Simple JavaScript Function Example</title><script language="JavaScript" type="text/javascript">function car (make, model, color){this.make = make;this.model = model;this.color = color / nrthis.displayCar = displayCar;} o. e.cfunction displayCar() ub{ et csdocument.writeln("Make = " + this.make) ://} tp ht</script></head><script language="JavaScript" type="text/javascript">myCar = new car ("Ford", "Focus", "Red");myCar.displayCar();myCar.make = "BMW";myCar.displayCar();</script></body></html>Extending ObjectsJavaScript object instances are extremely flexible in that they can easily be extended. Toextend an object http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353that you have already created use object prototypes. The syntax for prototyping is asfollows:objectType.prototype.propertyNameFollowing this syntax we could add a year property to our car class and initialize it to theyear 2001using the following:car.prototype.year = "2001";When we now create an instance of the object it will contain this new property which can / nrbe read o.and manipulated in the same way as all the other properties in this class. e.c2.22 ARRAYS ubThe Array object is used to store multiple values in a single variable. et cs66 ://Array Object Reference tp htFor a complete reference of all the properties and methods that can be used with theArray object, go toour complete Array object reference.The reference contains a brief description andexamples of use foreach property and method!What is an Array?An array is a special variable, which can hold more than one value, at a time.If you have a list of items (a list of car names, for example), storing the cars in singlevariables could looklike this:cars1="Saab";cars2="Volvo";cars3="BMW"; http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353However, what if you want to loop through the cars and find a specific one? And what ifyou had not 3cars, but 300?The best solution here is to use an array!An array can hold all your variable values undera single name.And you can access the values by referring to the array name.Each element in the arrayhas its own ID sothat it can be easily accessed. / nrCreate an ArrayAn array can be defined in three ways. o. e.cThe following code creates an Array object called myCars: ub1: et csvar myCars=new Array(); // regular array (add an optional integer ://myCars[0]="Saab"; // argument to control arrays size) tp htmyCars[1]="Volvo";myCars[2]="BMW";2: var myCars=new Array("Saab","Volvo","BMW"); // condensed array3: var myCars=["Saab","Volvo","BMW"]; // literal arrayNote: If you specify numbers or true/false values inside the array then the variable typewill be Numberor Boolean, instead of String.67Access an ArrayYou can refer to a particular element in an array by referring to the name of the array andthe indexnumber. The index number starts at 0.The following code line:document.write(myCars[0]); http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353will result in the following output:SaabModify Values in an ArrayTo modify a value in an existing array, just add a new value to the array with a specifiedindex number:myCars[0]="Opel";Now, the following code line:document.write(myCars[0]); / nrwill result in the following output:`Opel o. e.cJoin two arrays - concat() ubJoin three arrays - concat() et csJoin all elements of an array into a string - join() ://Remove the last element of an array - pop() tp htAdd new elements to the end of an array - push()Reverse the order of the elements in an array - reverse()Remove the first element of an array - shift()Select elements from an array - slice()Sort an array (alphabetically and ascending) - sort()Sort numbers (numerically and ascending) - sort()Sort numbers (numerically and descending) - sort()68Add an element to position 2 in an array - splice()Convert an array to a string - toString()Add new elements to the beginning of an array - unshift()2.23 BUILT –IN OBJECTSJava Script StringThe String object is used to manipulate a stored piece of text. http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Complete String Object ReferenceFor a complete reference of all the properties and methods that can be used with theString object, go toour complete String object reference.The reference contains a brief description and examples of use for each property andmethod!String objectThe String object is used to manipulate a stored piece of text. / nrExamples of use: o.The following example uses the length property of the String object to find the length of a e.cstring: ubvar txt="Hello world!"; et csdocument.write(txt.length); ://The code above will result in the following output: tp ht12The following example uses the toUpperCase() method of the String object to convert astring touppercase letters:var txt="Hello world!";document.write(txt.toUpperCase());The code above will result in the following output:HELLO WORLD!JavaScript Date ObjectThe Date object is used to work with dates and times.69Complete Date Object ReferenceFor a complete reference of all the properties and methods that can be used with the Dateobject, go to our http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353complete Date object reference.The reference contains a brief description and examplesof use for eachproperty and method!Create a Date Objecthe Date object is used to work with dates and times. Date objects are created with theDate() constructor.There are four ways of instantiating a date:new Date() // current date and time / nrnew Date(milliseconds) //milliseconds since 1970/01/01new Date(dateString) o. e.cnew Date(year, month, day, hours, minutes, seconds, milliseconds) ubMost parameters above are optional. Not specifying, causes 0 to be passed in.Once a Date et csobject is ://created, a number of methods allow you to operate on it. Most methods allow you to get tp htand set the year,month, day, hour, minute, second, and milliseconds of the object, using either local timeor UTC(universal, or GMT) time.All dates are calculated in milliseconds from 01 January, 197000:00:00Universal Time (UTC) with a day containing 86,400,000 milliseconds.Some examples of instantiating a date:today = new Date()d1 = new Date("October 13, 1975 11:13:00")d2 = new Date(79,5,24)d3 = new Date(79,5,24,11,33,0)Set DatesWe can easily manipulate the date by using the methods available for the Date object.Inthe example http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353below we set a Date object to a specific date (14th January 2010):var myDate=new Date();myDate.setFullYear(2010,0,14);And in the following example we set a Date object to be 5 days into the future:var myDate=new Date();myDate.setDate(myDate.getDate()+5);Compare Two DatesThe Date object is also used to compare two dates. / nrThe following example compares todays date with the 14th January 201070 o. e.cvar myDate=new Date(); ubmyDate.setFullYear(2010,0,14); et csvar today = new Date(); ://if (myDate>today) tp ht{alert("Today is before 14th January 2010");}else{alert("Today is after 14th January 2010");}:JavaScript Boolean ObjectThe Boolean object is used to convert a non-Boolean value to a Boolean value (true orfalse).Complete Boolean Object ReferenceFor a complete reference of all the properties and methods that can be used with theBoolean object, go to http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353our complete Boolean object reference.The reference contains a brief description andexamples of use foreach property and method!Create a Boolean ObjectThe Boolean object represents two values: "true" or "false".The following code creates aBoolean objectcalled myBoolean:var myBoolean=new Boolean(); / nrNote: If the Boolean object has no initial value or if it is 0, -0, null, "", false, undefined,or NaN, the o. e.cobject is set to false. Otherwise it is true (even with the string "false")! ubAll the following lines of code create Boolean objects with an initial value of false: et csvar myBoolean=new Boolean(); ://var myBoolean=new Boolean(0); tp htvar myBoolean=new Boolean(null);var myBoolean=new Boolean("");var myBoolean=new Boolean(false);var myBoolean=new Boolean(NaN);And all the following lines of code create Boolean objects with an initial value of true:71var myBoolean=new Boolean(1);var myBoolean=new Boolean(true);var myBoolean=new Boolean("true");var myBoolean=new Boolean("false");var myBoolean=new Boolean("Richard");JavaScript Math ObjectThe Math object allows you to perform mathematical tasks.Complete Math Object Reference http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353For a complete reference of all the properties and methods that can be used with the Mathobject, go toour complete Math object reference.The reference contains a brief description andexamples of use foreach property and method!Math ObjectThe Math object allows you to perform mathematical tasks.The Math object includesseveral / nrmathematical constants and methods.Syntax for using properties/methods of Math: o. e.cvar pi_value=Math.PI; ubvar sqrt_value=Math.sqrt(16); et csMathematical Constants ://JavaScript provides eight mathematical constants that can be accessed from the Math tp htobject. These are: E,PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E,and base-10 logof E.Mathematical MethodsIn addition to the mathematical constants that can be accessed from the Math object thereare also severalmethods available.The following example uses the round() method of the Math object toround a numberto the nearest integer:document.write(Math.round(4.7));The code above will result in the following output: 5JavaScript RegExp ObjectRegExp, is short for regular expression. http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT235372Complete RegExp Object ReferenceFor a complete reference of all the properties and methods that can be used with theRegExp object, go toour complete RegExp object reference.The reference contains a brief description andexamples of use foreach property and method!What is RegExp? / nrA regular expression is an object that describes a pattern of characters.When you searchin a text, you can o. e.cuse a pattern to describe what you are searching for.A simple pattern can be one single ubcharacter.A more et cscomplicated pattern can consist of more characters, and can be used for parsing, format ://checking, tp htsubstitution and more.Regular expressions are used to perform powerful pattern-matchingand "searchand-replace" functions on text.Syntaxvar txt=new RegExp(pattern,modifiers);or more simply:var txt=/pattern/modifiers;pattern specifies the pattern of an expressionmodifiers specify if a search should be global, case-sensitive, etc.RegExp ModifiersModifiers are used to perform case-insensitive and global searches.The i modifier is usedto perform caseinsensitivematching.The g modifier is used to perform a global match (find all matches rather thanstopping after the first match). http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Example 1Do a case-insensitive search for "w3schools" in a string:var str="Visit W3Schools";var patt1=/w3schools/i;he marked text below shows where the expression gets a match:Visit W3Schoolstest()The test() method searches a string for a specified value, and returns true or false, / nrdepending on the result.73 o. e.cexec() ubThe exec() method searches a string for a specified value, and returns the text of the et csfound value. If no ://match is found, it returns null. tp ht2.24 JAVASCRIPT DEBUGGERSFirebugFirebug is a powerful extension for Firefox that has many development and debuggingtoolsincluding JavaScript debugger and profiler.Venkman JavaScript DebuggerVenkman JavaScript Debugger (for Mozilla based browsers such as Netscape 7.x,Firefox/Phoenix/Firebird and Mozilla Suite 1.x)Introduction to VenkmanUsing Breakpoints in VenkmanInternet Explorer debuggingMicrosoft Script Debugger (for Internet Explorer) The script debugger is from theWindows 98and NT era. It has been succeeded by the Developer Toolbar http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Internet Explorer Developer ToolbarMicrosofts Visual Web Developer Express is Microsofts free version of the Visual StudioIDE. Itcomes with a JS debugger. For a quick summary of its capabilities see [1]Internet Explorer 8 has a firebug-like web development tool by default (no add-on) whichcan beaccessed by pressing F12. The web development tool also provides the ability to switchbetween / nrthe IE8 and IE7 rendering engines.JTF: Javascript Unit Testing Farm o. e.cJTF is a collaborative website that enables you to create test cases that will be tested by uball et csbrowsers. Its the best way to do TDD and to be sure that your code will work well on all ://browsers. tp htjsUnitjsUnitCommon MistakesCarefully read your code for typos.Be sure that every "(" is closed by a ")" and every "{" is closed by a "}".Trailing commas in Array and Object declarations will throw an error in MicrosoftInternetExplorer but not in Gecko-based browsers such as Firefox.// Object74var obj = {foo : bar,color : red, //trailing comma}; http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353// Arrayvar arr = [foo,bar, //trailing comma];Remember that JavaScript is case sensitive. Look for case related errors.Dont use Reserved Words as variable names, function names or loop labels.Escape quotes in strings with a "" or the JavaScript interpreter will think a new string is / nrbeingstarted, i.e: o. e.calert(Hes eating food); should be ubalert(Hes eating food); or alert("Hes eating food"); et csWhen converting strings to numbers using the parseInt function, remember that "08" and ://"09" tp ht(e.g. in datetimes) indicate an octal number, because of the prefix zero. Using parseIntusing aradix of 10 prevents wrong conversion. var n = parseInt(09,10);Remember that JavaScript is platform independent, but is not browser independent.Becausethere are no properly enforced standards, there are functions, properties and even objectsthat maybe available in one browser, but not available in another, e.g. Mozilla / Gecko Arrayshave anindexOf() function; Microsoft Internet Explorer does not.Debugging MethodsDebugging in Javascript doesnt differ very much from debugging in most otherprogramming languages.See the article at Computer programming/debugging. http://csetube.co.nr/
    • GKMCET Lecture PlanSubject Name: Web TechnologySubject Code: IT2353Following Variables as a Script is RunningThe most basic way to inspect variables while running is a simple alert() call. Howeversomedevelopment environments allow you to step through your code, inspecting variables asyou go. Thesekind of environments may allow you to change variables while the program is paused.Browser BugsSometimes the browser is buggy, not your script. This means you must find a / nrworkaround. o. e.c ub et cs :// tp ht http://csetube.co.nr/