WEB Programming I
Week 1 Newsletter (E. Nikjeh)
Hello Class,
HTML
Introduction
HTML stands for HyperText Markup Language . HTML files are text files that have an “ htm ” or “ html ” extension.
Example
filename.htm
HTML uses tags to tell a browser what to do. For example, <B> sample </B> tells a browser to
bold the word “ sample ”. HTML is not case sensitive ; so it does not matter if the tags are lower
or upper case. The front tag is <> and the back tag is </> . If a browser does not understand a tag,
it ignores the tag.
Structure Tags:
<HTML>…</HTML> first and last tag of an HTML file
<HEAD>…</HEAD> first section an HTML file
<BODY>…</BODY> main section of an HTML file
Example 1:
<HTML>
<HEAD>
<TITLE>…</TITLE>
…
</HEAD>
<BODY>
…
</BODY>
</HTML>
Example 2:
<TITLE> title of document </TITLE>
<H1>…</H1> heading in document, there are 6 heading levels: 1,2,3,4,5,6
We can align the header with ALIGN =direction, where direction is left , right , or center
<P>…</P> marks a paragraph. </P> is optional
<P ALIGN=CENTER > … </P> aligns paragraph
<P ALIGN=LEFT >
<P ALIGN=RIGHT >
Example 3:
<HTML>
<HEAD>
<TITLE> Guide to HTML </TITLE>
</HEAD>
<BODY>
<H1> Tags </H1>
<P> HTML uses tags to tell a browser what to do </P>
<P ALIGN= CENTER > Tags are not case sensitive </P>
</BODY>
</HTML>
List Tags
Ordered Lists
<OL>…</OL> ordered (numbered) list
<LI>…</LI> list item. </LI> is optional
We can have TYPE=X where X represents the kind of symbols that should be used in the ordered list. A for capital letters, a for small letters, I for capital roman numerals, i for small roman numerals and 1 for numbers. We can also have START=n , where n represents the initial value for this list item. The START value is always numeric and is converted automatically, according to the TYPE value.
Example 1:
<OL TYPE=A START=15>
<LI> item1 </LI>
<LI> item2 </LI>
<LI> item3 </LI>
</OL>
Unordered lists
We can have TYPE=SHAPE, where shape represents the kind of bullet that should be used with each list item. You may choose disc for a solid round bullet (the default for first level lists), circle for an empty round bullet (the default for the second level lists), or square for square bullets (the default for third and subsequent level lists). These are case sensitive .
<UL>…</UL> unnumbered list or unordered list
<LI>…</LI> list item. </LI> is optional
Example 1:
<UL><EM><FONT SIZE= " -1 " > New or improved features marked with a solid bullet.< BR> (All features may show the same bullets in some browsers.) </FONT></EM>
<LI TYPE= " circle " > Item 1 </LI>
<LI TYPE= " disc " > Item 2 </LI>
<LI TYPE= " square " > Item 3 </LI>
</UL>
Example 2:
<UL>
<LI> Item 1
<LI> Item 2
<LI> Item 3
</UL>
Creating Definition Lists
HTML provides a special tag for creating definition lists. This type of list is particularly suited to glossaries , but works well with any list that pairs a word or a phrase with a longer description. <DL>, We may enter text after the DL tag. It will appear on its own line, aligned to the left margin. <DT>, We type the word or short phrase that will be defined or explained, including any logical or physical formatting desired. <DD>, We type the definition of the term entered in the <DT>, browsers generally indent definitions on a new line below your definition term.
<DL>…</DL> definition list. <DL COMPACT> places term on same line as definition
<DT>…</DT> term. </DT> is optional
<DD>…</DD> definition. </DD> is optional
Example 3:
<DL>
<DT> Term 1</DT>
<DD> Definition of Term 1 </DD>
<DT> Term 2</DT>
<DD> Definition for Term 2</DD>
</DL>
Nested Lists
Example 1:
<UL>
<LI> Item 1
<UL>
<LI> Sub Item 1 of Item 1
<LI> Sub Item 2 of Item 1
</UL>
<LI> Item 2
<UL>
<LI> Sub Item 1 of Item 2
<LI> Sub Item 2 of Item 2
<LI> Sub Item 3 of Item 2
</UL>
<LI> Item 3
</UL>
Format Tags
Example 1:
<!-- comment -->
<P> leaves extra blank lines between paragraphs
<BR> forced line break without extra blank lines
Example 2:
<P> This produces a paragraph with extra blank lines between paragraphs.
This produces a line break without extra blank lines between lines. <BR>
This line will be directly below the last line. <BR>
HTML generally disregards spacing.
<PRE>…</PRE> recognizes preformatted text. Spaces, new lines , and tabs are recognized.
<PRE WIDTH =" 40 " >…</PRE> width gives maximum number of characters per line
Example 3:
<PRE>
C:\htmldocs\example1.htm
Location that browser can find HTML files
</PRE>
Example 4:
<BLOCKQUOTE>…</BLOCKQUOTE> for long quotations
We can use block quotes to set off a section of our text. They always start on a new line . As usual, different browsers display block quotes in different ways. Some center the text in an indented paragraph in the middle of the page, while others simply italicize the special text.
Example
<HR> produces a horizontal (rule) line
<HR SIZE =" 4 " WIDTH =" 80% " > size is thickness . width is how far across screen .
with the percentage of the document's width
<HR SIZE =" 4 " WIDTH =" 400 " > width of the rule in pixels
<HR SIZE =" 4 " WIDTH =" 100% " NOSHADE> To create a solid bar , with no shading
Physical Styles
Example 1:
<B>…</B> bold
<I>…</I> italic
To format text with a mono-spaced font:
<TT>…</TT> typewriter text
or <CODE>…</CODE> CODE is for formatting computer code in languages
like C or Perl
or <KBD>…</KBD> KBD is for formatting keyboard instructions
or <SAMP>…</SAMP> SAMP is for displaying sample text
<U>…</U> underline
<em> …</em> displays in italics
<strong> … </strong> displays in bold
<blink>…</blink> makes the text to blink ( works with NetScape )
<strike> … </strike> displays line through the text
Changing the Font
Fonts give your page more personality. We can choose exactly what fonts we'd prefer to use.
<FONT FACE= " fontname1,fontname2, … " > … </FONT> where fontname1 is your first choice of fonts.
Example 1:
<FONT FACE= " Lithos Black, Chicago, Arial " > … </FONT>
<FONT FACE= " New Century, Futura ExtraBold " > … </FONT>
<FONT FACE= " Springfield , Extra Bold " > … </FONT>
<FONT SIZE= " 4 " FACE= " Garamond Bold " COLOR= " #FF1212 " >… </FONT>
To choose a default size for body text :
<BODY>
<BASEFONT SIZE= " n " >
…
</BODY> optional closing tag for <BASEFONT>
Where n is a number from 1 to 7 . The default is 3 . BASEFONT does not affect headers .
To set the specific size of one or more characters:
<FONT SIZE =" n " >…</FONT> Where n is a number from 1 to 7 .
To make the text bigger or smaller than the surrounding text:
<BIG> Hello world! </BIG>
<SMALL> Hello world! </SMALL>
One more way to change the size of text with respect to surrounding text:
<FONT SIZE= " n " > … </FONT> we can type +n or –n to specify how much bigger or smaller than the surrounding text we want the affected text to be.
To choose a default color for text:
The TEXT attribute for the BODY tag lets you specify a default color for all of the text on the page.
<BODY TEXT = " #FF0000 " >
To change the text color:
<FONT SIZE= " 5 " FACE= " Garamond " COLOR= " red " > or we can use #rrggbb
To create superscripts or subscripts :
<P> Welcome to UOP! <SUP>1</SUP> </P>
Subscripts are perfect for writing out chemical formulas like H2O.
H <SUB> 2 </SUB> O
Escape Sequences (Character Entities) are case sensitive.
Example 3:
< escape sequence for <
> escape sequence for >
& escape sequence for &
È escape sequence for E grave accent (È)
ñ escape sequence for n tilde (ñ)
ö escape sequence for o umlaut (ö)
a non-breaking space
Linking Tags
<A HREF ="URL" >…</A> hyperlink reference anchor
Targeting links to specific Windows:
The following line opens a new blank window.
<A HREF ="C:\htmldocs\sample1.htm" TARGET =" _blank " > Text for Link </A>
The following line opens the title window:
<A HREF ="C:\htmldocs\sample1.htm" TARGET =" title " > Text for Link </A>
To set a default target for a page:
We specify a default target for all the links on a page.
In the HEAD section we type <BASE TARGET= " title " >
To create an anchor:
<A HREF =" # prog " > Programming C </A> hyperlink to section in document
<A NAME = " prog " > Programming C </A> section title in document to which
link refers
Example 1:
| <a href = " # Lecture Notes " > Lecture Notes </a> |
<center><dt><a name= " Lecture Notes " ></a><b> Lecture Notes </b></dt></ center >
Example 2:
<A HREF ="C:\htmldocs\sample1.htm # Sec1 " > Section One in Sample One </A>
inside sample1.htm document is <A NAME =" Sec1 " > Section One </A>
<A HREF =" mailto: …@host" >…</A> email hyperlink
Example 3:
<A HREF =" mailto: firstname.lastname@apollogrp.edu" > Firstname Lastname </A>
To add a keyboard shortcut to a link:
<A HREF ="story.html" ACCESSKEY =w > Story </A> (Alt-W)
Graphic Tags
<IMG SRC ="filename" > image source file
Example 1:
<IMG SRC ="myImages/picture1.gif" >
Scaling Images
<IMG SRC ="picture1.gif" HEIGHT =" 40 " WIDTH =" 60 " > define height and width of
picture
Wrapping Text around Images
We can use the ALIGN attribute (with the LEFT and RIGHT variables only) to wrap text around an image.
<IMG SRC ="picture1.gif" ALIGN = RIGHT >
<H1> The University of Phoenix </H1>
The University of Phoenix is located in the Phoenix , Arizona .
...
Aligning Images
We can align an image in various ways to a single line in a paragraph. We can align an image to TEXTTOP , TOP , MIDDLE , ABSMIDDLE , BOTTOM , or ABSBOTTOM .
TEXTTOP aligns the image with the highest text in the line.
TOP aligns the image with the highest element in the line.
MIDDLE aligns the middle of the image with the baseline .
ABSMIDDLE aligns the middle of the image with the middle of the largest item .
BOTTOM aligns the bottom of the image with the bottom of the text .
ABSBOTTOM aligns the bottom of the image with the bottom of the largest item .
Example 1:
<IMG SRC ="picture1.gif" ALIGN = TOP> aligns with the highest element in the line
<IMG SRC ="picture1.gif" ALT ="alternate text" > displays alternate text if graphic cannot be displayed
<IMG SRC ="picture1.gif" BORDER =" n "> n is the width in pixels of the border
To use images to label links:
<A HREF ="C:\htmldocs\sample1.htm" > <IMG SRC ="picture1.gif" ></A>
<A HREF ="Large.gif" ><IMG SRC ="Small.gif" ></A> clicking on small image opens large image
<IMG SRC ="picture2.jpg" >
Adding Spaces around Image
Example 1:
<IMG SRC ="picture1.gif" ALIGN = RIGHT VSPACE = 15>
<IMG SRC ="picture2.gif" ALIGN = LEFT HSPACE = 6>
Example 2:
<BODY BACKGROUND ="picture1.gif" > background is an image
<BODY BGCOLOR ="#000000" TEXT ="#FFFFFF" LINK ="#0000FF">
background will be black , text will be white , and link will be blue . FF0000 is red .
To change the Color of Links
We use LINK attribute to change the color of links that have not yet been visited.
We use VLINK attribute to change the color of links that have already been visited .
We use ALINK attribute to change the color of a link when the user clicks on it .
Example 3:
<BODY BGCOLOR =" # 000000"” TEXT =" # FFFFFF" ALINK =" # 242424"
VLINK =" # 616161" LINK =" # BABABA" >
Example 4:
<A HREF ="sound1.wav">link </A> sound file
<A HREF ="movie1.mov">link </A> QuickTime movie file
<A HREF ="movie2.mpg">link </A> mpeg movie file
HTML and Color
Hypertext Markup Language (HTML) is used to format the contents of a Web page. The colors selected for the various elements of a Web page will have a significant impact upon the use and acceptance of a Web site by the end users. In designing your Web pages, it is important to consider how the end user will see your creation. While your computer and monitor may allow you to use a pallet of millions of colors, some of the users of your Web site may only be able to view a pallet of hundreds or thousands of colors. In order for the end user to view your Web site as you created it, many experts recommend that Web sites be designed using a HTML Safe pallet of 216 colors. These colors can be rendered by virtually any computer in use today and are not affected by the users' choice of browser or operating system. Colors are defined in HTML with the use of a six-digit hexadecimal number. The Hex number is always preceded by the pound symbol (#). For example, to format the text on a Web page to appear blue, you would use the following HTML tag:
<font color=“#0000FF”>
In the latest version of HTML, sixteen colors have been given names that can be used in defining the color of a Web page element. If you used the color name, the above HTML tag would appear as:
<font color=“blue”>
If you define a color within the Head or Body or your HTML page, the hex value or the color name must be enclosed within quotation marks. If you define a color using a Cascading Style Sheet, the quotation marks are not necessary; however, the pound symbol (#) must still precede the hex value.
Attached is a chart of the HTML Safe 216 color pallet for your reference. The chart provides a sample of the colors, each color's hex value, and the color names for the eight named colors that are within the HTML Safe pallet.
__________________________________________________________________________________________________________________________
WEB Programming I
Week 2 Newsletter (E. Nikjeh)
Hello Class,
Adding Video to a Web Page
File Formats for Video
The most popular formats for the Web today are as follows:
QuickTime ( .mov ) was developed by Apple Computer. The QuickTime player and plug-in can display video in a variety of other file formats, including .avi and .mpg.
Moving Pictures Experts Group ( .mpg ) is an ISO standards group that devised the MPEG system of compressing video and animation data files. Both QuickTime and Windows Media Player can display .mpg files.
Audio-Video Interleaved ( .avi ) was developed by Microsoft and Intel as a format to store and display video files with sound. You can play .avi files using the Windows Media or QuickTime plug-in.
Embedding Video with HTML
To embed a video with HTML, we use <embed> tag as follows:
<embed src ="myVideo/family.mov" width ="320" height ="240" autoplay ="true" controller ="false" loop ="true"> </embed>
Linking Video with HTML
We use <a> tag as follows:
<a href ="myVideo/family.mov">Click here to see the video </a>
Adding Sound to a Web Page
File Formats for Sound
.aif Audio Interchange File Format
.au UNIX audio file format
.mov QuickTime format, originated by Apple, used both video and sound\
.mid MIDI file
.ram RealAudio streaming format from RealNetworks
.asf Windows Media Player format
.wav Waveform audio file format
.mp3 Audio track from MPEG-3 compression scheme
<embed src ="mySounds/test1.mov" width ="0" height="0" autoplay="true"
hidden="true" loop="true"></embed>
<a href ="mySounds/test1.mov" >Click here to hear the sound </a>
Background Sound:
<bgsound src ="images/Minuet.mid" loop="1">
We use loop = " -1 " or loop = " infinite " to play the sound over and over.
MARQUEE
The <MARQUEE> tag is used to create an area containing scrolling text. We have the following attributes for the MARQUEE tag:
BEHAVIOR = SCROLL | SLIDE | ALTERNATE
BEHAVIOR controls the behavior of the text in the marquee. SCROLL causes the text to repeatedly scroll across the page. SLIDE causes the text to slide onto the page and stop at the margin. ALTERNATE causes the text to bounce from margin to margin.
AIGN = TOP | MIDDLE | BOTTOM
DIRECTION = LEFT | RIGHT
LOOP = a digit or INFINITE
SCROLLAMOUNT = The amount of space between successive draws of the text in the marquee
SCROLLDELAY = The amount of time between scrolling actions, in milliseconds
VSPACE = The amount of space above and below the marquee in pixels
HSPACE = The amount of space to the left and right of the marquee in pixels
WIDTH = The width of the marquee, in either pixels or as a percentage of the display area
Example:
<marquee behavior ="alternate" width = " 400 " height ="30" bgcolor ="#FFCCFF">
Thank you for visiting my Website </marquee>
Table
Table Tags
<TABLE>...</TABLE> table
<CAPTION>...</CAPTION> caption for table
<TH>... </TH> table header cell
<TR>...</TR> table row
<TD> ... </TD> table data cell
Tables are made up of rows of cells . The number of cells in each row determines the table's shape.
To create a simple table:
<html>
<head><title>My Table</title>
</head>
<body>
<table>
<tr>
<td><img src="Lion.jpg" width="300" height="250" alt="Lion Picture"></td>
</tr>
<tr>
<td><font size="-1"><i>A lion is in the Los Angeles Zoo</i></font></td>
</tr>
</table>
We can create a caption for the table in opening and closing CAPTION tags. Use ALIGN =direction, where direction is top, bottom, left, or right to align the caption.
Adding a Border
A border helps separate your table from the rest of the text. So it is up to us.
To create a border:
<TABLE BORDER =” n ” > where n is the thickness in pixels of the border. The default thickness for the border is 2 pixels . To get rid of the border completely, use BORDER = 0 .
Changing the Border Color
Generally, a table's border is generated from the color of the background.
To make a solid colored border:
<TABLE BORDER =” n ” BORDERCOLOR =” #rrggbb ” > where rrggbb is the hexadecimal representation of the desired color for the border .
To make a shaded colored border:
<TABLE BORDER =”8” BORDERCOLORLIGHT =”#00FF00”
BORDERCOLORDARK =”#209030”>
We used #209030 for the darker parts of the border ( top and left borders of cells , bottom and right borders of the table itself ).
We used #00FF00 for the lighter parts of the border ( bottom and right borders of cells , top and left borders of the table itself ).
Setting the Width
A browser will automatically determine the width of your table by calculating the width of the elements and text it contains. Somehow, it always seems to add a little extra.
<TABLE WIDTH =”350” BORDER =”0”>
<TR>
<TD WIDTH =”300” ><img src =”Lion.jpg” ></TD>
</TR>
</TABLE>
Centering a table on the page:
<TABLE ALIGN =” center ” WIDTH =”300”> … </TABLE>
Adding Space around a Table
HSPACE =” h ”, where h is the number of pixels of space to add on both right and left sides of the table.
VSPACE =” h ”, where h is the number of pixels of space to add on both the top and bottom of the table.
<TABLE ALIGN =”left” WIDTH=” 300 ” HSPACE=” 20 ” VSPACE=” 15 ”>
…
</TABLE>
Spanning a Cell across Columns
With a table, it's often necessary to span one cell across a few columns.
<TABLE WIDTH=”300”>
…
<TR><TD COLSPAN=”2”></TD>
</TR>
…
</TABLE>
Spanning a Cell across Rows
Creating a cell that spans more than one row is essentially identical to spanning cells over more than one column-just from another direction.
<TABLE WIDTH=”300”>
…
<TR><TD ROWSPAN=”2”></TD>
</TR>
…
</TABLE>
Controlling Space in and Around Cells
CELLSPACING =”n”, where n is the number of pixels desired between each cell.
CELLPADDING =”n”, where n is the number of pixels desired between the contents and the walls of the cell.
<TABLE WIDTH=” 450 ” CELLSPACING=” 2 ” CELLPADDING=” 4 ”
BORDER=” 0 ”>
…
</TABLE>
Example 1:
<TABLE>
<CAPTION ALLIGN=top> Table Title </CAPTION>
<TR>
<TH>header cell 1</TH>
<TH>header cell 2 </TH>
</TR>
<TR>
<TD>row 1, cell 1</TD>
<TD>row 1, cell 2</TD>
</TR>
<TR>
<TD>row 2, cell 1</TD>
<TD>row 2, cell 2</TD>
</TR>
</TABLE>
Example 2:
<html>
<head><title>Table example</title></head>
<body>
<TABLE width="500" cellspacing="2" cellpadding="4" border="3">
<CAPTION ALLIGN=top> Table Title </CAPTION>
<TR>
<TH>header cell 1</TH>
<TH>header cell 2 </TH>
</TR>
<TR>
<TD bgcolor="yellow">row 1, cell 1</TD>
<TD>row 1, cell 2</TD>
</TR>
<TR>
<TD>row 2, cell 1</TD>
<TD>row 2, cell 2</TD>
</TR>
<TR>
<TD COLSPAN="2" width="250" ALIGN="center" VALIGN="top">This cell takes two columns</TD>
</TR>
<TR>
<TD>row 5, cell 1</TD>
<TD ROWSPAN="2" ALIGN="center" VALIGN="bottom">row 6, cell 2</TD>
</TR>
<TR>
<TD>row 7, cell 2</TD>
</TR>
</TABLE>
</body>
</html>:
Table Title |
|
header cell 1 |
header cell 2 |
row 1, cell 1 |
row 1, cell 2 |
row 2, cell 1 |
row 2, cell 2 |
This cell takes two columns |
|
row 5, cell 1 |
row 6, cell 2 |
row 7, cell 2 |
Frame
Frames partition a browser window into predefined regions so that different HTML files can be displayed inside each region. Thus a frames-based display consists of one Web page that displays multiple Web pages. Although each frame remains an independent entity, frames become even more interesting when they interact with one another. For example, Web site designers often insert hyperlinks in one frame that alter the content inside a different frame. By dividing a page, called a frameset, into frames, you allow the visitor to see more than one page at a time, without completely clutering up their screen. Each frame contains its own Web page, and theoretically could be viewd independently in a separate window. Whenever we inculde a FRAMESET element in an HTML file, we do not need a BODY element; the FRAMESET replaces the BODY .
Example 1: Frames in Rows
<html>
<head>
<title>Simple frames in Rows</title>
</head>
<frameset rows=”40,*,50”>
<frame name= "banner” src=”banner.html”>
<frame name= "photos” src=”welcomepage.html”>
<frame name= "buttons” src=”buttons.html”>
</frameset>
</html>
Example 2: Frames in Columns
<html>
<head>
<title>Simple frames in Columns</title>
</head>
<frameset cols=”100,*,80”>
<frame name= "banner” src=”banner.html”>
<frame name= "photos” src=”welcomepage.html”>
<frame name= "buttons” src=”buttons.html”>
</frameset>
</html>
Example 3: Frames in Rows and Columns
<html>
<head>
<title>four frames</title>
</head>
<frameset cols= "35%, 65%" rows= "60%, 40%" >
<frame name= " upperleft" src="one.html" >
<frame name= " upperright" src="two.html" >
<frame name= " lowerleft" src="three.html" >
<frame name= " lowerright" src="four.html" >
</frameset>
<NOFRAMES>
The information on this page is displayed in frames. Your browser can't view
frames.
</NOFRAMES>
</html>
Now we can have one.html, two.html, three.html, and four.html. e.g.
Here is one.html:
<html>
<head><title>upperleft page</title></head>
<body>
<a href="Lion.jpg" target="upperright">Lion</a>
</body>
</html>
Example 4: Nested Frames
frameborder =0 makes the sculpted borders disappear but it does not get rid of all of the space between frames. To get rid of both borders and space, use border =0 frameborder =0.
<html>
<head>
<title>Virtual Zoo</title>
</head>
<frameset rows ="20%, *" bordercolor =”#FF0000” border =”10”>
<frame src="title.html" name="title" scrolling=auto >
<frameset cols ="20%, *" >
<frame src="list.html" name="list" scrolling=no noresize >
<frame src="welcome.html" name="display" scrolling=yes noresize >
</frameset>
</frameset>
</html>
list.html is as follows:
<html>
<head>
<title>Animal List</title>
<base target ="display">
</head>
<body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000">
<a href="../images/Elephant.jpg">Elephant</a><br>
<a href="../images/Gazelle.jpg">Gazelle</a><br>
<a href="../images/Giraffe.jpg">Giraffe</a><br>
<a href="../images/Lion.jpg">Lion</a><br>
<a href="../images/PolarBear.jpg">PolarBear</a><br>
<a href="../images/Rhino.jpg">Rhino</a><br>
<a href="../images/Tiger.jpg">Tiger</a><br>
<a href="../images/Zebra.jpg">Zebra</a><br>
</body>
</html>
welcome.html is as follows:
<html>
<head>
<title>Welcome</title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000">
<p>Click an animal in the list to display its picture.</p>
</body>
</html>
title.html is as follows:
<html>
<head><title>Title Virtual Zoo</title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000">
<h1>Virtual Zoo</h1>
</body>
</html>
Targeting Links to Special Spots
We use target=_blank to have the link open in a new, blank window.
We use target=_self to open the link in the same frame that contains the link.
<a href =”welcome.html” target=_self >To see welcome page </a>
We use target=_top to open the link in the current browser window but independently of the rest of the frameset to which it currently belongs.
We use target=_parent to open the link in the frame that contains the current frameset. This will only be different from _top when you are using nested framesets.
Changing the Default Target
If a frame contains a link, the link will open up in that same frame, by default, unless you change the target as follows:
<a href=”page1.html” target=”main” > To see the introduction</a>
You can change the default target for all of the links on a page by using the base tag.
<base target ="display">
We should have the above statement above the <body> tag.
Frame Tags
<FRAMESET ROWS= “height1, height2” >…</FRAMESET>
<FRAMESET COLS= “width1, width2”>…</FRAMESET>
<FRAMESET SRC= filename>
Example
<FRAMESET ROWS= “40,*”>
<FRAME SRC= “logo.htm” name=”title”>
<FRAMESET COLS= “100.*”>
<FRAME SRC= “navigate.htm” name=”list”>
<FRAME SRC= “info.htm” name=”display”>
</FRAMESET>
</FRAMESET>
Form
All form begin with the <form> tag and end with the </form> tag. This tag pairs designate a form within an HTML document and contains all text and tags that make up a form. We can include as many forms as we like within an HTML document. However, we cannot nest one form inside another form.
Attributes of the <form> tag:
Action Specifies the URL to which form data will be submitted
Method Determines how form data will be submitted ( GET or POST )
Enctype Specifies the format of the data being submitted. The default is application/x-www-form-urlencoded. Specifies an encoding protocol known as Multipurpose Internet Mail Extension, or MIME. Encoding with MIME ensures that data does not become corrupt when transmitted acroos the Internet. Now MIME has become a standard method of exchanging files over the internet.
Target Specifies a window in which any results returned from the server appear.
Name Designate a name for the form
Text Boxes: An <input> tag with a type of text creates a simple text box that accepts a single line of text. e.g.
<input type= "text" name= "firstName" value= "David" size= 20 >
Password Boxes: An <input> tag with a type of password is similar to an <input> tag with a type of text. However, each character that a user types in a password box appears as an asterisk to hide it from anyone who may be looking over the user's shoulder. e.g.
<input type= "password" name= "myPassword" maxlength =8 >
Radio Buttons: An <input> tag with a type of radio is used to create a group of radio buttons from which we can select only one value. To create a group of radio buttons, all radio buttons in the group must have the same name attribute. Each radio button requires a value attribute. Only one checked radio button in a group creates a name=value pair when a form is submitted to a CGI (Common Gateway Interface) script. e.g.
<form action="cgi-bin/cgi_program.cgi" method="post" >
Please select your favorite type of music:<br>
<input type=" radio " name="music" value="jazz" >Jazz<br>
<input type=" radio " name="music" value="classical">Classical<br>
<input type=" radio " name="music" value="country">Country<br>
<input type=" radio " name="music" value="rock">Rock<br>
</form>
Check Boxes: An <input> tag with a type of checkbox creates a box that can be set to yes ( checked ) or no ( unchecked ). We use check boxes when we want users to select whether or not to include a certain item or to allow users to select multiple values from a list of items. e.g.
<form action="cgi-bin/cgi_program.cgi" method="post" >
<h3>Which programming languages do you know?</h3>
<input type=" checkbox " name="progLng" value="JavaScript" checked>JavaScript<br>
<input type=" checkbox " name="progLng" value="Java">Java<br>
<input type=" checkbox " name="progLng" value="VB6.0">VB6.0<br>
<input type=" checkbox " name="progLng" value="C">C language<br>
</form>
We are not required to group check boxes with the same name attribute.
Submit Buttons: An <input> tag with a type of submit creates a button that submits the form to a CGI script on a server. If we do not include a value attribute, then the default label of the submit button, Submit Query , appears. e.g.
<input type=" submit " value=" Submit The Form " name=" submitButton " >
Reset Buttons: An <input> tag with a type of reset clears all form entries and resets each form element to its initial value specified by the value attribute. e.g.
<input type=" reset " value=" Reset The Form " >
Command Buttons: An <input> tag with a type of button creates a command button similar to the OK and Cancel buttons we see in dialog boxes. e.g.
<input type=" button " name="calc" value=" Calculate " onClick= "total_sale( );">
Selection Lists: The <select> … </select> tag pair creates a selection list that presents users with fixed lists of values from which to choose. The selection list can appear as an actual list of choices or as a drop-down menu. Depending on the number of items in the list, a selection list can also include a scroll bar. e.g.
<p> where will you use this product?
<select name="location" >
<option value="work" > Work
<option value="school" > School
<option value="home" > Home
<option value="office" > Office
</select></p>
Multiline Text Fields: The <textarea> tag is used to create a field in which users can enter multiple lines of information. Fields created with the <textarea> … </textarea> tag pair is known as multiline text fields or text areas. e.g.
<p>Comments<br>
<textarea name="comments" cols=40 rows = 8 > Enter your comments here </textarea>
</p>
Form Example:
<html>
<head><title>General Form</title><head>
<body>
<h3> Billing Information</h3>
<form name="exampleForm" action="cgi-bin/cgi_example.cgi" method="post">
<b>Name</b><br>
<input type="text" name="fullName" size=50><br>
<b>Address</b><br>
<input type="text" name="address" size=50><br>
<b>City, State, Zip</b><br>
<input type="text" name="city" size=38>
<input type="text" name="state" size=2>
<input type="text" name="zip" size=5 maxlength=5><br>
<b>Credit Card</b><br>
<input type="radio" name="creditcard" checked>VISA
<input type="radio" name="creditcard">MasterCard
<input type="radio" name="creditcard">American Express<br>
<input type="radio" name="creditcard">Discover
<input type="radio" name="creditcard">Dinner Club<br>
<b>Credit card Number</b><br>
<input type="text" name="ccNo" value="xxxx xxxxxx xxxxx" size=50><br>
<b>Expiration Date</b><br>
<p><input type="text" name="expdate" value=" 5/1/03 " size=50></p>
<p>Comments<br>
<textarea cols=60 rows=10>Enter your comments here</textarea></p>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>
Form Tags
< FORM NAME= formname>…</FORM>
<INPUT TYPE=inputtype NAME=fieldname VALUE=”default data” SIZE=99>
inputtype
BUTTON
CHECKBOX
HIDDEN
IMAGE
PASSWORD
RADIO
RESET
SUBMIT
TEXT
TEXTAREA
<SELECT NAME=fieldname>…</SELECT>
<OPTION>
Example:
<html>
<head>
<title>Simple frames in Rows</title>
</head>
<body>
<FORM NAME = "address">
street:<INPUT TYPE="TEXT" NAME="street"><br>
city:<INPUT TYPE="TEXT" NAME=city SIZE="25"><br>
state:<SELECT NAME="state" SIZE="1">
<OPTION>AZ</ OPTION >
<OPTION>CA</ OPTION >
< OPTION >TX</ OPTION >
< OPTION >WA</ OPTION >
</SELECT>
<br>
zip:<INPUT TYPE="TEXT" NAME="zip" SIZE="10">
</FORM>
</body>
</html>
Meta Tags
Meta tags are invisible tags placed in the header of your HTML document that add meta, or higher level, information to your Web site. An example is the description meta tag, which you can use to write a short description of your Web site. There are two categories of meta tags: HTTP-equiv attribute meta tags and Name attribute meta tags. HTTP-equiv attribute tags are used to manipulate the browser into performing some action. The most popular of these is probably the refresh meta tag. Inserting the following code in the header of your HTML document results in the browser opening the Coca-Cola Web site after five seconds.
<meta http-equiv ="refresh" content ="5"; URL ="http://www.coke.com">
the refresh meta tag is often used to redirect an old Web site to a new location or to create an entry page for a Web site. Name attribute meta tags are used for listing information such as keywords, authors, and descriptions. This tag ensures that search engines attempting to index the Web site utilizes the listed keywords to improve the accuracy and ranking of the Web site in their search results.
<html>
<head>
<meta name =" author " content ="Esmaail Nikjeh">
<meta name =" keywords " content ="orange juice, sports drink, citrus products, gifts, holidays gifts, oranges, grapefruit">
<meta name =" description " content ="Sunny Morning Products produces Olympic Gold brand orange juice and sports drink. Check it out our Sunshine Country Store.">
<meta name =" Content-Language " content ="en-us">
<meta name =" GENERATOR " content ="Microsoft FrontPage 5.0">
<meta name =" ProgId " content ="FrontPage.Editor.Document">
<title> New Page 1 </title>
<bgsound src ="images/Minuet.mid" loop ="1">
</head>
<body background ="images/WP53196.jpg">
<p> <a name ="Top"> </a> <img border="0" src="images/SMPLogo.gif" alt="Sunny Morning Products Logo" width="380" height="64"></p>
<p align="center">| <a href="index.htm">Home</a> | <a href="WhatsNew.htm">What's New</a> |<a href="Products.htm">Products</a> | <a href="EmpPage.htm">Employment</a> | <a href="Investor.htm">Investor Relations</a> | <a href="Feedback.htm">Feedback</a> | <a href="Search.htm">Search</a> |</p>
<h3>Welcome to the Sunny Morning Products Web Site!</h3>
<p>Sunny Morning Products is an international bottler and distributor of
<font color="#FF9900"><b>Olympic Gold</b></font> orange juice and sports drink.
While the vitamins and minerals in orange juice make it a popular breakfast
choice of many people, the <font color="#FF9900"><b>Olympic</b></font>
<font color="#FF9900"><b>Gold</b></font> sports drink delivers the fluids,
electrolytes, and carbohydrate energy that the human body needs for peak
performance in athletic competition. <font color="#FF9900"><b>Olympic</b></font>
<font color="#FF9900"><b>Gold </b></font>products are sold through grocery
stores, convenience stores, and many other outlets. </p>
<p class="MsoNormal">The Sunshine Country Store, which is located at our citrus
groves in the valley, offers you the freshest produce from our groves, fresh
orange juice, and sports drinks. These products are also available for delivery
to your door for any occasion. </p>
<h3 align="center">
<marquee behavior ="alternate" bgcolor ="#C0C0C0" width ="90%">Brighten your day. Enjoy some of our sunshine ! </marquee> </h3>
<hr color="#FF9900" width="90%" size="5">
<p><i><font size="2">Last updated May 31, 2003 <br>
Copyright <font face="Times New Roman">©</font> 2003 Sunny Morning Products. All
right reserved.</font></i></p>
<h5><font size="2" face="Arial"><a href="#top">
<img src="images/Up.gif" border="0" width="16" height="16"></a>
<a href="#Top">Top of Page</a></font></h5>
</body>
</html>
__________________________________________________________________________________________________________________________
WEB Programming I
Week 3 Newsletter (E. Nikjeh)
Hello Class,
Introduction
JavaScript is a scripting language. The term scripting language refers to programming languages that are executed by an interpreter from within a Web browser . An interpreter translates programming code into an executable format each time the program runs, one line at a time. Programs written in scripting languages, such as JavaScript , are interpreted when a scripting engine loads an HTML page. A scripting engine is an interpreter that is part of the Web browser . A Web browser that contains a scripting engine to translate scripts is called a scripting host . Netscape Navigator and IE (Internet Explorer) are both examples of scripting hosts for JavaScript programs.
JavaScript was originally created by Netscape Navigator and was called LiveScript . With the release of Netscape 2.0 , the name was changed to JavaScript 1.0 . Subsequently, Microsoft released its own version of JavaScript in IE 4.0 and named it JScript . The most current versions of each implementation are JavaScript 1.5 in Netscape and JScript 5.5 , which is available for IE versions 4.0 and later.
When Microsoft released JScript, a number of major problems occurred. For example, the Netscape and Microsoft versions of the JavaScript language differed so greatly that programmers were required to write almost completely different JavaScript programs for Netscape and IE. This divergence led to the creation of an international , standardized version of JavaScript called ECMAScript (European Computer Manufacturer's association).
The most recent version of ECMAScript is edition 3 . Both Netscape JavaScript 1.5 and Microsoft JScript 5.5 conform to ECMAScript Edition 3 . Although they both conform to ECMAScript Edition 3, Netscape and IE each include their own unique programming features that are not supported by the other language.
JavaScript is available in two formats: client-side JavaScript and server-side JavaScript. There is no server-side standard similar to ECMAScript. Client-side and server-side JavaScript share the same basic programming features. JavaScript runs "100x" slower than C , as it is purely interpreted ( Java runs "10x" slower than C code).
The <script> Tag
The statements that make up a JavaScript program in an HTML document are contained between the <script> …</script> tag pairs. The <script> tag is used to notify the Web Browser that the commands that follow it need to be interpreted by a scripting engine. The language attribute of the <script> tag tells the browser which scripting language and which version of the scripting languages are being used. We include the following code in our HTML document:
<script language=" JavaScript ">
JavaScript statements;
</script>
or
<script type="text/javascript"> JavaScript statements; </script>
JavaScript is the default scripting language for most Web browsers. If you omit the language attribute from the <script> tag; your program should still run.
Microsoft's VBScript is another type of scripting language, and is based on the Visual Basic programming language. To use VBScript in our HTML document, we would use the following code:
<script language=" VBScript ">
VBScript statements
</script>
We can include JavaScript codes in the head section and in the body section .
Identifiers
The name we assign to a variable is an identifier . Identifiers must begin with an uppercase or lowercase ASCII letter , dollar sign ($), or underscore “ _ ”. We can use numbers in an identifier, but not as the first character. For example
Legal variable names: My_name, $saleValue, _myAccount, and sale130
Illegal variable names: %my_Lname, 2saleVale, and -mySale
Case Sensitivity, Optional Semicolons, and Comments
Unlike HTML, JavaScript is a case-sensitive language. For example, the “while” keyword must be typed "while", not "While" or "WHILE". Each statement in JavaScript are generally followed by semicolons (;) . However, we may omit the semicolon if each of our statements is placed on a separate line.
In JavaScript, we have two formats of comments : // and /* … */
// This is for a single-line comment.
/* This is for
several lines
comments. */
HTML comment blocks begin with <!-- and end with --> .
Example 1: <html>
<head><title>Example One</title></head>
<body>
<pre>
< script language = " JavaScript ">
<!-- Hide from incompatible browsers
document.write("<h3>Hello World</h3><br>");
document.writeln("Hello UOP");
document.writeln("Hello to my class");
// Stop hiding from incompatible browsers -->
< /script >
</pre>
<NOSCRIPT>
Your browser does not support JavaScript or JavaScript is disabled.<br>
</NOSCRIPT>
</body>
</html>
The <pre> tag is short for preformatted text. This tag pair tells a Web browser that any text and line breaks contained between the opening and closing tag are to be rendered exactly as they appear. If we don't put <pre> tag, the writeln() method cannot add a carriage return after the line of text. We display an alternate message to users of incompatible browsers with the <NOSCRIPT> … </NOSCRIPT> tag pair.
JavaScript Source File
We can save JavaScript code in an external file called a source file . A JavaScript source file is usually designated with the file extension .js and contains JavaScript statements; it does not contain the <script> … </script> tag pair. JavaScript source files cannot include HTML tags. We use the SRC attribute of the <script> tag to access JavaScript code that is saved in an external file. The SRC attribute accepts a text string that specifies the URL or directory location of a JavaScript source file.
Example 2:
<html>
<head><title>Using a source file for JavaScript</title>
<script language="JavaScript" SRC="c:\javafiles\example2_Text.js">
</script>
</head>
<body>
</body>
</html>
In the source file, we have:
// Esmaail M Nikjeh
// Date: 09-16-2002
document.writeln("This line is created using a JavaScript source file.");
document.writeln("Hello to WEB/410 class at UOP”);
We save it as example2_Text .js.
Variables
The values stored in computer memory locations are called variables . Data contained in a specific variable often change. In JavaScript, we use the reserved keyword var to create variables. Reserved words (keywords) cannot be used for variable names. e.g.
var firstName;
var total;
var name1, name2, mySale;
We can assign a value to a variable at declaration. e.g.
var name="David";
var discount = 75;
var saleValue = 546.65;
Data Types
Variables can contain many different kinds of values e.g the time of day, a dollar amount, or a person's name. A data type is the specific category of information that a variable contains. Data types that can be assigned only a single value are called primitive types . JavaScript supports five primitive data types: integer numbers (positive or negative number with no decimal places and can range from -9007199254740990(-2 to power 53) to 9007199254740990(2 to power 53) e.g. 325), floating-point numbers ( a number with decimal places or is written using exponential notation e.g. 45.75), strings (A string is a sequence of zero or more characters enclosed within single or double quotes( ' or " ) e.g. "Hello world"), Boolean values ( true or false ), and the null value (An empty value, the variable does not contain a value). JavaScript includes a typeof() operator that we can use to determine the data type of a variable. e.g.
var myVariable = 6.75;
document.write ("The data type of the variable is " + typeof (myVariable));
Programming languages that do not require you to declare the data types of variables are called loosely typed programming languages.
Dates
JavaScript's Date object provides methods for date and time manipulations. Date and time processing can be performed based on the computer's local time zone or based on World Time Standard's Universal Time Coordinated ( UTC )- formerly called Greenwich Mean Time (GMT). Most methods of the Date object have a local time zone and a UTC version. Some of the methods of the Date object are:
getDate( ) Returns a number from 1 to 31 (the day of the month in local time)
getDay( ) Return a number from 0 (Sun) to 6 (Sat) (day of the week in local time)
getFullYear( ) or getYear( ) Returns the year as a four-digit number in local time
getHours( ) Returns a number from 0 to 23 representing hours since midnight in local
getMilliseconds( ) Returns a number from 0 to 999, number of milliseconds in local time
getMinutes( ) Returns a number from 0 to 59 (minutes for the time in local time)
getMonth( ) Returns a number from 0(Jan.) to 11(Dec.)
getSeconds( ) Returns a number from 0 to 59 (seconds for the time in local time)
getTime( ) Returns the number of milliseconds between January 1, 1970 and the time
in the Date object
We can use set methods for Date to set the time values. Instead get , we have set e.g. setDate( ), setDay( ), setFullYear( ), setHours( ), setMilliseconds( ), setMinutes( ), setMonth( ), and setSeconds( )
For UTC time, we put UTC after get or set method e.g. getUTCDate( ).
toLocaleString( ) , returns a string representation of the date and time in a form specific to the computer's local e.g. May 27, 2002 at 3:42:22 PM is represented as 05/27/02 15:47:22 in the United States and 27/05/02 15:47:22 in Europe.
toString( ) Returns a string representation of the date and time in a form specific to the locale of the computer (Mon Sep 29 15:47:22 EDT 2002 in the United States ).
To create a date and time variable, use the following JavaScript command:
var myDate = new Date("month, day, year, hours:minutes:seconds");
or
var myDate = new Date(year, month, day, hours, minutes, seconds);
e.g. myDate = new Date(" April, 4, 2002 , 16:40:21 ");
or myDate = new Date(2002, 3, 4, 16, 40, 21);
Use the following command to return the current date and time:
var myDate = new Date();
Example:
var current = new Date( );
document.writeln("Today's date and time is " + current.toLocaleString( ));
Expression
Variables and data become most useful when you use them in an expression. An expression is a combination of literal values, variables, operators, and other expressions that can be evaluated by the JavaScript interpreter to produce a result. The JavaScript interpreter recognizes the literal values and variables as expressions. We can use operands and operators to create more complex expressions. Operands are variables and literals contained in an expression. Operators are symbols used in expressions to manipulate operands. e.g.
Literal and variable expressions: employee_number
3.156
Expression: myNumber = 120;
totalSale = saleValue + saleValue*tax;
Operators
In JavaScript, we have different types of operator as Follows:
Arithmetic Operators: Used for performing mathematical calculations
Arithmetic binary operators: + (addition) - (subtraction)
* (multiplication) / (division) % (modulus)
e.g. x = 7;
y = 4;
result = x % y; // result changes to 3(remainder of dividing x by y)
Arithmetic unary operators: ++ (increment) -- (decrement) - (negation)
Assignment Operators: Assigns values to variables
= += -= *= /= %=
e.g. var x, y;
x = "Hello ";
x += "World"; // x changes to "Hello World"
e.g. x = "ten";
y = 7;
x *= y; // x changes to NaN
The value NaN stands for Not a Number and is returned when a mathematical operation does not result in a numerical value.
Comparison Operators: Compares operands and returns a Boolean value
= = (equal) Returns true if the operands are equal
= = = (strict equal) Returns true if the operands are equal and of the same type
!= (not equal) Returns true if the operands are not equal
!= = (strict not equal) Returns true if the operands are not equal or not of the same type
> (greater than) Returns true if the left operand is greater than the right operand
< (less than) Returns true if the left operand is less than the right operand
>= (greater than or equal) true if the left operand is greater than or equal to right operand
<= (less than or equal) true if the left operand is greater than or equal to right operand
Logical Operators: Used for performing Boolean operations on Boolean operands
&& (and) Returns true if both the left operand and right operand return a value of true, otherwise it returns a value of false.
|| (or) Returns true if either the left operand or right operand returns a value of true. If neither operand returns a value of true, then the expression containing the || (or) operator returns a value of false.
! (not) Returns true if an expression is false and returns false if an expression is true.
Operator Precedence: Operator precedence is the order of priority in which operations in an expression are evaluated. Expressions are evaluated on a left-to-right basis with the highest priority precedence evaluated first. The order of precedence for JavaScript operators is as follows:
Parentheses/brackets/dot ( ( ) [] . ) highest precedence
Negation/increment ( ! - ++ -- typeof void )
Multiplication/division/modulus ( * / % )
Addition/subtraction ( + - )
Comparison ( < <= > >= )
Equality ( = = != )
Logical and ( && )
Logical or ( || )
Assignment operators ( = += -= *= /= %= )
Comma ( , ) lowest precedence
Functions
Individual statements used in a computer program are often grouped into logical units called procedures. In JavaScript, procedures are called functions. A function allows you to treat a related group of JavaScript statements as a single unit. Functions, like all JavaScript code, must exist within the <script> … </script> tag pair. Before we use a function in a JavaScript program, we must first create, or define, it. The lines that compose a function within an HTML document are called the function definition . The syntax for defining a function is:
function name_of_function( parameters ) {
Statements;
}
A parameter is a variable that will be used within a function. Functions are not required to contain parameters. A function definition does not execute automatically. To execute a function, we must invoke, or call, it from elsewhere in our program. To call a function, we include the function name followed by parentheses containing any variables or values to be assigned to the function arguments. Always create functions within the <head> section, and place calls to a function within the <body> section. The <head> section of an HTML document is always rendered before the <body> section. Placing functions in the <head> section and function calls in the <body> section ensures that functions will be created before they are actually called. If our program does attempt to call a function before it has been created, we will receive an error.
Function_example1:
<html>
<head><title>Two Functions Program</title>
<script language="JavaScript">
<!-- Hide from incompatible browsers
function first_message(myMessage) {
document.writeln(myMessage+"<br>");
}
function return_message() {
return "This message was returned from a function.";
}
// Stop hiding from incompatible browsers -->
</script>
</head>
<body>
<script language="JavaScript">
first_message("This text was printed from a function");
var second_message = return_message();
document.writeln(second_message);
</script>
</body></html>
Function_example2:
<html>
<head><title>Two Functions Program</title>
<script language="JavaScript">
function welcome(name) {
alert("Hi " + name + "!");
document.write("<h1>Welcome " + name + "! </h1>");
}
</script>
</head>
<body>
<script language="JavaScript">
var myName = prompt("What is your name?","Enter your name here!");
welcome(myName);
</script>
</body>
</html>
Some of the Built-in JavaScript functions:
eval( ) Evaluates expression contained within strings
parseInt( ) Converts string literals to integers
parseFloat( ) Converts string literals to floating-point numbers
How to get the data from the user and to convert to numeric value:
We need to declare two variables one for string value and the other one for numeric value. The data type of the value of the input box (in the prompt pop up window) is string. So we need to convert to the integer or floating point number. We do this using the parseInt (to convert the string to numeric integer), and parseFloat (to convert the string to numeric floating point). Example:
<script language=”JavaScript”>
var firstNumber, number1; // we declare two variables for entering the first number
var secondNumber, number2; // we declare two variables for entering the second number
// to get the first number from the user
firstNumber = prompt (“Enter the first number”, “0”);
number1 = parseInt (firstNumber); // to convert string to integer number
// to get the second number from the user
secondNumber = prompt (“Enter the second number”, “0”);
number2 = parseFloat (secondNumber); // to convert string to floating point number
</script>
Arrays
An array is a group of memory locations that all have the same name and normally are of the same type (although this attribute is not required). We use arrays when we want to store groups or lists of related information in a single, easily managed location. Arrays are represented in JavaScript by the Array object, which contains a constructor function named Array( ). We create new arrays by using the new keyword and the Array( ) constructor function is as follows:
var c = new Array(12); // To allocate 12 elements for integer array c
or
var c;
c = new Array(12); // To allocate 12 elements for integer array c
The length of array c is 12 and is determined by the following expression:
c.length
There are two ways in which the initial values can be specified. The statement
var n = [10, 20, 30, 40, 50];
uses a comma-separated initializer list enclosed in square brackets ( [ and ] ) to create a five element Array with subscripts of 0, 1, 2, 3, and 4. The array size is determined by the number of values in the initializer list. Note that the preceding declaration does not require the new operator to create the Array object. The statement
var m = new Array( 75, 6.45, "Hello", true, false);
Also creates a five-element array with subscripts of 0, 1, 2, 3, and 4.
m[0] = 75 m[1] = 6.45 m[2] = "Hello" m[3] = true m[4] = false
We can have different data types in an array. So JavaScript is loosely typed language.
Loops
A loop statement repeatedly executes a statement or a series of statements while a specific condition is true or until a specific condition becomes true.
while statement is used for repeating a statement or series of statements as long as a given conditional expression evaluates to true . The syntax for the while statement is as follows:
while ( conditional expression ) {
statement(s);
}
Example 1: var count = 1;
while ( count <= 5 ) {
document.write(count + "<br>");
++count;
}
document.write("You have printed 5 numbers.");
The do … while statement executes a statement or statements once; then repeats the execution as long as a given conditional expression evaluates to true.
The syntax for do … while statement is as follows:
do {
statement(s);
} while ( conditional expression ) ;
Example 2: var count = 2;
do {
document.write("The count is equal to " + count + "<br>");
++count;
} while ( count < 2 );
The for statement is used for repeating a statement or series of statements as long as a given conditional expression evaluates to true . The syntax of the for statement is as follows:
for (initialization expression ; condition ; update statement) {
statement(s);
}
Example: var fastFoods = new Array ("pizza", "burgers", "french fries","tacos");
for (var count = 0; count < fastFoods .length ; ++count) {
document.write(fastFoods[count] + "<br>");
}
Conditional Statements
The process of determining the order in which statements execute in a program is called decision making or flow control .
The if statement is used to execute specific programming code if the evaluation of a conditional expression returns a value of true . The syntax for if statement is as follows:
if ( conditional expression ) {
statement(s);
}
Example 1: var myNumber = 5;
if (myNumber ==5 ) {
document.write("The condition evaluates to true.<br>");
document.write("myNumber is equal to " + myNumber);
}
When using an if statement, you can include an else clause to run an alternate set of code if the conditional expression evaluated by the if statement returns a value of false . An if statement that includes an else clause is called an if … else statement. The syntax for an if … else statement is as follows:
if ( condition ) {
statement(s);
}
else {
statement(s);
}
Example 2: var today = "Tuesday";
if (today == "Monday") // we don't need "{" and "}" for one statement
document.write("Today is Monday");
else
document.write("Today is not Monday");
An if statement contained within an if or if … else statement is called a nested if statement. Similarly, an if … else statement contained within an if or if … else statement is called a nested if … else statement.
switch Statements: The switch statement controls program flow by executing a specific set of statements, depending on the value of an expression. The syntax for the switch statement is as follows:
switch ( expression ) {
case value1 : statement(s) ;
break;
case value2 : statement(s) ;
break;
…
default: statement(s) ;
}
Example: var country = " Germany ";
switch ( country ) {
case " Spain " : document.write("Buenos Dias");
break;
case " Germany " : document.write("Guten Tag");
break;
case " Italy " : document.write("Buon Giorno");
break;
case " France " : document.write("Bonjour");
break;
default: document.write("I don't speak your language");
}
JavaScript Objects
Window
The window object includes several properties that contain information about Web browser window. For instance, the status property contains information displayed in a Web browser's status bar. Methods of the Window object we have already used include the alert(), confirm(), and prompt() methods used for displaying dialog boxes.
Window object properties: defaultStatus, document, frames[], history, location, navigator, opener, parent, self, status, top, window, and name.
Window object methods: alert(), blur(), clearInterval(), clearTimeout(), close(), confirm(), focus(), open(), prompt(), setInterval(), and setTimeout().
Opening and closing Windows: We can open a new Web browser window using the open() method of the Window object. The syntax for the open() method is
window.open("URL", "name", options);
The URL argument represents the Web address or filename to be opened. The name argument is used to assign a value to the name property of the new Window object. The options argument represents a string that allows you to customize the new Web browser window's appearance.
open() method options: directories, height, location, menubar, resizable, scrollbars, status, toolbar, and width. Example:
<html>
<head>
<script language="JavaScript">
<!-- hide from …
window.open("", "targetWindow"); // "" is new browser window (blank page)
self.focus(); // returns focus to the original Web browser window
// stop hide … -->
</script>
</head>
<body>
<a href=" http://www.yahoo.com " target="targetWindow">
Visit the Yahoo home page.</a>
</body>
</html>
Example: window.open("PolarBear.html", "PolarBear", "height=350, width=320,
Scrollbars=yes");
Location Object
When we want to allow users to open one Web page from within another Web page, we usually create a hypertext link with the <a> tag. We can also use JavaScript code and the Location object to open Web pages. The Location object allows us to change to a new Web page from within JavaScript code. One reason we may want to change Web pages with JavaScript code is to redirect our Web site visitors to a different or updated URL.
Location object methods:
assign() Loads a new HTML document
reload() Causes the page that currently appears in the Web browser to open again
replace() Replaces the currently loaded URL with a different one
Examples: location.assign (" http://www.yahoo.com "); This is equivalent to the following statement :
location.href=" http://www.yahoo.com ";
location.reload(); // It is like Refresh button (IE) or Reload button (Netscape)
History Object
The history object maintains a history list of all the documents that have been opened during the current Web browser session. Each Web browser window and frame , regardless of how many windows and frames we have opened , contains its own internal History object.
History object methods:
Back( ) The equivalent of clicking a Web browser's Back button
Forward( ) The equivalent of clicking a Web browser's Forward button
Go( ) Opens a specific document in the history list
Example:
<!-- SiteNavigator.html -->
<html>
<head><title>Site Navigator</title>
</head>
<frameset rows="75%, 25%">
<frame src="" name="main">
<frame src="Controls.html" name="controls">
</frameset>
</html>
<!-- Controls.html -->
<html>
<head><title>Controls</title></head>
<body>
<form name="myform">
URL Address:
<input type="text" name="newURL">
<input type="button" name="goto" value=" Go To "
onClick="parent.main.location.href=document.myform.newURL.value;">
<input type="button" name="next" value=" Next URL "
onClick="parent.main.history.forward();">
<input type="button" name="previous" value=" Previous URL "
onClick="parent.main.history.back();">
</form>
</body>
</html>
The go() method is used for navigating to a specific Web page that has been previously visited. e.g. history.go(-2); opens the Web page that is two pages back in the history list; the statement history.go(3); opens the Web page that is three pages forward in the history list.
Alert("You have visited " + history.length + " Web pages.");
Navigator Object
The Navigator object is used to obtain information about the current Web browser. The Navigator object gets its name from Netscape Navigator, but is also supported by Internet Explorer.
Navigator properties: appCodeName The Web browser code name
appName The Web bowser name
appVersion The Web browser version
platform The operating system in use
userAgent The string stored in the HTTP user-agent request header, which contains information about the browser, the platform name, and compatibility
Example 1: with (navigator) {
document.writeln("Browser code name: " + appCodeName);
document.writeln("Web browser name: " + appName);
document.writeln("Web browser version: " + appVersion);
document.writeln("Operating platform: " + platform);
document.writeln("User agent: " + userAgent);
}
Example 2: <html>
<head><title>Navigator Properties</title>
</head>
<body>
<pre>
<script language="JavaScript">
<!-- Hide …
for (prop in navigator) {
document.writeln(prop + ": " + navigator[prop]);
}
// Stop hide … -->
</script>
</pre>
</body>
</html>
![]() |
» About ![]() » Lessons ![]() » News Letter ![]() » UOP ![]() |
|