0 valutazioniIl 0% ha trovato utile questo documento (0 voti)
48 visualizzazioni66 pagine
CSS is a breakthrough in Web design because it allows developers to control the style and layout of multiple Web pages all at once. Style sheets define how HTML elements are displayed, just like the font tag and the color attribute in HTML 3.2. External Style Sheets enable you to change the appearance and layout of all the pages in your Web, just by editing a single CSS document.
CSS is a breakthrough in Web design because it allows developers to control the style and layout of multiple Web pages all at once. Style sheets define how HTML elements are displayed, just like the font tag and the color attribute in HTML 3.2. External Style Sheets enable you to change the appearance and layout of all the pages in your Web, just by editing a single CSS document.
Copyright:
Attribution Non-Commercial (BY-NC)
Formati disponibili
Scarica in formato PDF, TXT o leggi online su Scribd
CSS is a breakthrough in Web design because it allows developers to control the style and layout of multiple Web pages all at once. Style sheets define how HTML elements are displayed, just like the font tag and the color attribute in HTML 3.2. External Style Sheets enable you to change the appearance and layout of all the pages in your Web, just by editing a single CSS document.
Copyright:
Attribution Non-Commercial (BY-NC)
Formati disponibili
Scarica in formato PDF, TXT o leggi online su Scribd
Introduction to CSS What is CSS? CSS stands for Cascading Style Sheets Styles define how to display HTML elements Styles are normally stored in Style Sheets Styles were added to HTML 4.0 to solve a problem External Style Sheets can save you a lot of work External Style Sheets are stored in CSS files Multiple style definitions will cascade into one
Styles Solve a Common Problem HTML tags were originally designed to define the content of a document. They were supposed to say "This is a header", "This is a paragraph", "This is a table", by using tags like <h1>, <p>, <table>, and so on. The layout of the document was supposed to be taken care of by the browser, without using any formatting tags. As the two major browsers - Netscape and Internet Explorer - continued to add new HTML tags and attributes (like the <font> tag and the color attribute) to the original HTML specification, it became more and more difficult to create Web sites where the content of HTML documents was clearly separated from the document's presentation layout. To solve this problem, the World Wide Web Consortium (W3C) - the non profit, standard setting consortium responsible for standardizing HTML - created STYLES in addition to HTML 4.0. Both Netscape 4.0 and Internet Explorer 4.0 support Cascading Style Sheets.
Style Sheets Can Save a Lot of Work Styles in HTML 4.0 define how HTML elements are displayed, just like the font tag and the color attribute in HTML 3.2. Styles are normally saved in files external to your HTML documents. External style sheets enable you to change the appearance and layout of all the pages in your Web, just by editing a single CSS document. If you have ever tried to change the font or color of all the headings in all your Web pages, you will understand how CSS can save you a lot of work. CSS is a breakthrough in Web design because it allows developers to control the style and layout of multiple Web pages all at once. As a Web developer you can define a style for each HTML element and apply it to as many Web pages as you want. To make a global change, simply change the style, and all elements in the Web are updated automatically.
Multiple Styles Will Cascade Into One Style Sheets allow style information to be specified in many ways. Styles can be specified inside a single HTML element, inside the <head> element of an HTML page, or in an external CSS file. Even multiple external Style Sheets can be referenced inside a single HTML document. Cascading Order What style will be used when there is more than one style specified for an HTML element?
Generally speaking we can say that all the styles will "cascade" into a new "virtual" Style Sheet by the following rules, where number four has the highest priority: 1. Browser default 2. External Style Sheet 3. Internal Style Sheet (inside the <head> tag) 4. Inline Style (inside HTML element) So, an inline style (inside an HTML element) has the highest priority, which means that it will override every style declared inside the <head> tag, in an external style sheet, and in a browser (a default value). CSS Syntax The CSS syntax is made up of three parts: a selector, a property and a value: selector {property: value} The selector is normally the HTML element/tag you wish to define, the property is the attribute you wish to change, and each property can take a value. The property and value are separated by a colon and surrounded by curly braces: body {color: black} If the value is multiple words, put quotes around the value: p {font-family: "sans serif"} Note: If you wish to specify more than one property, you should separate each property with a semi-colon. The example below shows how to define a center aligned paragraph, with a red text color: p {text-align:center;color:red} To make the style definitions more readable, you can describe one property on each line, like this: p { text-align: center; color: black; font-family: arial }
Grouping You can group selectors. Separate each selector with a comma. In the example below we have grouped all the header elements. Each header element will be green: h1,h2,h3,h4,h5,h6 { color: green }
The class Selector With the class selector you can define different styles for the same type of HTML element. Say that you would like to have two types of paragraphs in your document: one right-aligned paragraph, and one center-aligned paragraph. Here is how you can do it with styles: p.right {text-align: right} p.center {text-align: center} You have to use the class attribute in your HTML document: <p class="right"> This paragraph will be right-aligned. </p> <p class="center"> This paragraph will be center-aligned. </p> Note: Only one class attribute can be specified per HTML element! The example below is wrong: <p class="right" class="center"> This is a paragraph. </p> You can also omit the tag name in the selector to define a style that will be used by all HTML elements that have a certain class. In the example below, all HTML elements with class="center" will be center-aligned: .center {text-align: center} In the code below both the h1 element and the p element have class="center". This means that both elements will follow the rules in the ".center" selector: <h1 class="center"> This heading will be center-aligned </h1> <p class="center"> This paragraph will also be center-aligned. </p>
The id Selector The id selector is different from the class selector! While a class selector may apply to SEVERAL elements on a page, an id selector always applies to only ONE element. An ID attribute must be unique within the document. The style rule below will match a p element that has the id value "para1": p#para1 { text-align: center; color: red } The style rule below will match the first element that has the id value "wer345": *#wer345 {color: green} The rule above will match this h1 element: <h1 id="wer345">Some text</h1> The style rule below will match a p element that has the id value "wer345": p#wer345 {color: green} The rule above will not match this h2 element: <h2 id="wer345">Some text</h2>
CSS Comments You can insert comments in CSS to explain your code, which can help you when you edit the source code at a later date. A comment will be ignored by the browser. A CSS comment begins with "/*", and ends with "*/", like this: /* This is a comment */ p { text-align: center; /* This is another comment */ color: black; font-family: arial }
How to Insert a Style Sheet When a browser reads a style sheet, it will format the document according to it. There are three ways of inserting a style sheet: External Style Sheet An external style sheet is ideal when the style is applied to many pages. With an external style sheet, you can change the look of an entire Web site by changing one file. Each page must link to the style sheet using the <link> tag. The <link> tag goes inside the head section: <head> <link rel="stylesheet" type="text/css" href="mystyle.css" /> </head> The browser will read the style definitions from the file mystyle.css, and format the document according to it. An external style sheet can be written in any text editor. The file should not contain any html tags. Your style sheet should be saved with a .css extension. An example of a style sheet file is shown below: hr {color: sienna} p {margin-left: 20px} body {background-image: url("images/back40.gif")}
Do NOT leave spaces between the property value and the units! If you use "margin-left: 20 px" instead of "margin-left: 20px" it will only work properly in IE6 but it will not work in Mozilla or Netscape. Internal Style Sheet An internal style sheet should be used when a single document has a unique style. You define internal styles in the head section by using the <style> tag, like this: <head> <style type="text/css"> hr {color: sienna} p {margin-left: 20px} body {background-image: url("images/back40.gif")} </style> </head> The browser will now read the style definitions, and format the document according to it. Note: A browser normally ignores unknown tags. This means that an old browser that does not support styles, will ignore the <style> tag, but the content of the <style> tag will be displayed on the page. It is possible to prevent an old browser from displaying the content by hiding it in the HTML comment element: <head> <style type="text/css"> <!-- hr {color: sienna} p {margin-left: 20px} body {background-image: url("images/back40.gif")} --> </style> </head> Inline Styles An inline style loses many of the advantages of style sheets by mixing content with presentation. Use this method sparingly, such as when a style is to be applied to a single occurrence of an element. To use inline styles you use the style attribute in the relevant tag. The style attribute can contain any CSS property. The example shows how to change the color and the left margin of a paragraph: <p style="color: sienna; margin-left: 20px"> This is a paragraph </p>
Multiple Style Sheets If some properties have been set for the same selector in different style sheets, the values will be inherited from the more specific style sheet. For example, an external style sheet has these properties for the h3 selector: h3 { color: red; text-align: left; font-size: 8pt } And an internal style sheet has these properties for the h3 selector: h3 { text-align: right; font-size: 20pt } If the page with the internal style sheet also links to the external style sheet the properties for h3 will be: color: red; text-align: right; font-size: 20pt The color is inherited from the external style sheet and the text-alignment and the font-size is replaced by the internal style sheet. Examples An HTML file uses the <link> tag to link to an external style sheet: <html> <head> <link rel="stylesheet" type="text/css" href="ex2.css" /> </head>
<body>
<h1>This is a header 1</h1> <hr>
<p>You can see that the style sheet formats the text</p>
<p><a href="http://www.microsoft.com" target="_blank">This is a link</a></p>
</body> </html>
Following is ex1.css
body {background-color: tan} h1 {color:maroon; font-size:20pt} hr {color:navy} p {font-size:11pt; margin-left: 15px} a:link {color:green} a:visited {color:yellow} a:hover {color:black} a:active {color:blue}
CSS Background CSS Background properties define the background effects of an element.
The Background properties allow you to control the background color of an element, set an image as the background, repeat a background image vertically or horizontally, and position an image on a page.
Background Properties: NN: Netscape, IE: Internet Explorer, W3C: Web Standard Property Description Values NN IE W3C background A shorthand property for setting all background properties in one declaration background-color background- image background- repeat background- attachment background- position 6.0 4.0 CSS1 background- attachment Sets whether a background image is fixed or scrolls with the rest of the page scroll fixed 6.0 4.0 CSS1 background-color Sets the background color of an element color-rgb color-hex color-name transparent 4.0 4.0 CSS1 background- image Sets an image as the background url none 4.0 4.0 CSS1 background- position Sets the starting position of a background image top left top center top right center left center center center right bottom left bottom center bottom right x-% y-% x-pos y-pos 6.0 4.0 CSS1 background- repeat Sets if/how a background image will be repeated repeat repeat-x repeat-y no-repeat 4.0 4.0 CSS1
Example: <html> <head>
<style type="text/css"> body { background-image: ur l('myimage.gif'); background-repeat: no-repeat; background-attachment: fixed } h1 {background-color: #00ff00} h2 {background-color: transparent} p {background-color: rgb(250,0,255)} </style>
</head>
<body>
<h1>This is header 1</h1> <h2>This is header 2</h2> <p>This is a paragraph</p>
</body> </html>
CSS Text Text properties allow you to control the appearance of text. It is possible to change the color of a text, increase or decrease the space between characters in a text, align a text, decorate a text, indent the first line in a text, and more.
Text Properties: NN: Netscape, IE: Internet Explorer, W3C: Web Standard Property Description Possible Values NN IE W3C color Sets the color of a text color 4.0 3.0 CSS1 direction Sets the text direction ltr rtl CSS2 letter-spacing Increase or decrease the space between characters normal length 6.0 4.0 CSS1 text-align Aligns the text in an element left right center justify 4.0 4.0 CSS1 text-decoration Adds decoration to text none underline overline line-through blink 4.0 4.0 CSS1 text-indent Indents the first line of text in an element length % 4.0 4.0 CSS1 text-shadow none color length
text-transform Controls the letters in an element none capitalize uppercase 4.0 4.0 CSS1 lowercase unicode-bidi normal embed bidi-override 5.0 CSS2 white-space Sets how white space inside an element is handled normal pre nowrap 4.0 5.5 CSS1 word-spacing Increase or decrease the space between words normal length 6.0 6.0 CSS1
<body> <h1>This is header 1</h1> <h2>This is header 2</h2> <p>This is a paragraph</p> </body> </html>
CSS Fonts The Font properties allow you to change the font family, boldness, size, and the style of a text.
Notes - Useful Tips Fonts are identified by their name in CSS1. Note that if a browser does not support the font that is specified, it will use a default font.
Font Properties: NN: Netscape, IE: Internet Explorer, W3C: Web Standard Property Description Values NN IE W3C font A shorthand property for setting all of the properties for a font in one declaration font-style font-variant font-weight font-size/line- height font-family caption icon menu message-box small-caption status-bar 4.0 4.0 CSS1 font-family A prioritized list of font family names and/or generic family names for an element family-name generic-family 4.0 3.0 CSS1 font-size Sets the size of a font xx-small x-small small medium large x-large xx-large smaller larger length % 4.0 3.0 CSS1 font-size-adjust Specifies an aspect value for an element that will preserve the x-height of the first- choice font none number CSS2 font-stretch Condenses or expands the current font-family normal wider narrower ultra-condensed extra-condensed condensed semi-condensed CSS2 semi-expanded expanded extra-expanded ultra-expanded font-style Sets the style of the font normal italic oblique 4.0 4.0 CSS1 font-variant Displays text in a small-caps font or a normal font normal small-caps 6.0 4.0 CSS1 font-weight Sets the weight of a font normal bold bolder lighter 100 200 300 400 500 600 700 800 900 4.0 4.0 CSS1
Example <html> <head> <style type="text/css"> p { font: italic small-caps 900 12px arial } </style> </head> <body> <p>This is a paragraph</p> </body> </html> CSS Borders The Border properties allow you to specify the style, color, and width of an element's border. In HTML we use tables to create borders around a text, but with the CSS Border properties we can create borders with nice effects, and it can be applied to any element.
Border Properties: NN: Netscape, IE: Internet Explorer, W3C: Web Standard Property Description Values NN IE W3C border A shorthand property for setting all of the properties for the four borders in one declaration border-width border-style border-color 4.0 4.0 CSS1 border-bottom A shorthand property for setting all of the properties for the bottom border in one declaration border-bottom- width border-style border-color 6.0 4.0 CSS1 border-bottom- color Sets the color of the bottom border border-color 6.0 4.0 CSS2 border-bottom- style Sets the style of the bottom border border-style 6.0 4.0 CSS2 border-bottom- width Sets the width of the bottom border thin medium thick length 4.0 4.0 CSS1 border-color Sets the color of the four borders, can have from one to four colors color 6.0 4.0 CSS1 border-left A shorthand property for setting all of the properties for the left border in one declaration border-left-width border-style border-color 6.0 4.0 CSS1 border-left-color Sets the color of the left border border-color 6.0 4.0 CSS2 border-left-style Sets the style of the left border border-style 6.0 4.0 CSS2 border-left-width Sets the width of the left border thin medium thick length 4.0 4.0 CSS1 border-right A shorthand property for setting all of the properties for the right border in one declaration border-right-width border-style border-color 6.0 4.0 CSS1 border-right-color Sets the color of the right border border-color 6.0 4.0 CSS2 border-right-style Sets the style of the right border border-style 6.0 4.0 CSS2 border-right-width Sets the width of the right border thin medium thick length 4.0 4.0 CSS1 border-style Sets the style of the four borders, can have from one to four styles none hidden dotted dashed solid double groove ridge inset outset 6.0 4.0 CSS1 border-top A shorthand property for setting all of the properties for the top border in one declaration border-top-width border-style border-color 6.0 4.0 CSS1 border-top-color Sets the color of the top border border-color 6.0 4.0 CSS2 border-top-style Sets the style of the top border border-style 6.0 4.0 CSS2 border-top-width Sets the width of the top border thin medium thick length 4.0 4.0 CSS1 border-width A shorthand property for setting the width of the four borders in one declaration, can have from one to four values thin medium thick length 4.0 4.0 CSS1
Example <html> <head> <style type="text/css"> p { border: medium double rgb(250,0,255) } </style> </head> <body> <p>Some text</p> </body> </html>
CSS Margins The Margin properties define the space around elements. It is possible to use negative values to overlap content. The top, right, bottom, and left margin can be changed independently using separate properties. A shorthand margin property can also be used to change all of the margins at once.
Margin Properties: NN: Netscape, IE: Internet Explorer, W3C: Web Standard Property Description Values NN IE W3C margin A shorthand property for setting the margin properties in one declaration margin-top margin-right margin-bottom margin-left 4.0 4.0 CSS1 margin-bottom Sets the bottom margin of an element auto length % 4.0 4.0 CSS1 margin-left Sets the left margin of an element auto length % 4.0 3.0 CSS1 margin-right Sets the right margin of an element auto length % 4.0 3.0 CSS1 margin-top Sets the top margin of auto 4.0 3.0 CSS1 an element length %
Example <html> <head> <style type="text/css"> p.margin {margin: 2cm 4cm 3cm 4cm} <! --only for one margin use p-margin { margin-left : 2cm } --> </style> </head> <body> <p> This is a paragraph </p> <p class="margin"> This is a paragraph with margins </p> <p> This is a paragraph </p> </body> </html> CSS Padding The Padding properties define the space between the element border and the element content. Negative values are not allowed. The top, right, bottom, and left padding can be changed independently using separate properties. A shorthand padding property is also created to control multiple sides at once.
Padding Properties: NN: Netscape, IE: Internet Explorer, W3C: Web Standard Property Description Values NN IE W3C padding A shorthand property for setting all of the padding properties in one declaration padding-top padding-right padding-bottom padding-left 4.0 4.0 CSS1 padding-bottom Sets the bottom padding of an element length % 4.0 4.0 CSS1 padding-left Sets the left padding of an element length % 4.0 4.0 CSS1 padding-right Sets the right padding of an element length % 4.0 4.0 CSS1 padding-top Sets the top padding of an element length % 4.0 4.0 CSS1 Example <html> <head> <style type="text/css"> td {padding-left: 2cm} </style> </head> <body> <table border="1"> <tr> <td> This is a tablecell with a left padding </td> </tr> </table> </body> </html> CSS List Properties
The List properties allow you to change between different list-item markers, set an image as a list-item marker, and set where to place a list-item marker. NN: Netscape, IE: Internet Explorer, W3C: Web Standard Property Description Values NN IE W3C list-style A shorthand property for setting all of the properties for a list in one declaration list-style-type list-style-position list-style-image 6.0 4.0 CSS1 list-style-image Sets an image as the list-item marker none url 6.0 4.0 CSS1 list-style-position Places the list-item marker in the list inside outside 6.0 4.0 CSS1 list-style-type Sets the type of the list-item marker none disc circle square decimal decimal-leading- zero lower-roman upper-roman lower-alpha upper-alpha lower-greek lower-latin upper-latin hebrew armenian georgian cjk-ideographic hiragana katakana hiragana-iroha katakana-iroha 4.0 4.0 CSS1 marker-offset auto length CSS2
Example <html> <head> <style type="text/css"> ul { list-style-type:square; list-style-position:inside; list-style- image:url('arrow.gif') } </style> </head> <body> <p><b>Note:</b> Netscape 4 does not display the images or position the list.</p> <ul> <li>Coffee</li> <li>Tea</li> <li>Coca Cola</li> </ul>
</body> </html>
Introduction to JavaScript JavaScript
JavaScript is used in millions of Web pages to improve the design, validate forms, and much more. JavaScript was developed by Netscape and is the most popular scripting language on the internet. JavaScript works in all major browsers that are version 3.0 or higher.
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 is lines of executable computer code A JavaScript is usually embedded directly in HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Everyone can use JavaScript without purchasing a license JavaScript is supported by all major browsers, like Netscape and Internet Explorer
Are Java and JavaScript the same? NO! Java and JavaScript are two completely different languages! Java (developed by Sun Microsystems) is a powerful and very 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("<h1>" + name + "</h1>") 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 will save the server from extra processing
How to Put a JavaScript Into an HTML Page <html> <body> <script type="text/javascript"> document.write("Hello World!") </script> </body> </html> The code above will produce this output on an HTML page: Hello World! To insert a script in an HTML page, we use the <script> tag. Use the type attribute to define the scripting language <script type="text/javascript"> Then the JavaScript starts: The JavaScript command for writing some output to a page is document.write document.write("Hello World!") Then the <script> tag has to be closed </script>
Ending Statements With a Semicolon? With traditional programming languages, like C++ and Java, each code statement has to end with a semicolon. Many programmers continue this habit when writing JavaScript, but in general, semicolons are optional! However, semicolons are required if you want to put more than one statement on a single line.
How to Handle Older Browsers Browsers that do not support scripts will display the script as page content. To prevent them from doing this, we may use the HTML comment tag: <script type="text/javascript"> <!-- some statements //--> </script> The two forward slashes at the end of comment line (//) are a JavaScript comment symbol. This prevents the JavaScript compiler from compiling the line. Note: You cannot put // in front of the first comment line (like //<!--), because older browsers will display it. Strange? Yes! But that's the way it is. Where to Put the JavaScript
Scripts in the body section will be executed WHILE the page loads. Scripts in the head section will be executed when CALLED.
Scripts 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. <html> <head> <script type="text/javascript"> some statements </script> </head> 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. <html> <head> </head> <body> <script type="text/javascript"> some statements </script> </body> 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. <html> <head> <script type="text/javascript"> some statements </script> </head> <body> <script type="text/javascript"> some statements </script> </body>
How to Run an External JavaScript Sometimes you might want to run the same script on several pages, without writing the script on each and every page. To simplify this you can write a script in an external file, and save it with a .js file extension, like this: document.write("This script is external") Save the external file as xxx.js. Note: The external script cannot contain the <script> tag Now you can call this script, using the "src" attribute, from any of your pages: <html> <head> </head> <body> <script src="xxx.js"></script> </body> </html> Remember to place the script exactly where you normally would write the script. JavaScript Variables
A variable is a "container" for information you want to store. A variable's value can change during the script. You can refer to a variable by name to see its value or to change its value. Rules for Variable names: Variable names are case sensitive They must begin with a letter or the underscore character
Declare a Variable You can create a variable with the var statement: var strname = some value You can also create a variable without the var statement: strname = some value
Assign a Value to a Variable You assign a value to a variable like this: var strname = "Hege" Or like this: strname = "Hege" The variable name is on the left side of the expression and the value you want to assign to the variable is on the right. Now the variable "strname" has the value "Hege".
Lifetime of Variables When you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared. If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed. JavaScript Operators
Operators are used to operate on values.
Arithmetic Operators Operator Description Example Result + Addition x=2 x+2 4 - Subtraction x=2 5-x 3 * Multiplication x=4 20 x*5 / Division 15/5 5/2 3 2.5 % Modulus (division remainder) 5%2 10%8 10%2 1 2 0 ++ Increment x=5 x++ x=6 -- Decrement x=5 x-- x=4 Assignment Operators Operator Example Is The Same As = x=y x=y += x+=y x=x+y -= x-=y x=x-y *= x*=y x=x*y /= x/=y x=x/y %= x%=y x=x%y Comparison Operators Operator Description Example == is equal to 5==8 returns false != is not equal 5!=8 returns true > is greater than 5>8 returns false < is less than 5<8 returns true >= is greater than or equal to 5>=8 returns false <= is less than or equal to 5<=8 returns true Logical Operators Operator Description Example && and x=6 y=3 (x < 10 && y > 1) returns true || or x=6 y=3 (x==5 || y==5) returns false ! not x=6 y=3 !(x==y) returns true String Operator A string is most often text, for example "Hello World!". To stick two or more string variables together, use the + operator. txt1="What a very" txt2="nice day!" txt3=txt1+txt2 The variable txt3 now contains "What a verynice day!". To add a space between two string variables, insert a space into the expression, OR in one of the strings. txt1="What a very" txt2="nice day!" txt3=txt1+" "+txt2 or txt1="What a very " txt2="nice day!" txt3=txt1+txt2 The variable txt3 now contains "What a very nice day!". JavaScript Conditional Statements
Conditional statements in JavaScript are used to perform different actions based on different conditions. Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In JavaScript we have three conditional statements: if statement - use this statement if you want to execute a set of code when a condition is true if...else statement - use this statement if you want to select one of two sets of lines to execute switch statement - use this statement if you want to select one of many sets of lines to execute
If and If...else Statement You should use the if statement if you want to execute some code if a condition is true. Syntax if (condition) { code to be executed if condition is true } Example <script type="text/javascript"> //If the time on your browser is less than 10, //you will get a "Good morning" greeting. var d=new Date() var time=d.getHours()
if (time<10) { document.write("<b>Good morning</b>") } </script> Notice that there is no ..else.. in this syntax. You just tell the code to execute some code if the condition is true. If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement. Syntax if (condition) { code to be executed if condition is true } else { code to be executed if condition is false } Example <script type="text/javascript"> //If the time on your browser is less than 10, //you will get a "Good morning" greeting. //Otherwise you will get a "Good day" greeting. var d = new Date() var time = d.getHours()
Switch Statement You should use the Switch statement if you want to select one of many blocks of code to be executed. Syntax switch (expression) { case label1: code to be executed if expression = label1 break case label2: code to be executed if expression = label2 break default: code to be executed if expression is different from both label1 and label2 } This is how it works: First we have a single expression (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. Example <script type="text/javascript"> //You will receive a different greeting based //on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc. var d=new Date() theDay=d.getDay() switch (theDay) { case 5: document.write("Finally Friday") break case 6: document.write("Super Saturday") break case 0: document.write("Sleepy Sunday") break default: document.write("I'm looking forward to this weekend!") } </script>
Conditional Operator JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax variablename=(condition)?value1:value2 Example greeting=(visitor=="PRES")?"Dear President ":"Dear " If the variable visitor is equal to PRES, then put the string "Dear President " in the variable named greeting. If the variable visitor is not equal to PRES, then put the string "Dear " into the variable named greeting. JavaScript Functions
A function is a reusable code-block that will be executed by an event, or when the function is called. A function contains some code that will be executed by an event or a call to that function. A function is a set of statements. You can reuse functions within the same script, or in other documents. You define functions at the beginning of a file (in the head section), and call them later in the document. It is now time to take a lesson about the alert-box: This is JavaScript's method to alert the user. alert("This is a message")
How to Define a Function To create a function you define its name, any values ("arguments"), and some statements: function myfunction(argument1,argument2,etc) { some statements } A function with no arguments must include the parentheses: function myfunction() { some statements } Arguments are variables used in the function. The variable values are values passed on by the function call. By placing functions in the head section of the document, you make sure that all the code in the function has been loaded before the function is called. Some functions return a value to the calling expression function result(a,b) { c=a+b return c }
How to Call a Function A function is not executed before it is called. You can call a function containing arguments: myfunction(argument1,argument2,etc) or without arguments: myfunction()
The return Statement Functions that will return a result must use the "return" statement. This statement specifies the value which will be returned to where the function was called from. Say you have a function that returns the sum of two numbers: function total(a,b) { result=a+b return result } When you call this function you must send two arguments with it: sum=total(2,3) The returned value from the function (5) will be stored in the variable called sum. JavaScript Looping Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to do this. In JavaScript we have the following looping statements: while - loops through a block of code while a condition is true do...while - loops through a block of code once, and then repeats the loop while a condition is true for - run statements a specified number of times
while The while statement will execute a block of code while a condition is true.. while (condition) { code to be executed }
do...while The do...while statement will execute a block of code once, and then it will repeat the loop while a condition is true do { code to be executed } while (condition)
for The for statement will execute a block of code a specified number of times for (initialization; condition; increment) { code to be executed } Example <html> <body> <script type="text/javascript"> for (i = 0; i <= 5; i++) { document.write("The number is " + i) document.write("<br>") } </script>
<p>Explanation:</p> <p>The for loop sets <b>i</b> equal to 0.</p> <p>As long as <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p> <p><b>i</b> will increase by 1 each time the loop runs.</p> </body> </html>
JavaScript Guidelines
JavaScript is Case Sensitive A function named "myfunction" is not the same as "myFunction". Therefore watch your capitalization when you create or call variables, objects and functions.
Symbols Open symbols, like ( { [ " ', must have a matching closing symbol, like ' " ] } ).
White Space JavaScript ignores extra spaces. You can add white space to your script to make it more readable. These lines are equivalent: name="Hege" name = "Hege"
Break up a Code Line You can break up a code line within a text string with a backslash. The example below will be displayed properly: document.write("Hello \ World!") Note: You can not break up a code line like this: document.write \ ("Hello World!") The example above will cause an error.
Insert Special Characters You can insert special characters (like " ' ; &) with the backslash: document.write ("You \& I sing \"Happy Birthday\".") The example above will produce this output: You & I sing "Happy Birthday".
Comments You can add a comment to your JavaScript code starting the comment with two slashes "//": sum=a + b //calculating the sum You can also add a comment to the JavaScript code, starting the comment with "/*" and ending it with "*/" sum=a + b /*calculating the sum*/ Using "/*" and "*/" is the only way to create a multi-line comment: /* This is a comment block. It contains several lines*/ JavaScript Objects JavaScript Array Object
The Array object is used to store a set of values in a single variable name.
The Array object is used to store a set of values in a single variable name. Each value is an element of the array and has an associated index number. You create an instance of the Array object with the "new" keyword. The following example creates two arrays, both of three elements: var family_names=new Array(3) var family_names=new Array("Tove","Jani","Stale") You can refer to a particular element in the array by using the name of the array and the index number. The index number starts at 0. If you create an array with a single numeric parameter, you can assign data to each of the elements in the array like this: family_names[0]="Tove" family_names[1]="Jani" family_names[2]="Stale" And the data can be retrieved by using the index number of the particular array element you want, like this: mother=family_names[0] father=family_names[1] The Array object's properties and methods are described below: NN: Netscape, IE: Internet Explorer Properties Syntax: object.property_name Property Description NN IE constructor Contains the function that created an object's prototype 4 4 length Returns the number of elements in the array 3 4 prototype Allows you to add properties to an array 3 4 Methods Syntax: object.method_name() Method Description NN IE concat() Joins two or more arrays and returns a new array 4 4 join(delimiter) Puts all the elements of an array into a string separated by a specified delimiter (comma is default) 3 4 pop() Removes and returns the last element of an array 4 5.5 push("element1","element2") Adds one or more elements to the end of an array and returns the new length 4 5.5 reverse() Reverses the order of the elements in an array 3 4 shift() Removes and returns the first element of an array 4 5.5 slice(begin[,end]) Creates a new array from a selected section of an existing array 4 4 sort() Sorts the elements of an array 3 4 splice(index,howmany[,el1,el2]) Adds and/or removes elements of an array 4 5.5 toSource() Returns a string that represents the source code of the array 4.06 4 toString() Returns a string that represents the specified array and its elements 3 4 unshift("element1","element2") Adds one or more elements to the beginning of an array and returns the new length 4 5.5 valueOf() Returns the primitive value of an array 4 3
Example <html> <body> <script type="text/javascript"> var famname = new Array(3) famname[0] = "Jani" famname[1] = "Tove" famname[2] = "Hege"
Output: 3 Jani.Tove.Hege Hege,Tove,Jani 5 Jon Hege JavaScript Boolean Object
The Boolean object is an object wrapper for a Boolean value and it is used to convert a non-Boolean value to a Boolean value.
The Boolean object is an object wrapper for a Boolean value and it is used to convert a non-Boolean value to a Boolean value, either true or false. If the Boolean object has no initial value or if it is 0, null, "", false, or NaN, the initial value is false. Otherwise it is true (even with the string "false"). All the following lines of code create Boolean objects with an initial value of false: var b1=new Boolean() var b2=new Boolean(0) var b3=new Boolean(null) var b4=new Boolean("") var b5=new Boolean(false) var b6=new Boolean(NaN) All the following lines of code create Boolean objects with an initial value of true: var b1=new Boolean(true) var b2=new Boolean("true") var b3=new Boolean("false") var b4=new Boolean("Richard") The Boolean object's properties and methods are described below: NN: Netscape, IE: Internet Explorer Properties Syntax: object.property_name Property Description NN IE constructor Contains the function that created an object's prototype 4 4 prototype Allows addition of properties and methods to the object 3 4 Methods Syntax: object.method_name() Method Description NN IE toString() Converts a Boolean value to a string. This method is called by JavaScript automatically whenever a Boolean object is used in a situation requiring a string 4 4 valueOf() Returns a primitive value ("true" or "false") for the Boolean object 4 4
JavaScript Math Object
The built-in Math object includes mathematical constants and functions.
The built-in Math object includes mathematical constants and functions. You do not need to create the Math object before using it. To store a random number between 0 and 1 in a variable called "r_number": r_number=Math.random() To store the rounded number of 8.6 in a variable called "r_number": r_number=Math.round(8.6) The Math object's properties and methods are described below: NN: Netscape, IE: Internet Explorer Properties Syntax: object.property_name Property Description NN IE E Returns the base of a natural logarithm 2 3 LN2 Returns the natural logarithm of 2 2 3 LN10 Returns the natural logarithm of 10 2 3 LOG2E Returns the base-2 logarithm of E 2 3 LOG10E Returns the base-10 logarithm of E 2 3 PI Returns PI 2 3 SQRT1_2 Returns 1 divided by the square root of 2 2 3 SQRT2 Returns the square root of 2 2 3 Methods Syntax: object.method_name() Method Description NN IE abs(x) Returns the absolute value of x 2 3 acos(x) Returns the arccosine of x 2 3 asin(x) Returns the arcsine of x 2 3 atan(x) Returns the arctangent of x 2 3 atan2(y,x) Returns the angle from the x axis to a point 2 3 ceil(x) Returns the nearest integer greater than or equal to x 2 3 cos(x) Returns the cosine of x 2 3 exp(x) Returns the value of E raised to the power of x 2 3 floor(x) Returns the nearest integer less than or equal to x 2 3 log(x) Returns the natural log of x 2 3 max(x,y) Returns the number with the highest value of x 2 3 and y min(x,y) Returns the number with the lowest value of x and y 2 3 pow(x,y) Returns the value of the number x raised to the power of y 2 3 random() Returns a random number between 0 and 1 2 3 round(x) Rounds x to the nearest integer 2 3 sin(x) Returns the sine of x 2 3 sqrt(x) Returns the square root of x 2 3 tan(x) Returns the tangent of x 2 3 JavaScript Date Object
The Date object is used to work with dates and times. To create an instance of the Date object and assign it to a variable called "d", you do the following: var d=new Date() After creating an instance of the Date object, you can access all the methods of the Date object from the "d" variable. To return the current day in a month (from 1-31) of a Date object, write the following: d.getDate() The Date object can also have the following parameters: new Date(milliseconds) new Date(dateString) new Date(yr_num, mo_num, day_num [, hr_num, min_num, sec_num, ms_num]) milliseconds - the number of milliseconds since 01 January, 1970 00:00:00 dateString - the date in a format that is recognized by the Date.parse method yr_num, mo_num, day_num - the year, month or day of the date hr_num, min_num, sec_num, ms_num - the hours, minutes, seconds and milliseconds If you only use Date(), JavaScript creates an object for today's date according to the time on the local machine. Here are some examples on how to create Date objects: var d=new Date("October 12, 1988 13:14:00") var d=new Date("October 12, 1988") var d=new Date(88,09,12,13,14,00) var d=new Date(88,09,12) var d=new Date(500) The Date object's properties and methods are described below: NN: Netscape, IE: Internet Explorer Properties Syntax: object.property_name Property Description NN IE constructor Contains the function that created an object's prototype 4 4 prototype Allows addition of properties to a date 3 4 Methods Syntax: object.method_name() Method Description NN IE Date() Returns a Date object 2 3 getDate() Returns the date of a Date object (from 1-31) 2 3 getDay() Returns the day of a Date object (from 0-6. 0=Sunday, 1=Monday, etc.) 2 3 getMonth() Returns the month of a Date object (from 0- 11. 0=January, 1=February, etc.) 2 3 getFullYear() Returns the year of a Date object (four digits) 4 4 getYear() Returns the year of a Date object (from 0- 99). Use getFullYear instead !! 2 3 getHours() Returns the hour of a Date object (from 0-23) 2 3 getMinutes() Returns the minute of a Date object (from 0- 59) 2 3 getSeconds() Returns the second of a Date object (from 0- 59) 2 3 getMilliseconds() Returns the millisecond of a Date object (from 0-999) 4 4 getTime() Returns the number of milliseconds since midnight 1/1-1970 2 3 getTimezoneOffset() Returns the time difference between the user's computer and GMT 2 3 getUTCDate() Returns the date of a Date object in universal (UTC) time 4 4 getUTCDay() Returns the day of a Date object in universal time 4 4 getUTCMonth() Returns the month of a Date object in universal time 4 4 getUTCFullYear() Returns the four-digit year of a Date object in universal time 4 4 getUTCHours() Returns the hour of a Date object in universal time 4 4 getUTCMinutes() Returns the minutes of a Date object in universal time 4 4 getUTCSeconds() Returns the seconds of a Date object in universal time 4 4 getUTCMilliseconds() Returns the milliseconds of a Date object in universal time 4 4 parse() Returns a string date value that holds the number of milliseconds since January 01 1970 00:00:00 2 3 setDate() Sets the date of the month in the Date object (from 1-31) 2 3 setFullYear() Sets the year in the Date object (four digits) 4 4 setHours() Sets the hour in the Date object (from 0-23) 2 3 setMilliseconds() Sets the millisecond in the Date object (from 0-999) 4 4 setMinutes() Set the minute in the Date object (from 0-59) 2 3 setMonth() Sets the month in the Date object (from 0- 11. 0=January, 1=February) 2 3 setSeconds() Sets the second in the Date object (from 0- 59) 2 3 setTime() Sets the milliseconds after 1/1-1970 2 3 setYear() Sets the year in the Date object (00-99) 2 3 setUTCDate() Sets the date in the Date object, in universal time (from 1-31) 4 4 setUTCDay() Sets the day in the Date object, in universal time (from 0-6. Sunday=0, Monday=1, etc.) 4 4 setUTCMonth() Sets the month in the Date object, in universal time (from 0-11. 0=January, 1=February) 4 4 setUTCFullYear() Sets the year in the Date object, in universal time (four digits) 4 4 setUTCHours() Sets the hour in the Date object, in universal time (from 0-23) 4 4 setUTCMinutes() Sets the minutes in the Date object, in universal time (from 0-59) 4 4 setUTCSeconds() Sets the seconds in the Date object, in universal time (from 0-59) 4 4 setUTCMilliseconds() Sets the milliseconds in the Date object, in universal time (from 0-999) 4 4 toGMTString() Converts the Date object to a string, set to GMT time zone 2 3 toLocaleString() Converts the Date object to a string, set to the current time zone 2 3 toString() Converts the Date object to a string 2 4
Example <html> <body> <script type="text/javascript"> var d = new Date() var time = d.getHours() if (time < 10) { document.write("<b>Good morning</b>") } else { document.write("<b>Good day</b>") } </script> <p> This example demonstrates the If...Else statement. </p> <p> If the time on your browser is less than 10, you will get a "Good morning" greeting. Otherwise you will get a "Good day" greeting. </p> </body> </html> JavaScript String Object
The String object is used to work with text. The String object's properties and methods are described below: NN: Netscape, IE: Internet Explorer Properties Syntax: object.property_name Property Description NN IE constructor 4 4 length Returns the number of characters in a string 2 3 Methods Syntax: object.method_name() Method Description NN IE anchor("anchorname") Returns a string as an anchor 2 3 big() Returns a string in big text 2 3 blink() Returns a string blinking 2 bold() Returns a string in bold 2 3 charAt(index) Returns the character at a specified position 2 3 charCodeAt(i) Returns the Unicode of the character at a specified position 4 4 concat() Returns two concatenated strings 4 4 fixed() Returns a string as teletype 2 3 fontcolor() Returns a string in a specified color 2 3 fontsize() Returns a string in a specified size 2 3 fromCharCode() Returns the character value of a Unicode 4 4 indexOf() Returns the position of the first occurrence of a specified string inside another string. Returns -1 if it never occurs 2 3 italics() Returns a string in italic 2 3 lastIndexOf() Returns the position of the first occurrence of a specified string inside another string. Returns -1 if it never occurs. Note: This method starts from the right and moves left! 2 3 link() Returns a string as a hyperlink 2 3 match() Similar to indexOf and lastIndexOf, but this method returns the specified string, or "null", instead of a numeric value 4 4 replace() Replaces some specified characters with some new specified characters 4 4 search() Returns an integer if the string contains some specified characters, if not it returns -1 4 4 slice() Returns a string containing a specified character index 4 4 small() Returns a string as small text 2 3 split() Splits a string into an array of strings 4 4 strike() Returns a string strikethrough 2 3 sub() Returns a string as subscript 2 3 substr() Returns the specified characters. 14,7 returns 7 characters, from the 14th character (starts at 0) 4 4 substring() Returns the specified characters. 7,14 returns all characters from the 7th up to but not including the 14th (starts at 0) 2 3 sup() Returns a string as superscript 2 3 toLowerCase() Converts a string to lower case 2 3 toUpperCase() Converts a string to upper case 2 3
Example <html> <body> <script type="text/javascript"> var str="Internet Programming is a good course!" var pos=str.indexOf("Programmingl") if (pos>=0) { document.write("Programming found at position: ") document.write(pos + "<br />") } else { document.write("Programming not found!") } </script>
<p>This example tests if a string contains a specified word. If the word is found it returns the position of the first character of the word in the original string. Note: The first position in the string is 0!</p> </body> </html>
HTML DOM
Introduction
The HTML DOM is a programming interface for HTML documents. The HTML DOM defines how you can access and change the content of HTML documents. The DOM stands for the Document Object Model. The HTML DOM is the Document Object Model for HTML. The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML objects.
Why The HTML DOM? Because we need an easy and standard way to access the content of HTML documents, that can be used by all types of browsers, and all types of programming languages. The HTML DOM defines how to access HTML elements, and how to change, add, or delete their content, attributes and styles.
The DOM Standard The DOM standard is developed by W3C (The World Wide Web Consortium): "The W3C Document Object Model (DOM) is a platform and language neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document" Key players in the development of the DOM has been people from ArborText, IBM, Inso EPS, JavaSoft, Microsoft, Netscape, Novell, the Object Management Group, SoftQuad, Sun Microsystems, and Texcel.
In this material, we Will Use JavaScript The HTML DOM is a platform and language independent API (Application Programming Interface). It can be used by any programming language like Java, JavaScript, and VBScript.
The DOM Parts The DOM is separated into three parts: DOM Core XML DOM (X)HTML DOM
An HTML DOM Example This coding example shows how the background color of an HTML document can be changed to yellow when a user clicks on it: <html>
<head> <script type="text/javascript"> function ChangeColor() { document.body.bgColor="yellow" } </script> </head>
<body onclick="ChangeColor()"> Click on this document! </body>
</html>
Document Objects HTML DOM defines HTML documents as a collection of objects. The document object is the parent of all the other objects in an HTML document. The document.body object represents the <body> element of the HTML document. The document object is the parent of the body object, and the body object is a child of the document object.
Object Properties HTML document objects can have properties (also called attributes). The document.body.bgColor property defines the background color of the body object. The statement document.body.bgColor="yellow" in the example above, sets the background color of the HTML document to yellow.
Object Events HTML document objects can respond to events. The onclick="ChangeColor()" attribute of the <body> element in the example above, defines an action to take place when the user clicks on the document.
Functions The ChangeColor() function in the example above, is a JavaScript function. The function will be triggered (started) when a user clicks on the HTML document.
Changing Style The HTML DOM also defines a model for changing the styles of HTML objects. The coding example below shows how to obtain the same effect as the first example, by changing the style of the body object: <html>
<head> <script type="text/javascript"> function ChangeColor() { document.body.style.background="yellow" } </script> </head>
<body onclick="ChangeColor()"> Click on this document! </body>
</html>
The W3C DOM The W3C Document Object Model is a platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure and style of documents. The W3C DOM provides a standard set of objects for representing HTML and XML documents, how these objects can be combined, and a standard interface for accessing and manipulating them. The DOM is separated into three parts: Core DOM XML DOM HTML DOM The Core DOM provides a set of objects that can represent any structured document. The HTML and XML specifications provide additional interfaces that are used with the core specification to provide a more convenient view into the document. These specifications consist of objects and methods that provide easier and more direct access into the specific types of documents. DOM is being designed at several levels:
DOM Level 0 The DOM Level 0 is not a W3C specification. It is just a definition of the functionality equivalent to that found in Netscape Navigator 3.0 and Microsoft Internet Explorer 3.0. W3C's DOM Level 1 builds on this functionality.
DOM Level 1 DOM Level 1 concentrates on HTML and XML document models. It contains functionality for document navigation and manipulation. DOM Level 1 was released as a W3C Recommendation 1. October 1998. A Working Draft for a Second Edition (SE) was published 29. September. 2000.
DOM Level 2 DOM Level 2 adds a style sheet object model to DOM Level 1, and defines functionality for manipulating the style information attached to a document. DOM Level 2 also defines an event model and provides support for XML namespaces. The DOM Level 2 specification was released as W3C Recommendations 13. November 2000: DOM Level 2 Core DOM Level 2 Core specifies an API to access and update the content and structure of documents. The API also contains interfaces dedicated to XML. DOM Level 2 HTML DOM Level 2 HTML specifies an API to manipulate the structure and contents of an HTML document. (This part of the specification is still a working draft) DOM Level 2 Views DOM Level 2 Views specifies an API to dynamically access and update the view of a document. A view is some alternate representation of, or a presentation of, a document. DOM Level 2 Style DOM Level 2 Style specifies an API to dynamically access and update the content style sheets. DOM Level 2 Events DOM Level 2 Events specifies an API to access document events. DOM Level 2 Traversal-Range DOM Level 2 Traversal-Range specifies an API to dynamically traverse and identify a range of content in a document.
DOM Level 3 DOM Level 3 specifies content models (DTD and Schemas) and document validation. It also specifies document loading and saving, document views, document formatting, and key events. DOM Level 3 builds on DOM Core Level 2. DOM Level 3 Requirements The DOM Requirements document has been updated for Level 3 requirements and was released as a Working Draft 12. April 2000. The following DOM Level 3 Working Drafts were released 1. September 2000: DOM Level 3 Core DOM Level 3 Core specifies an API to access and update the content, structure and style of documents. DOM Level 3 Events The DOM Level 3 Events API expands the functionality of the Level 2 Event API by adding new interfaces and new event sets. DOM Level 3 Load and Save DOM Level 3 Content Model specifies an API for document loading and saving, content models (DTD and Schemas) and document validation support. DOM Level 3 Views and Formatting DOM Level 3 Views specifies an API to dynamically access and update the view of a document. A view is some alternate representation of, or a presentation of, a document. HTML DOM Objects Reference Anchor object Applet object Area object Base object Basefont object Body object Button object Checkbox object Document object Event object FileUpload object Form object Frame object Frameset object Hidden object History object Iframe object Image object Link object Location object Meta object Navigator object Option object Password object Radio object Reset object Screen object Select object Style object Submit object Table object TableData object TableHeader object TableRow object Text object Textarea object Window object Examples Body Object The Body object represents the body of the document (the HTML body). The Body object's properties are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard) Properties Syntax: object.property_name Property Description N IE W3C accessKey Sets or returns the keyboard key to access the body object 5 No aLink Sets or returns the color of active links in the document 6 5 Yes background Sets or returns the URL of the background image of the document 6 5 Yes bgColor Sets or returns the background color of the document 6 5 Yes id Sets or returns the id of the body (In IE 4 this property is read-only) 4 No link Sets or returns the color of links in the document 6 5 Yes scrollLeft Sets or returns the distance between the left edge of the body and the leftmost portion of the content visible in the window 7 5 No scrollTop Sets or returns the distance between the top edge of the body and the topmost portion of the content visible in the window 7 5 No text Sets or returns the color of text in the document 6 5 Yes vLink Sets or returns the color of visited links in the document 6 5 Yes
History Object The History object is a predefined object which can be accessed through the history property of the Window object. The History object consists of an array of URLs. These URLs are the URLs the user has visited within a browser window. Note: The History object is not a W3C standard. The History object's properties and methods are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard) Properties Syntax: history.property_name Property Description N IE W3C length Returns the number of elements in the history list 2 3 No Methods Syntax: history.method_name() Method Description N IE W3C back() Loads the previous URL in the history list (same as clicking the Back button and to history.go(-1)) 2 3 No forward() Loads the next URL in the history list (same as clicking the Forward button and to history.go(1)) 2 3 No go(number|"URL") Loads a specified URL from the history list 2 3 No
Password Object For each instance of an HTML <input type="password"> tag on a form, a Password object is created. All Password objects are stored in the elements array of the corresponding form. You can access a Password object by indexing this array - either by number (0 represents the first element in a form) or by using the value of the name attribute. The Password object's properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard) Properties Syntax: object.property_name Property Description N IE W3C accept Sets or returns a list of content types that the server that processes this form will handle correct - Yes accesskey Sets or returns the keyboard key to access the password field 4 Yes defaultValue Sets or returns the initial value of the password field 2 3.02 Yes disabled Sets or returns whether or not the password field should be disabled 6 5.5 Yes form Returns a reference to the password field's parent form 2 3.02 Yes id Sets or returns the id of the password field (In IE 4 this property is read-only) 4 No maxLength Sets or returns the maximum number of characters the user can enter in the password field 6 4 Yes name Sets or returns the name of the password field 2 3.02 Yes readOnly Sets or returns whether the content of the password field is read-only 6 4 Yes size Sets or returns the size of the password field 6 3.02 Yes tabIndex Sets or returns the index that defines the tab order for the password field 4 Yes type The type of the form element. For a password object it will always be "password" 3 3.02 Yes value Sets or returns the value of the value attribute of the password field 2 3.02 Yes Methods Syntax: object.method_name() Method Description N IE W3C blur() Removes focus from the password field 2 4 Yes click() Simulates a mouse-click on the password field 4 No focus() Sets focus on the password field 2 3.02 Yes select() Selects and highlights the entire text that is in the password field 2 4 Yes Events Syntax: object.event_name="someJavaScriptCode" Event Description N IE W3C onBlur Executes some code when the password field loses focus 2 4 onClick Executes some code when the user clicks in the password field 4 onFocus Executes some code when the password field gets focus 2 3.02 onKeyDown Executes some code when a key is pressed down in the password field 4 4 onKeyPress Executes some code when an alphanumeric key is pressed in the password field 4 4 onKeyUp Executes some code when a key is released in the password field 4 4 onSelectStart Executes some code when some text in the password field is selected 4
DHTML (Dynamic HTML)
Introduction to DHTML
DHTML is the art of making HTML pages dynamic! In our DHTML tutorial you will learn how to combine HTML, CSS, and JavaScript to create dynamic and interactive Web pages. DHTML is NOT a W3C Standard DHTML stands for Dynamic HTML. DHTML is not a standard defined by the World Wide Web Consortium (W3C). DHTML is a "marketing term" - used by Netscape and Microsoft to describe the new technologies the 4.x generation browsers would support. DHTML is a combination of technologies used to create dynamic Web sites. To most people DHTML means a combination of HTML 4.0, Style Sheets and JavaScript. W3C once said: "Dynamic HTML is a term used by some vendors to describe the combination of HTML, style sheets and scripts that allows documents to be animated."
DHTML Technologies With DHTML a Web developer can control how to display and position HTML elements in a browser window. 1. HTML 4.0 With HTML 4.0 all formatting can be moved out of the HTML document and into a separate style sheet. Because HTML 4.0 separates the presentation of the document from its structure, we have got total control of presentation layout without messing up the document content. 2. Cascading Style Sheets (CSS) With CSS we got a style and layout model for HTML documents. CSS was a breakthrough in Web design because it allowed developers to control the style and layout of multiple Web pages all at once. As a Web developer you can define a style for each HTML element and apply it to as many Web pages as you want. To make a global change, simply change the style, and all elements in the Web are updated automatically. 3. The Document Object Model (DOM) DOM stands for the Document Object Model. The HTML DOM is the Document Object Model for HTML. The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML objects. "The W3C Document Object Model (DOM) is a platform and language neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document". 4. JavaScript (and VBScript) Allows you to write code to control all HTML elements.
DHTML technologies in Netscape 4.x and Internet Explorer 4.x: Netscape Navigator 4.x Cross-Browser DHTML Internet Explorer 4.x JSS (JavaScript Style Sheets) (allows you to control how different HTML elements will be displayed) Layers (allows you to control element positioning and visibility) CSS1 CSS2 (allows you to control how different HTML elements will be displayed) CSS Positioning (allows you to control element positioning and visibility) JavaScript Visual Filters (allow you to apply visual effects to text and graphics) Dynamic CSS (allows you to control element positioning and visibility) Note: Problems with coding DHTML technologies WILL occur as long as each browser creates its own proprietary features and technology that is not supported by other browsers. A Web page may look great in one browser and horrible in another. DHTML CSS (CSS-P) CSS is used to style HTML elements. Which Attributes can be Used with CSS-P? First, the element must specify the position attribute (relative or absolute). Then we can set the following CSS-P attributes: left - the element's left position top - the element's top position visibility - specifies whether an element should be visible or hidden z-index - the element's stack order clip - element clipping overflow - how overflow contents are handled
Position The CSS position property allows you to control the positioning of an element in a document. position:relative The position:relative property positions an element relative to its current position. The following example positions the div element 10 pixels to the right from where it's normally positioned: div { position:relative; left:10; } position:absolute The position:absolute property positions an element from the margins of the window. The following example positions the div element 10 pixels to the right from the left-margin of the the window: div { position:absolute; left:10; }
Visibility The visibility property determines if an element is visible or not. visibility:visible The visibility:visible property makes the element visible. h1 { visibility:visible; } visibility:hidden The visibility:hidden property makes the element invisible. h1 { visibility:hidden; }
Z-index The z-index property is used to place an element "behind" another element. Default z-index is 0. The higher number the higher priority. z-index: -1 has lower priority. h1 { z-index:1; } h2 { z-index:2; } In the example above, if the h1 and h2 elements are positioned on top of each other, the h2 element will be positioned on top of the h1 element.
Filters The filter property allows you to add more style effects to your text and images. h1 { width:100%; filter:glow; } Note: Always specify the width of the element if you want to use the filter property. The example above produces this output: Header Different Filters Note: Some of the Filter properties will not work unless the background- color property is set to transparent! Property Argument Description Example alpha opacity finishopacity style startx starty finishx finishy Allows you to set the opacity of the element filter:alpha(opacity=20, finishopacity=100, style=1, startx=0, starty=0, finishx=140, finishy=270) blur add direction strength Makes the element blur filter:blur(add=true, direction=90, strength=6); chroma color Makes the specified color transparent filter:chroma(color=#ff0000) fliph none Flips the element horizontally filter:fliph; flipv none Flips the element vertically filter:flipv; glow color strength Makes the element glow filter:glow(color=#ff0000, strength=5); gray none Renders the element in black and white filter:gray; invert none Renders the element in its reverse color and brightness values filter:invert; mask color Renders the element with the specified background color, and transparent foreground color filter:mask(color=#ff0000); shadow color direction Renders the element with a shadow filter:shadow(color=#ff0000, direction=90); dropshadow color offx offy Renders the element with a dropshadow filter:dropshadow(color=#ff0000, offx=5, offy=5, positive=true); positive wave add freq lightstrength phase strength Renders the element like a wave filter:wave(add=true, freq=1, lightstrength=3, phase=0, strength=5) xray none Renders the element in black and white with reverse color and brightness values filter:xray;
Background The background property allows you to select your own background. background-attachment:scroll The background scrolls along with the rest of the page. background-attachment:fixed The background does not move when the rest of the page scrolls.
DHTML Document Object Model
The Document Object Model gives us access to every element in a document.
How to access an element? The element must have an id attribute defined and a scripting language is needed. JavaScript is the most browser compatible scripting language, so we use JavaScript. <html> <body> <h1 id="header">My header</h1> <script type="text/javascript"> document.getElementById('header').style.color="red" </script> </body> </html> The script changes the color of the header element, and produces this output. My header
DHTML Event Handlers
With an event handler you can do something with an element when an event occurs. when the user clicks an element, when the page loads, when a form is submitted, etc. <h1 onclick="style.color='red'">Click on this text</h1> The example above defines a header that turns red when a user clicks on it. You can also add a script in the head section of the page and then call the function from the event handler: <html> <head> <script type="text/javascript"> function changecolor() { document.getElementById('header').style.color="red" } </script> </head> <body> <h1 id="header" onclick="changecolor()"> Click on this text</h1> </body> </html>
HTML 4.0 Event Handlers Event Occurs when... onabort a user aborts page loading onblur a user leaves an object onchange a user changes the value of an object onclick a user clicks on an object ondblclick a user double-clicks on an object onfocus a user makes an object active onkeydown a keyboard key is on its way down onkeypress a keyboard key is pressed onkeyup a keyboard key is released onload a page is finished loading. Note: In Netscape this event occurs during the loading of a page! onmousedown a user presses a mouse-button onmousemove a cursor moves on an object onmouseover a cursor moves over an object onmouseout a cursor moves off an object onmouseup a user releases a mouse-button onreset a user resets a form onselect a user selects content on a page onsubmit a user submits a form onunload a user closes a page