WordPress.com
UNIT II CSS AND CLIENT SIDE SCRIPTING
Style Sheets: CSS-Introduction to Cascading Style Sheets-Features-Core Syntax-Style Sheets and HTML Style Rule Cascading and Inheritance-Text Properties-Box Model Normal Flow Box Layout-Beyond the Normal Flow-Other Properties-Case Study. Client- Side Programming: The JavaScript Language-History and Versions Introduction JavaScript in Perspective-Syntax-Variables and Data Types-Statements-Operators- Literals-Functions-Objects-Arrays-Built-in Objects-JavaScript Debuggers.
Style Sheets: CSS
2.1 Introduction to Cascading Style Sheets
Cascading Style Sheets (CSS) is a slightly misleading term, since a website might have only one CSS file (style sheet), or the CSS might be embedded within an HTML file. It is better to think of CSS as a technology (in the singular). CSS is comprised of statements that control the styling of HTML documents. Simply put, an HTML document should convey content. A CSS document should control the styling of that content.
...
All these examples can easily be replaced with CSS. Don't worry if you don't understand these declarations 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 of declarations embedded within the head of the HTML file) which then controls the style of the HTML document. These style declarations are called CSS rules.
2.2 Features
The latest version of Cascade Style Sheets, CSS 3, was developed to make Web design easier but it became a hot topic for a while because not all browsers supported it. However, trends change quickly in technology and all browser makers currently are implementing complete CSS 3 support. Making that process easier for the browser manufacturers is CSS 3's modularized specification, which allows them to provide support for modules incrementally without having to perform major refactoring of the browsers' codebases. The modularization concept not only makes the process of approving individual CSS 3 modules easier and faster, but it also makes documenting the spec easier. Eventually, CSS 3 -- along with HTML5 -- are going to be the future of the web. You should begin making your Web pages compatible with these latest specifications. In this article, I explore 10 of the exciting new features in CSS 3, which is going to change the way developers who used CSS2 build web sites. Some of the features are:
• CSS Text Shadow
• CSS Selectors
• CSS Rounded Corners
• CSS Border Image
2.3 Core Syntax
2.3.1 At-Rules
As we learned when we studied CSS statements, there are two types of statements. The most common is the rule-sets statement, and the other is the at-rules statement. As opposed to rule sets, at-rules statements consist of three things: the at-keyword, @, an identifier, and a declaration. This declaration is defined as all content contained within a set of curly braces, or by all content up until the next semicolon.
@import
Perhaps the most commonly used of the at-rules, @import, is used to import an external style sheet into a document. It can be used to replace the LINK element, and serves the same function, except that imported style sheets have a lower weight (due to having less proximity) than linked style sheets.
@import url(imported.css);
@import url(addonstyles.css); @import "addonstyles.css";
Relative and absolute URLs are allowed, but only one is allowed per instance of @import. One or more comma-separated target media may be used here.
@charset
@charset is used to specify the character encoding of a document, and must appear no more than once. It must be the very first declaration in the external style sheet, and cannot appear in embedded style sheets. @charset is used by XML documents to define a character set.
@charset "utf-8";
@namespace
The @namespace rule allows the declaration of a namespace prefix to be used by selectors in a style sheet. If the optional namespace prefix is omitted, then the URL provided becomes the default namespace. Any @namespace rules in a style sheet must come after all @import and
• @charset at-rules, and come before all CSS rule-sets.
• @namespace foo url("");
• @namespace can be used together with the new CSS3 selectors (see below). It defines which XML namespace to use in the CSS. If the XML document doesn't have matching XML namespace information, the CSS is ignored.
@font-face
This was removed from the CSS2.1 specification, but is still used to describe a font face for a document..
@font-face { font-family: "Scarborough Light"; src:
url(""); } @font-face { font-family:
Santiago; src: local ("Santiago"), url(""),
format("truetype"); unicode-range: U+??,U+100-220; font-size: all; fontfamily:
sans-serif; }
@media
This at-rule is used within a style sheet to target specific media. For example, after defining how an element is to be displayed (in this example for the screen), the declaration can be overwritten for 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
aural (for speech synthesizers)
handheld
print
projection
screen
braille
embossed
tty
tv
@page
This at-rules declaration is used to define rules for page sizing and orientation rules for printing.
@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 right.
@page :first {margin-top: 12cm;} @page :left {margin-left: 4.5cm;}
@page :right {margin-right: 7cm;}
@fontdef
This is an old Netscape-specific at-rule which we should ignore.
CSS1 Selectors
[pic]
FIG 2.1 CSS1 SELECTORS
Selectors refer to elements in an HTML document tree. Using CSS, they are atternmatched in order to apply styles to those elements. A selector consists of one or more elements, classes, or IDs, and may also contain pseudo-elements and/or pseudo-classes.
Type Selector
The type selector is the simplest selector of all, and matches all occurrences of an element. In this example, all tags throughout the document will have the following style applied, unless overridden.
p {color: #666;}
Universal Selector
The universal selector, used alone, matches all elements in the document tree, and thus will apply styles to all elements. It is in effect a wildcard.
* {margin: 0; padding: 0;}
In this example, all tags are reset to have no padding or margin. This, by the way, is a practice to gain control over all the default padding and margin inherent in the way User Agents (UAs) display HTML.
Class Selector
The 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" class will only function as styled if called into an H3 element. This is useful if you have another "cartHeader" declaration that you wish to override in the context of an H3 element, or if you wish to enforce the placement of this class.
ID Selector
The ID selector matches an ID. IDs are identifiers unique to a page. They bear a resemblance to classes, but are used a bit differently. IDs will be treated more fully below. The first two ID examples below refer to sections of a web page, while the last refers to a specific occurrence of an item, say, an image in a DHTML menu. IDs have a higher specificity than classes.
#header {height: 100px;} #footer {color: #F00;} #xyz123 {font-size: 9px;}
Descendant Selector
A selector can itself be a chain of one or more selectors, and is thus sometimes called a compound selector. The descendant selector is the only compound selector in CSS1, and consists of two or more selectors and one or more white space combinators. In the example below, the white space between the H1 and EM elements is the descendant combinator. In other words, white space conveys a hierarchy. (If a comma were to have intervened instead, it would mean that we were styling H1 and EM elements alike.) Selectors using combinators are used for more precise drill-down to specific points within the document tree. In this example tags will have the color red applied to them if they are within an tag.
h1 em {color: #F00;}
Note that EM elements do not have to be immediately inside an H1 heading, that is, they do not have to be children, but merely descendants of their ancestor. The previous style would apply to an EM element in either of the following statements.
This is a main heading This is another
main heading
In the next example, the color black will be applied to all tags that are descendants (whether directly or not) of tags which are in turn descendants (whether directly or not) of tags, no matter how deep the tags are in the document tree.
div p span {color: #000;}
That is to say, this style would apply to SPAN elements inside a P element, even if they are many levels below (that is, within) the DIV element, as long as there is an intervening P element. 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. The SPAN element could in fact be much deeper, but it will not be styled by this declaration if it is the child (direct descendant) of a P element.
Other Selectors
Other combinators convey greater precision. They include the direct adjacent sibling Combinatory (+), the indirect adjacent sibling (or general) combinator (~), and the child combinatory (>). These combinators will be treated below because they are part of the CSS2.1 specification, and are not supported in IE6.
Example:
div.ex
{
width:220px;
padding:10px;
border:5px solid gray;
margin:0px;
}
2.4 STYLE SHEETS AND HTML STYLE RULE
To apply a style, CSS uses the HTML document tree to match an element, attribute, or value in an HTML file. For an HTML page to properly use CSS, it should be well-formed and valid, and possess a valid doctype. If these conditions are not met the CSS match may not yield the desired results. There are two types of CSS statements: rule-sets and at-rules. A rule set, also known simply as a rule, is the more common statement, and consists of a selector and a declaration block, sometimes simply called a block. The selector can be an element, class, or ID, and may include combinators, pseudo-elements, or pseudo-classes.
Statement Type 1: Rules Sets (Rules)
statement + statement block
X {declaration; declaration;}
X {property; value; property: value;}
div > p {font-size: 1em; color #333;}
Statement Type 2: At-Rules
at-keyword + identifier + declaration
@import "subs.css";
The declaration block consists of the braces and everything in between. Within the declaration block are declarations, which consist of properties and values. Properties are separated from their values (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 document lest we confuse CSS properties with HTML attributes.) White space inside a declaration block is ignored, which facilitates formatting the code in developer-friendly ways.
For example, both of the following statements are valid and equivalent, though the latter slightly increases document weight.
h1 {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 of measurement (e.g.1.2em, not 1.2 em). As opposed to rule sets, at-rules statements consist of the at-keyword "@", an identifier, and a declaration. This declaration is defined as all the content contained within a set of curly braces, or by all content up until the next semicolon. Note the following two examples.
@media print { p {font-size: 10pt;} tt {font-family: monospace;} } @import url(addonstyles.css);
Other examples of at-keywords are media, font-face, and page. At-rules will be treated separately below.
Properties
I have decided not to include a description of all CSS1 and CSS2.1 Properties (such as font-size, text-transform, border, margin, and many others) because they are numerous and can be examined in the Property References section of this site. Moreover, they are used throughout this tutorial and can be easily deduced. So we move directly to CSS1 selectors.
2.5 STYLE RULE CASCADING AND INHERITANCE
CSS are probably wondering what exactly cascades about cascading style sheets. In this section, we look at the idea of cascading, and a related idea, that of inheritance. Both are important underlying concepts that you will need to grasp, and understand the difference between, in order to work properly with style sheets.
Rule Cascade
A single style sheet associated with one or more web pages is valuable, but in quite a limited way. For small sites, the single style sheet is sufficient, but for larger sites, especially sites managed by more than one person (perhaps several teams who may never communicate) single style sheets don't provide the ability to share common styles, and extend these styles where necessary. This can be a significant limitation. Cascading style sheets are unlike the style sheets you might have worked with using word processors, because they can be linked together to create a hierarchy of related style sheets.
Managing style at large sites using @import imagine how the web site for a large organization, says a corporation, might be structured. As sites grow in complexity, individual divisions, departments, and workgroups become more responsible for their own section of a site. We can already see a potential problem – how do we ensure a consistent look and feel across the whole site? A dedicated web development team can ensure that a style guide is adhered to.
Specificity
Get browser support information for specificity in the downloadable version of this guide or our browser support tables. At this point it might be timely to have a quick discussion of specificity. Both inside a single style sheet, and in a cascade of style sheets, it should be clear that more than one rule can apply to the same element. What happens when two properties in separate rules which both apply to an element contradict one another? Obviously they can't both apply (the text of an element can't be both red and blue, for example). CSS provides a mechanism for resolving these conflicts, called specificity.
Some selectors are more specific than others. For example, the class and ID selectors are more specific than simple HTML element selectors. When two rules select the same element and the properties contradict one another, the rule with the more specific selector takes precedence. Specificity for selectors is a little involved. Without going into the full detail, most situations can be resolved with the following rules.
1. ID selectors are more specific than other selectors
2. Class selectors are more specific than HTML element selectors, and other selectors such as contextual, pseudo class and pseudo element selectors.
3. Contextual selectors, and other selectors involving more than one HTML element selector are more specific than a single element selector (and for two multiple element selectors, the one with more elements is more specific than the one with fewer.)
There are times though when the two rules will have the same specificity. In this case, the rule that comes later in the cascade prevails. For example, where one rule is in an imported style sheet, and the other in the style sheet itself, the rule in the style sheet which is importing takes precedence. When the two rules are in the same style sheet, it is the one furthest from the top of the style sheet that takes precedence. While these rules seem complicated at first, they are pretty much common sense, and it is uncommon that much confusion or difficulty arises for a developer.
Style Inheritance
Any HTML page comprises a number of (perhaps a large number of) elements - headings, paragraphs, lists, and so on. Often, developers use the term "tag" to refer to an element, making reference for example to "the p tag". But the tag is simply the part of the element. The whole construction of , this is the content of the paragraph is in fact the element (as we refer to it in this guide). What many web developers don't realize (largely because it wasn't particularly important until style sheets came along) is that every element is contained by another element, and may itself contain other elements. The technical term for this is the containment hierarchy of a web page.
At the top of the containment hierarchy is the element of the page. Every other element on a web page is contained within the element, or one of the elements contained within it, and so on. Similarly, many elements will be contained in paragraphs, while paragraphs are contained in the .
Graphically, we can understand it like this. figure 4: the HTML containment hierarchy I said above that style sheets made it important to understand this. Why? Well, with cascading style sheets, elements often (and with CSS2 can always be forced to) inherit properties from the elements which contain them (otherwise known as their parent elements). This means that if you give the body of the page certain properties (for example font and color) then every element within the page will inherit these properties- there is no need to set the font and color again for each element, such as list items or paragraphs.
You can always override the inheritance however. By assigning a property to an element, you override the inherited property.
2.6 Text t properties
2.6.1 CSS Font Families
CSS font properties define the font family, boldness, size, and the style of a text.
Difference between Serif and Sans-serif Fonts
On computer screens, sans-serif fonts are considered easier to read than serif fonts. In CSS, there are two types of font family names:
generic 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 Description
Serif
Times New Roman
Georgia
Serif fonts have small lines at the ends on some characters
Sans-serif
Arial
Verdana
"Sans" means without - these fonts do not have the lines at the ends of characters
Monospace
Courier New
Lucida Console
All monospace characters have the same width Font Family
The font family of a text is set with the font-family property.The font-family property should hold several font names as a "fallback" system. If the browser does not support the first font, it tries the next font.Start with the font you want, and end with a generic family, to let the browser pick 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 font-family: "Times New Roman". More than one font family is specified in a comma separated list:
Example
p{font-family:"Times New Roman", Times, serif;}
Font Style
The font-style property is mostly used to specify italic text.
This property has three values:
normal - The text is shown normally
italic - The text is shown in italics
oblique - The text is "leaning" (oblique is very similar to italic, but less supported)
Example
p.normal {font-style:normal;}
p.italic {font-style:italic;}
p.oblique {font-style:oblique;}
Font Size
The font-size property sets the size of the text. Being able to manage the text size is important in web design. However, you should not use font size adjustments to make paragraphs look like headings, or headings look like paragraphs. Always use the proper HTML tags, like - for headings and for paragraphs. The font-size value can be an absolute or relative size.
Absolute size:
• Sets the text to a specified size
• Does not allow a user to change the text size in all browsers (bad for accessibility reasons)
Absolute size is useful when the physical size of the output is known Relative size:
• Sets the size relative to surrounding elements
• Allows a user to change the text size in browsers
• If you do not specify a font size, the default size for normal text, like paragraphs, is 16px (16px=1em).
• Set Font Size With Pixels
Setting the text size with pixels, gives you full control over the text size:
Example
h1 {font-size:40px;}
h2 {font-size:30px;}
p {font-size:14px;}
Set Font Size with Em
To avoid the resizing problem with Internet Explorer, many developers use em instead of pixels.The em size unit is recommended by the W3C.1em is equal to the current font size. The default 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=em
Example
h1 {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 Properties
The number in the "CSS" column indicates in which CSS version the property is defined (CSS1 or CSS2).
Property Description Values CSS font
Sets all the font properties in one declaration
font-style
font-variant
font-weight
font-size/line-height
font-family
caption
icon
menu
message-box
small-caption
status-bar1
inherit
font-family
Specifies the font family for text
family-name
generic-family
inherit
1
font-size
Specifies the font size of text
xx-small
x-small
small
medium
large
x-large
xx-large
smaller
larger
length
%
Inherit
1
font-style
Specifies the font style for text
normal
italic
oblique
inherit
1
font-variant
Specifies whether or not a text should be displayed in a small-caps
font
normal
small-caps
inherit
1
font-weight
Specifies the weight of a font
normal
bold
bolder
lighter
100
200
300
400
500
600
700
800
900
1
inherit
Text Formatting and color
All CSS Text Properties
The number in the "CSS" column indicates in which CSS version the property is defined
(CSS1 or CSS2).
Property Description Values CSS color Sets the color of a text color 1 direction Sets the text direction
ltr
rtl
2
line-height Sets the distance between lines
normal
number
length
%
1
letter-spacing Increase or decrease the space between characters
normal
length
1
text-align Aligns the text in an element
left
right
center
justify
1
text-decoration Adds decoration to text
none
underline
overline
line-through
blink
1
text-indent Indents the first line of text in an element
length
%
1
text-shadow none
color
length
text-transform Controls the letters in an element none
capitalize
uppercase
lowercase
1
unicode-bidi
normal
embed
bidi-override
2
vertical-align Sets the vertical alignment of an element baseline
sub
super
top
text-top
middle
bottom
text-bottom
length
%
1
white-space Sets how white space inside an element is handled
normal
pre
nowrap
1 word-spacing Increase or decrease the space between words
normal
length
1
2.7 The CSS Box Model
BLOCK DIAGRAM
• All HTML elements can be considered as boxes. In CSS, the term "box model" is used when talking about design and layout.
• The CSS box model is essentially a box that wraps around HTML elements, and it consists of: margins, borders, padding, and the actual content.
• The box model allows us to place a border around elements and space elements in relation to other 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 is completely transparent
Border - A border that goes around the padding and content. The border is affected by the background color of the box
Padding - Clears an area around the content. The padding is affected by the background color of the box.
Content - The content of the box, where text and images appear In order to set the width and height of an element correctly in all browsers, you need to know how the box model works.
Width and Height of an Element Important: When you specify the width and height properties of an element with CSS,
You are just setting the width and height of the content area. To know the full size of the element, you must also add the padding, border and margin.
The total width of the element in the example below is 300px:
width:250px;
padding:10px;
border:5px solid gray;
margin:10px;
Let's do the math:
250px (width)
+ 20px (left and right padding)
+ 10px (left and right border)
+ 20px (left and right margin)
= 300px
Imagine that you only had 250px of space. Let's make an element with a total width of 250px:
Example
width:220px;
padding:10px;
border:5px solid gray;
margin: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 + left margin + right margin
The total height of an element should always be calculated like this:
Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin
Example
div.ex
{
width:220px;
padding:10px;
border:5px solid gray;
margin:0px;
}
CSS Background
CSS background properties are used to define the background effects of an element.
CSS properties used for background effects:
background-color
background-image
background-repeat
background-attachment
background-position
Background Color
The background-color property specifies the background color of an element. The background color of a page is defined in the body selector:
Example
body {background-color:#b0c4de;}
The background color can be specified by:
name - a color name, like "red"
RGB - an RGB value, like "rgb(255,0,0)"
Hex - a hex value, like "#ff0000"
Background Image
The background-image property specifies an image to use as the background of an element. By default, the image is repeated so it covers the entire element.
The background image for a page can be set like this:
Example
body {background-image:url('paper.gif');}
Below is an example of a bad combination of text and background image. The text is almost not readable:
Background Image - Repeat Horizontally or Vertically
By default, the background-image property repeats an image both horizontally and vertically.
Some images should be repeated only horizontally or vertically, or they will look strange, like this:
Example
body
{
background-image:url('gradient2.png');
}
If the image is repeated only horizontally (repeat-x), the background will look better:
Example
body
{
background-image:url('gradient2.png');
background-repeat:repeat-x;
}
Background Image - Set position and no-repeat
When 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:
Example
body
{
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. We want to change the position of the image, so that it does not disturb the text too much. The position of the image is specified by the background-position property:
Example
body
{
background-image:url('img_tree.png');
background-repeat:no-repeat;
background-position:right top;
}
Background - Shorthand property
As you can see from the examples above, there are many properties to consider when dealing with backgrounds. To shorten the code, it is also possible to specify all the properties in one single property. This is called 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-color
background-image
background-repeat
background-attachment
background-position
It does not matter if one of the property values are missing, as long as the ones that are present are in this order. This example uses more advanced CSS. Take a look:
Advanced example
All CSS Background Properties
The number in the "CSS" column indicates in which CSS version the property is defined
(CSS1 or CSS2).
Property Description Values CSS background
Sets all the background properties in one declaration
background-color
background-image
background-repeat
background-attachment
background-position
inherit
background-attachment
Sets whether a background image is fixed or scrolls with the rest of the page
scroll
fixed
inherit
1
background-color
Sets the background color of an element
color-rgb
color-hex
color-name
transparent
inherit
1
background-image
Sets the background image for an element
url(URL)
none
inherit
1
background-position
Sets the starting position of a background image
left top
left center
left bottom
right top
right center
right bottom
center top
center center
center bottom
x% y%
xpos ypos
inherit
1
background-repeat
Sets if/how a background image will
be repeated
repeat
repeat-x
repeat-y
no-repeat
inherit
1
2.8 NORMAL FLOW BOX LAYOUT
Understanding the box model is critical to developing web pages that don't rely on tables for layout. In the early days of writing HTML, before the advent of CSS, using tables was the only way to have discreet content in separate boxes on a page. But tables were originally conceived to display tabular information. With the advent of CSS floating and positioning, there is no longer a need to use tables for layout, though many years later many, if not most, sites are still using tables in this manner. The box model, as defined by the W3C "describes the rectangular boxes that are generated for elements in the document tree and laid out according to the visual formatting model". Don't be confused by the term "boxes". They need not appear as square boxes on the page. The term simply refers to discreet containers for content. In fact, every element in a document is considered to be a rectangular box.
Padding, Borders, Margins
Padding immediately surrounds the content, between content and borders. A margin is the space outside of the borders. If there are no borders both padding and margin behave in roughly the same way, except that you can have negative margins, while you cannot have negative padding. Also padding does not collapse like margins. See below for the section on collapsing margins.
The picture on the right illustrates padding, borders, and margins. The content area does not really have a border. The line around the content merely indicates the limits of the actual content.
Traditional vs. W3C Box Models
So how do you declare these properties in your CSS, and how do you set the width of a box?
That depends on the box model. There are actually two box models. The traditional box model is supported by IE5.5 and previous versions of IE, and any version of IE in quirks mode. It states that the width of a box is the combined width of the content, its padding and its borders. Imagine a literal box that you can hold. The car board exterior is the border. We don't care about the content inside of the box. It may fill up the box entirely or have space around it. If it has space around it, that is its padding, which sits between the content and the exterior (border) of the box.
But according to this model, it does not matter what the actual content width is. The width of the box is what matters. Using the traditional model let's 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:
The math from left to right would be:menu left padding + menu content + menu right padding + menu border + main left padding + main content + main right padding (or in pixels) 6 + 187 + 6 + 1 + 6 + 548 + 6 = 760.
Margin Collapse
Vertical margins collapse when they meet. Though it may seem like a strange thing, if you have assigned top and bottom margins to the P element of, say, 10px each, you will not have 20px of margin between paragraphs, but rather 10px. This is considered to be desirable and expected behavior, 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 two values. Margin collapse does not occur when either box is floated, when one element uses the overflow property set to any value other than "visible", with absolutely positioned elements, with elements whose display property is set to "inline-block", or if the child element is cleared. You can override margin collapse also by adding a border, of the same color as the background if you want it unnoticed, or by using padding instead of margins. Eric Meyer has a nice description of collapsing margins. In sum, margin collapse is meant to prevent certain design problems, and yet is not difficult to override.
Display Property
This is one of the most useful properties. The complete list of values is in the appendix of this document, but the most useful ones follow.
block
Block display provides behavior similar to a default DIV element. A line break occurs at the close of the tag. Elements that are block by default are DIV, P, BLOCKQUOTE, H1 through H6, UL, OL, LI, ADDRESS, etc. Block elements accept width, height, top and bottom margins, and top and bottom padding. A block element constitutes a separate block box.
Inline
Inline 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, top and bottom padding, and top and bottom margins, which makes good sense, since they are used for part 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. Lineheight can then be used to approximate height. If you need to apply width, height or other block properties to an inline element, consider assigning the element block display and/or floating it. Block display, of course, will force the element on to a separate line (unless the element is floated). Alternatively you can assign the inline-block value to make an inline element take block properties (see below).
none
Display set to none sets the element to invisible similar to the hidden value of the visibility property (see below). However, unlike the visibility property, this value takes up no space on the page. This is very useful for DHTML hidden tools and for other instances when you need items to 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 be included in the loop. (For more on generated content, see below.) Display set to none will also be hidden from most screen readers. If you are trying to make something readable only for those with sight disabilities, use an off-screen class like this:
.offScreen {position: absolute; left: -10000px; top: auto; width: 1px;
height: 1px; overflow: hidden;}
inline-block
This value causes the element to generate a block element box that will be flowed with surrounding content as if it were a single inline box. It lets you place a block inline with the content of its parent element. It also allows you to assign properties associated with block display, such as width and height to an element that naturally takes inline display. This property is also used to trigger has Layout in IE6, which is a difficult concept, but briefly means making IE6 assume CSS certain properties.
run-in
This display mode causes the element to appear as an inline element at the start of the block immediately following it. If there is no block following a run-in element, it is displayed as a normal block instead. Currently, there seems to be no browser support for this value except for IE8, but here is an example of how it is coded, and how it should look.
Here is some run-in text on this line.
But here is a block that follows it, so they are
conjoined.
Let's see if it works. Here is some run-in text on this line. But here is a block that follows it, so are they conjoined? Well, apparently not in Firefox. Oh well.
list-item
Unordered lists are traditionally used to list bulleted items vertically. But you can assign bullets to 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 list item, but at the very least it's helpful that CSS is so flexible. However you use these values, ensure that your HTML is meaningful irrespective of your CSS. Because there is a wide variety of display values, HTML tags can be made to display in a variety of ways, some counter to the nature of the element. Care should be taken to maintain the implicit content of elements. Should you, for example, give a P element inline display? You can, but use caution. It is more likely that you will set the inline value for the DIV element. This seems to be more acceptable in that the DIV element simply provides separate treatment for content, while a paragraph is visually demarcated from other elements.
2.9 Beyond the Normal Flow
Positioning
The CSS positioning properties allow you to position an element. It can also place an element behind another, and specify what should happen when an element's content is too big. Elements can be positioned using the top, bottom, left, and right properties. However, these properties will not work unless the position property is set first. They also work differently depending on the positioning method. There are four different positioning methods.
Static Positioning
HTML elements are positioned static by default. A static positioned element is always
Positioned according to the normal flow of the page. Static positioned elements are not affected by the top, bottom, left, and right properties.
Fixed Positioning
An element with fixed position is positioned relative to the browser window. It will not move even if the window is scrolled:
Example
p.pos_fixed
{
position:fixed;
top:30px;
right:5px;
}
Note: Internet Explorer supports the fixed value only if a !DOCTYPE is specified. Fixed positioned elements are removed from the normal flow. The document and other elements behave like the fixed positioned element does not exist. Fixed positioned elements can overlap other elements.
Relative Positioning
A relative positioned element is positioned relative to its normal position.
Example
h2.pos_left
{
position:relative;
left:-20px;
}
h2.pos_right
{
position:relative;
left:20px;
}
The content of a relatively positioned elements can be moved and overlap other elements, but the reserved space for the element is still preserved in the normal flow.
Example
h2.pos_top
{
position:relative;
top:-50px;
}
Relatively positioned elements are often used as container blocks for absolutely positioned elements.
Absolute Positioning
An absolute position element is positioned relative to the first parent element that has a position other than static. If no such element is found, the containing block is :
Example
h2
{
position:absolute;
left:100px;
top:150px;
}
27
Absolutely positioned elements are removed from the normal flow. The document and other elements behave like the absolutely positioned element does not exist. Absolutely
Positioned elements can overlap other elements.
Overlapping Elements
When elements are positioned outside the normal flow, they can overlap other elements. The zindex property specifies the stack order of an element (which element should be placed in front of, or behind, the others).An element can have a positive or negative stack order:
Example
img
{
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 stack order.
All CSS Positioning Properties
The number in the "CSS" column indicates in which CSS version the property is defined (CSS1 or CSS2).
Property Description Values CSS bottom, Sets the bottom margin edge for a positioned box
auto
length
%
inherit
2
clip Clips an absolutely positioned element
shape
auto
inherit
2
cursor Specifies the type of cursor to be displayed
url
auto
crosshair
default
pointer
move
2
28
e-resize
ne-resize
nw-resize
n-resize
se-resize
sw-resize
s-resize
w-resize
text
wait
help
left
Sets the left margin edge for a positioned
box
auto
length
%
inherit
2
overflow
Specifies what happens if content overflows an element's box
auto
hidden
scroll
visible
inherit
2
position
Specifies the type of positioning for an
element
absolute
fixed
relative
static
inherit
2
right
Sets the right margin edge for a positioned
box
auto
length
%
inherit
2
top
Sets the top margin edge for a positioned
box
auto
length
%
inherit
2
z-index Sets the stack order of an element
number
auto
inherit
2
29
What is CSS Float?
• With CSS float, an element can be pushed to the left or right, allowing other elements to wrap around it.
• Float is very often used for images, but it is also useful when working with layouts.
How Elements Float
Elements are floated horizontally, this means that an element can only be floated left or
right, not up or down. A floated element will move as far to the left or right as it can. Usually this means all the way to the left or right of the containing element. The elements after the floating element will flow around it. The elements before the floating element will not be affected.
If an image is floated to the right, a following text flows around it, to the left:
Example
img
{
float:right;
}
Floating Elements Next to Each Other
If you place several floating elements after each other, they will float next to each other if there is room. Here we have made an image gallery using the float property:
Example
.thumbnail
{
float:left;
width:110px;
height:90px;
margin:5px; }
2.10 SOME OTHER USEFUL STYLE PROPERTIES
CSS Lists
The CSS list properties allow you to:
• Set different list item markers for ordered lists 30
• Set different list item markers for unordered lists
• Set an image as the list item marker
List
In HTML, there are two types of lists:
unordered lists - the list items are marked with bullets
ordered lists - the list items are marked with numbers or letters
With CSS, lists can be styled further, and images can be used as the list item marker.
Different List Item Markers
The type of list item marker is specified with the list-style-type property:
Example
ul.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 Lists
Value Description none No marker disc Default. The marker is a filled circle circle The marker is a circle square. The marker is a square
Values for Ordered Lists
Value Description armenian
The marker is traditional Armenian numbering decimal. The marker is a number 31 decimal-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.)
lower-alpha
The marker is lower-alpha (a, b, c, d, e, etc.)
lower-greek
The marker is lower-greek (alpha, beta, gamma, etc.)
lower-latin
The marker is lower-latin (a, b, c, d, e, etc.)
lower-roman
The marker is lower-roman (i, ii, iii, iv, v, etc.)
upper-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.)
upper-roman
The marker is upper-roman (I, II, III, IV, V, etc.)
Note: No versions of Internet Explorer (including IE8) support the property values "decimalleadingzero", "lower-greek", "lower-latin", "upper-latin", "armenian", or "georgian" UNLESS a DOCTYPE is specified!
An Image as The List Item Marker
To specify an image as the list item marker, use the list-style-image property:
Example
ul
{
list-style-image: url('sqpurple.gif');
}
The example above does not display equally in all browsers. IE and Opera will display the image-marker a little bit higher than Firefox, Chrome, and Safari. If you want the image marker to be placed equally in all browsers, a cross browser solution is explained below. Cross browser Solution
The following example displays the image-marker equally in all browsers:
Example
ul
{
list-style-type: none;
32
padding: 0px;
margin: 0px;
}
li
{
background-image: url(sqpurple.gif);
background-repeat: no-repeat;
background-position: 0px 5px;
padding-left: 14px;
}
Example explained:
For ul:
• Set the list-style-type to none to remove the list item marker
• Set both padding and margin to 0px (for cross-browser compatibility)
For li:
• Set the URL of the image, and show it only once (no-repeat)
• Position the image where you want it (left 0px and down 5px)
• Position the text in the list with padding-left
List - Shorthand property
It is also possible to specify all the list properties in one, single property. This is called a
shorthand 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:
list-style-type
list-style-position (for a description, see the CSS properties table below)
list-style-image
It does not matter if one of the values above are missing, as long as the rest are in the specified order.
33
All CSS List Properties
The number in the "CSS" column indicates in which CSS version the property is defined (CSS1 or CSS2).
Property Description Values CSS
list-style Sets all the properties for a list in one declaration
list-style-type
list-style-position
list-style-image
inherit
1
list-style-image Specifies an image as the list-item marker URL
none
inherit
1
list-style-position
Specifies if the list-item markers should appear inside or outside the content flow
inside
outside
inherit
1
list-style-type Specifies the type of list-item marker
none
disc
circle
square
decimal
decimal-leading-zero
armenian
georgian
lower-alpha
upper-alpha
lower-greek
lower-latin
upper-latin
lower-roman
upper-roman
inherit
1
CSS Tables
The look of an HTML table can be greatly improved with CSS:
|Company |Contact |Country |
|Alfreds |Futterkiste Maria Anders |Germany |
|Berglunds |snabbköp Christina Berglund |Sweden |
|Centro commercial |Moctezuma Francisco Chang |Mexico |
|Ernst Handel |Roland Mendel |Austria |
|Island Trading |Helen Bennett |UK |
|Königlich Essen |Philip Cramer |Germany |
|Laughing Bacchus |Winecellars Yoshi Tannamuri |Canada |
|Magazzini Alimentari |Riuniti Giovanni Rovelli |Italy |
|Paris spécialités |Marie Bertrand |France |
|The Big Cheese Liz |Nixon |USA |
|Vaffeljernet Palle |Ibsen |Denmark |
Table Borders
To specify table borders in CSS, use the border property. The example below specifies a black border for table, th, and td elements: Notice that the table in the example above has double borders. This is because both the table, th, and td elements have separate borders.
Example
table, th, td
{
border: 1px solid black;
}
To display a single border for the table, use the border-collapse property.
Collapse Borders
The border-collapse property sets whether the table borders are collapsed into a single border or separated:
table
{
border-collapse:collapse;
}
table,th, td
{
border: 1px solid black;
}
Table Width and Height Width and height of a table is defined by the width and height properties. The example below sets the width of the table to 100%, and the height of the th elements to 50px:
table
{
width:100%;
}
th
{
height:50px;
}
CSS CURSORS
Although the cursors will not have the customized look in other browsers it usually doesn't ruin anything. These browsers will simply show the normal arrow-cursor which would be same case as if you refrained from customizing cursors at all. So unless the page really doesn't work without the customized cursor there shouldn't be technical reasons for choosing not to. However there might be other reasons for thinking twice before adding custom cursor to your pages. Many users are easily confused or irritated when a site breaks the standard user interface.
Adding A Customized Cursor
The syntax for a customized cursor is this:
(Position the mouse over each link to see the effect)
Selector {cursor:value}
For example:
.xlink {cursor:crosshair}
.hlink{cursor:help}
CROSS LINK
HELP LINK
2.11 CASE STUDY
Case Study: Revamping an Existing Site April 27, 2010 32 Comments .
Jacques Soudan, a client and friend I met through Divito Design, sent me an email with a guest post about a 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 JavaScript library to rebuild an outdated site – somehow you helped me with it, so in return I share my work, hoping it can be of future use. Thank you!
The website we are talking about was build back in 2001. As you would understand we are talking about a heavily-aged website that had the following ‘problems’ or difficulties: using some CSS, but mainly tables the menu is a separate JS file: easy to maintain, but it doesn’t look too good a few years ago I added the rounded corners (using JavaScript) and the red backdrop/border, but that doesn’t look too flashy either the source is not W3C compliant (outdated code like – instead of the current ) 37 the 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 supported in Firefox, the banner is not centered (in IE it is…..) and looks like this (also in a table – probably easy to fix, but never got to it):
For a website in the modern internet world, that is not acceptable. For this reason, I compiled a list of features I would like to have on the modern, good looking website. Site Features we Need W3C compliant code CSS and HTML in separated files browser
Compatibility rounded corners & drop shadow 1 central menu file JavaScript support (instead of using several separate scripts that (might) interfere) structured design (layout without tables).
Where to Start?
Last year I read this very useful article about building HTML/CSS sites using a template. This template has a grid CSS layout and the jQuery framework build in. I had seen those before, but was not yet using them in combination with WordPress. I also found this site for dropshadow & rounded corners. As I wanted to avoid too many jQuery plugins, I didn’t use jQuery for the round corners. So far my experience is that jQuery rounded corners can interfere with 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 it uses several , it messed up the Blueprint classes, it didn’t display properly ‘underneath’ the header images etc. The typical pain when it comes to CSS and different techniques in different browsers.
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 display the columns for design purposes, which you can switch off when you go live. But then, if you can remove that backdrop, why not adding your own???? Using my own image I had created for the initial technique, but thought useless now, it worked flawlessly! 38
Here is what I did – in the Blueprint folder, there is a screen.css – just add one line and comment the gridline – that’s all!
In your container-DIV, just add the ‘showgrid’-class: (you need that anyway, if you want to display the Blueprint-columns):
The grid.png is repeated both horizontally & vertically, but my one large image is not, so it fits perfectly – I stretched it to 1600px, as the backdrop is hardly ‘repeatable’: it is a scanned letter head paper with a unique texture – using only a small slice/strip and repeating that would make it look unnatural. And I use a footer-image – including it in php, it neatly fits underneath the length of the actual content – not the full background image of 1600px – it ‘stretches’ to the maximum height, but resizes to the needed height.
• I wanted to use this menu for this website. One problem though: it has no single menu file (eg. menu.php)
• You can add to your website. After building that menu.php file myself, the jQuery menu worked perfectly.
• When I created the header.php and footer.php files and included in the website using PHP, they are easily updated in those 100 different pages. Depending on the page of the website, I can now include different images via one page. Pretty efficient.
The Template
With all this now in place, this is how the code looks like (this is what I will use as the
‘page-template’ (there is some test copy in, to show in Blueprint columns – all the ‘body-text’ for an individual page is placed within the (both -classes, in blue) – everything remains in place, no fluid/stretched text (in different browsers).
<
39
Main content
Put your main text here (17 columns wide).
Sidebar
Some sidebar on the right (5 columns wide).
Blueprint-grid enabled:
40
And this is how it looks like (pictures not optimized yet):
2.12. CLIENT SIDE PROGRAMMING: JAVA SCRIPT
Introduction
JavaScript is most commonly used as a client side scripting language. This means that JavaScript code is written into an HTML page. When a user requests an HTML page with JavaScript in it, the script is sent to the browser and it's up to the browser to do something with it. JavaScript can be used in other contexts than a Web browser. Netscape created server-side JavaScript as a CGI language that can do roughly the same as Perl or ASP. There is no reason why JavaScript couldn’t be used to write real, complex programs. However, this site exclusively deals with the use of JavaScript in web browsers. I can also recommend Jeremy Keith, DOM Scripting:
Web Design with JavaScript and the Document Object Model, 1st edition, Friends of Ed,
2005. This, too, is a book that doesn't delve too deeply into technology, but gives non-programmers such as graphic designers/CSS wizards an excellent overview of the most common uses of JavaScript - as well as the most common problems.
History and Versions of The JavaScript language JavaScript is not a programming language in strict sense. Instead, it is a scripting language because it uses the browser to do the dirty work. If you command an image to be replaced by another one, JavaScript tells the browser to go do it. Because the browser actually does the work, you only need to pull some strings by writing some relatively easy lines of code. That’s what makes JavaScript an easy language to start with. But don’t be fooled by some beginner’s luck: JavaScript can be pretty difficult, too. First of all, despite its simple appearance it is a full fledged programming language: it is possible to write quite complex programs in JavaScript. This is rarely necessary when dealing with web pages, but, it is possible. This means that there are some complex programming structures that you’ll only understand after protracted studies.
Secondly, and more importantly, there are the browser differences. Though modern web browsers all support JavaScript, there is no sacred law that says they should support exactly the same JavaScript.
JavaScript versions
There have been several formal versions of JavaScript.
1.0: Netscape 2
1.1: Netscape 3 and Explorer 3 (the latter has bad JavaScript support, regardless of its version)
1.2: Early Version 4 browsers
1.3: Later Version 4 browsers and Version 5 browsers
1.4: Not used in browsers, only on Netscape servers
1.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 that method would only be supported by browsers understanding JavaScript
1.something.
The higher the version number, the more nifty features the browser would support.
Unfortunately Netscape 3 does not recognize the language attribute in a JavaScript include tag. So if you do:
Netscape 3 loads the script, even though it doesn't support JavaScript 1.3, and shows a lot of error messages. Too bad.
2.13 INTRODUCTION TO JAVA SCRIPT
What is JavaScript?
• JavaScript was designed to add interactivity to HTML pages
• JavaScript is a scripting language
• A scripting language is a lightweight programming language
• A JavaScript consists of lines of executable computer code
• A JavaScript is usually embedded directly into HTML pages
• JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
• Everyone can use JavaScript without purchasing a license
• Are Java and JavaScript the Same?
NO!
Java and JavaScript are two completely different languages in both concept and design!
Java (developed by Sun Microsystems) is a powerful and much more complex programming language – in the same category as C and C++.
What can a JavaScript Do?
JavaScript gives HTML designers a programming tool - HTML authors are normally not
Programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:
document.write("" + name + "") can write a variable text into an HTML page
JavaScript can react to events - A JavaScript can be set to execute when something happens, like 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 content of an HTML element
JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer.
2.14 JAVASCRIPT IN PERSPECTIVE
Examples
Write text with Javascript
The example demonstrates how to use JavaSript to write text on a web page.44
Write HTML with Javascript
The example demonstrates how to use JavaScript to write HTML tags on a web page. 45
2.15 BASIC SYNTAX
How to Put a JavaScript Into an HTML Page
document.write("Hello World!");
Hello World!
Example Explained
To insert a JavaScript into an HTML page, we use the tag. Inside the tag we use the "type=" attribute to define the scripting language. So, the and tells where the JavaScript starts and ends:
...
The word document. Write is a standard JavaScript command for writing output to a page. By entering the document. Write command between the and tags, the browser will recognize it as a JavaScript command and execute the code line. In this case the browser will write Hello World! to the page:
document.write("Hello World!");
HTML Comments to Handle Simple Browsers
Browsers that do not support JavaScript will display JavaScript as page content. 46
To prevent them from doing this, and as a part of the JavaScript standard, the HTML
comment tag can be used to "hide" the JavaScript. Just add an HTML comment tag (end of comment) after the last JavaScript statement.
The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents JavaScript from executing the --> tag. JavaScripts in the body section will be executed WHILE the page loads. JavaScripts in the head section will be executed when CALLED.
Examples
Head section
Scripts that contain functions go in the head section of the document. Then we can be sure that the script is loaded before the function is called.
2.16 JAVASCRIPT VARIABLES AND DATATYPES
As with algebra, JavaScript variables are used to hold values or expressions. A variable can have a short name, like x, or a more describing name like length. A JavaScript variable can also hold a text value like in 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 character
NOTE: Because JavaScript is case-sensitive, variable names are case-sensitive.
Example
A variable's value can change during the execution of a script. You can refer to a variable by its name to display or change its value.
• Declaring (Creating) JavaScript Variables
• Creating variables in JavaScript is most often referred to as "declaring" variables.
You can declare JavaScript variables with the var statement:
var x;
var carname;
After the declaration shown above, the variables has no values, but you can assign values to the variables while you declare them:
var x=5;
var carname="Volvo";
Assigning Values to JavaScript Variables
You 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 the variable is on the right.
• After the execution of the statements above, the variable x will hold the value 5, and carname will hold the value Volvo.
Assigning Values to Undeclared JavaScript Variables
If you assign values to variables that has not yet been declared, the variables will automatically be declared. These statements:
x=5;
carname="Volvo";
have the same effect as:
var x=5;
var carname="Volvo";
Redeclaring JavaScript Variables
• If you redeclare a JavaScript variable, it will not lose its original value.
var x=5;
var x;
• After the execution of the statements above, the variable x will still have the value of 5.
• The value of x is not reset (or cleared) when you redeclare it.
DataTypes
Numbers - are values that can be processed and calculated. You don't enclose them in
Quotation marks. The numbers can be either positive or negative.
Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript uses the string literally; it doesn't process it. You'll use strings for text you want displayed or values you want passed along.
Boolean (true/false) - lets you evaluate whether a condition meets or does not meet specified criteria.
Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number, whereas null is the absence of any value.
Data Types
TYPE EXAMPLE
Numbers Any number, such as 17, 21, or 54e7
Strings "Greetings!" or "Fun"
Boolean Either true or false
Null A special keyword for exactly that – the null value (that is, nothing)
Integers
In JavaScript, you can express integers in 3 different Bases:
base 10,
base 8 (octal), and
base 16 (hexadecimal).
Base 8 numbers can have digits only up to 7, so a decimal value of 18 would be an octal value of 22.
Similarly, hexadecimal allows digits up to F, where A is equivalent to decimal 10 and F
is 15. So, a decimal value of 18 would be 12 in hexadecimal notation.
Converting Numbers to Different Bases Table
In order to distinguish between these three bases, JavaScript uses the following notation.
Specifying bases in JavaScript
NUMBER SYSTEM NOTATION
Decimal (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 Values
Floating point values can include a fractional component. A floating-point literal includes
a decimal integer plus either a decimal point and a fraction expressed as another decimal number or an expression indicator and a type suffix
7.2945
-34.2
2e3 means 2 x 103 => 2000
2E-3 means 2 x 10-3 => .002
Floating point literals must, at a minimum, include a decimal integer and either the decimal point or the exponent indicator ("e" or "E"). As with integers, floating point values can be positive or negative.
Strings
Technically, a string literal contains zero or more characters enclosed, as you know, in single or double quotes:
"Hello!"
‘245’
"" // This example is called the empty string.
NOTE: the empty string is distinct from the null value in JavaScript.
NOTE: Strings are different from other data types in JavaScript. Strings are actually Objects. This will be covered later on.
Boolean
A Boolean value is either true or false.
Note: Unlike Java, C and other languages, in JavaScript Boolean values can only be represented with true and false. Values of 1 and 0 are not considered Boolean values in JavaScript.
Null Value
The null value is a special value in JavaScript. The null value represents just that – Nothing. If you try to reference a variable that isn’t defined and therefore has no value, the value returned is the null value. Likewise, with the prompt() dialog box, if the user selects the Cancel button, a null is returned. (example)
NaN (Not a Number)
In addition to these values, some functions return a special value called NaN – which means that the value is not a number, parseInt() and parseFloat() are an examples of functions that return NaN when the argument passed to them cannot be evaluated to a number.
Creating Values
In order to make working with data types useful, you need ways to store values for later use. This is where variables come in.
JavaScript Statements
• A JavaScript statement is a command to the browser. The purpose of the command is to tell the browser what 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 people think this is a good programming practice, and most often you will see this in JavaScript examples on the web.
• The semicolon is optional (according to the JavaScript standard), and the browser is supposed to interpret the end of the line as the end of the statement. Because of this you will often see examples without the semicolon at the end.
JavaScript Code
JavaScript code (or just JavaScript) is a sequence of JavaScript statements. Each 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:
document.write("This is a header");
document.write("This is a paragraph");
document.write("This is another paragraph");
JavaScript Blocks
• JavaScript 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:
{
document.write("This is a header");
document.write("This is a paragraph");
document.write("This is another paragraph");
}
The example above is not very useful. It just demonstrates the use of a block. Normally a block is used to group statements together in a function or in a condition (where a group of statements should be executed, if a condition is met).
You will learn more about functions and conditions in later chapters.
Where to Put the JavaScript
• JavaScripts in a page will be executed immediately while the page loads into the browser.
• This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event.
•
Scripts in the head section:
Scripts to be executed when they are called, or when an event is triggered, go in the head section. When you place a script in the head section, you will ensure that the script is loaded before anyone uses it.
....
Scripts in the body section: Scripts to be executed when the page loads go in the body section. When you place a script in the body section it generates the content of the page.
....
Scripts in both the body and the head section: You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head section.
....
....
Using an External JavaScript
• Sometimes you might want to run the same JavaScript on several pages, without having to write the same script on every page.
• To simplify this, you can write a JavaScript in an external file. Save the external JavaScript file with a .js file extension.
Note: The external script cannot contain the tag!
To use the external script, point to the .js file in the "src" attribute of the tag:
2.17 JAVASCRIPT STATEMENTS
• A JavaScript statement is a command to the browser. The purpose of the command is to tell the browser, what to do.
• write("Hello Dolly");
• It is normal to add a semicolon at the end of each executable statement. Most people think this is a good programming practice, and most often you will see this in JavaScript examples on the web.
• The semicolon is optional (according to the JavaScript standard), and the browser is supposed to interpret the end of the line as the end of the statement. Because of this you will often see examples without the semicolon at the end.
•
Note: Using semicolons makes it possible to write multiple statements on one line.
JavaScript Code
• JavaScript code (or just JavaScript) is a sequence This JavaScript statement tells the browser to write "Hello Dolly" to the web page: document. of JavaScript statements. Each 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:
document.write("This is a header");
document.write("This is a paragraph");
document.write("This is another paragraph");
2.18 JAVASCRIPT OPERATORS
= is used to assign values.
+ is used to add values.
The assignment operator = is used to assign values to JavaScript variables.
The arithmetic operator + is used to add values together.
y=5;
z=2;
x=y+z;
The value of x, after the execution of the statements above is 7.
JavaScript Arithmetic Operators
Arithmetic 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
JavaScript Assignment Operators
• Assignment 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=15
56
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0
The + Operator Used on Strings
The + operator can also be used to add string variables or text values together.
To add two or more string variables together, use the + operator.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
• After the execution of the statements above, the variable txt3 contains "What a very nice day".
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:
"What a very nice day"
Adding Strings and Numbers
The rule is: If you add a number and a string, the result will be a string!
Example
x=5+5;
document.write(x);
x="5"+"5";
document.write(x);
x=5+"5";
document.write(x);
x="5"+5;
document.write(x);
• If you add a number and a string, the result will be a string.
• Comparison and Logical operators are used to test for true or false.
Comparison Operators
• Comparison operators are used in logical statements to determine equality or difference between variables or 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 true
x==="5" is false
!= is not equal x!=8 is true
> is greater than x>8 is false
< is less than x= is greater than or equal to x>=8 is false
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- wordpress passing data between pages
- wordpress business templates
- wordpress rss feed not working
- wordpress jquery is not defined
- create wordpress blog
- wordpress roles editor
- wordpress full rss feed
- wordpress rss feed settings
- wordpress rss feed plugin
- wordpress display rss feed
- wordpress rss feed link
- wordpress rss feed to post