Вы находитесь на странице: 1из 59

HTML:

when type a url what happened?


1. browser checks cache; if requested object is in cache and is fresh, skip to #9
2. browser asks OS for server's IP address
3. OS makes a DNS lookup and replies the IP address to the browser
4. browser opens a TCP connection to server (this step is much more complex with HTTPS)
5. browser sends the HTTP request through TCP connection
6. browser receives HTTP response and may close the TCP connection, or reuse it for another request
7. browser checks if the response is a redirect (3xx result status codes), authorization request (401),
error (4xx and 5xx), etc.; these are handled differently from normal responses (2xx)
8. if cacheable, response is stored in cache
9. browser decodes response (e.g. if it's gzipped)
10. browser determines what to do with response (e.g. is it a HTML page, is it an image, is it a sound
clip?)
11. browser renders response, or offers a download dialog for unrecognized types
How to create nest tables within tables in HTML?
We can create nest table i.e. table inside a table. To create table we use following attributes:
<table></table>: declare starting and ending of table.
<tr></tr>: declare table row.
<td></td>: table data.
<table>
<tr>
<td>first cell of the outer table</td>
<td>second cell of the outer table,
creating second table inside the first table
<table>
<tr>
<td>first cell of the second table</td>
<td>second cell of the second table</td>
</tr>
</table>
</td>
</tr>
</table>
Explain Non Breaking space in HTML.
When we add many spaces in the content then HTML remove all space except one space this is Non Breaking
Space. To overcome this problem we use &nbsp. Suppose we want to add 3 space between two words then we
have to use &nbsp three time.
How do I link to a location in the middle of an HTML document?
Link to the labeled destination: we can link with the destination in the same URL page and with Different URL
page.
Same URL: <a href="#Destination"> Visit to destination</a> or
Different URL: <a href="thesis.html#section2">go to Section 2 of my thesis</a>
How to create a button which acts like a link?
To create buttons which act as a hyperlink, there are two ways:
<FORM ACTION="[url]" METHOD=get>
<INPUT TYPE=submit VALUE="Text on button">
</FORM>
<INPUT TYPE="submit" VALUE="Go to my link location"
ONCLICK=" http://www.careerride.com/;" />
What is difference between HTML and XHTML?
The differences between HTML and XHTML are:
HTML is application of Standard Generalized Markup Language(SGML) whereas XML is application of
Extensible Markup Language(XML).
HTML is a static Web Page whereas XHTML is dynamic Web Page.
HTML allows programmer to perform changes in the tags and use attribute minimization whereas
XHTML when user need a new markup tag then user can define it in this.
HTML is about displaying information whereas XHTML is about describing the information
How many types CSS can be include in HTML?
There are three ways to include the CSS with HTML:
Inline CSS: it is used when only small context is to be styled. To use inline styles add the style attribute in
the relevant tag.
External Style Sheet: is used when the style is applied to many pages. 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>
Internal Style Sheet: is used when a single document has a unique style. Internal styles sheet needs to put
in the head section of an HTML page, 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>
What are logical and physical tags in HTML?
Logical tags are used to tell the meaning of the enclosed text. The example of the logical tag is <strong> </strong>
tag. When we enclosed text in strong tag then it tell the browser that enclosed text is more important than other
text.
Physical text are used to tell the browser that how to display the text enclosed in the physical tag.
Some example of the physical tags are: <b> , <big> , <i>
<i> Defines a part of text in an alternate voice or mood
<em> Defines emphasized text
<b> Defines bold text
<strong> Defines important text
Explain marquee tag.
Marquee tag: Marquee tag is used when we want that some text or content move in the web page whether
horizontally or vertically.
Syntax of Marquee tag: <marquee>move text</marquee>
Attribute of Marquee tag are: bgcolor, direction, height, width, vspace etc.
A marquee allows you to put a scrolling text in a web page. To do this, place whatever text you want to appear
scrolling within the <marquee> and </marquee> tags.
How do I add midi music to my web page?
We can add midi Music in our HTML web page using following tag:
<bgsound src="music.mid" loop="1">
Attribute LOOP= 1: shows that music.mid is played only for one time. We can also set the value of loop to
infinite. This tag is supported by Netscape and Internet Explorer.
Example: <embed src="canyon.mid" Autostart=TRUE Width=145 Height=60 Loop=true>
Explain various HTML list tags.
In HTML we can list the element in two ways:
Ordered list: in this list item are marked with numbers.
Syntax: <ol>
<li> first item </li>
<li>second item </li> </ol>
Display as:
1. First item
2. Second item.
Unordered Lists: in this item are marked with bullets.
Syntax: <ul>
<li> first item </li>
<li>second item </li> </ul>
Display as:
-First item
-Second item.
Explain HTML background.
There are two types of background in HTML:
Colored Background: in this the background of the html is colored.
The Syntax is: <body bgcolor = red>
The value of the bgcolor can be set in three ways by hexadecimal number, an RGB value and Color name.
Example: <body bgcolor = black>
<body bgcolor = rgb(0,0,0)>
<body bgcolor = #000000>
Image Background: in this we set the background of the website by an image. Syntax used for this is :
<body background=study.gif>
What is CSS?
By using CSS with HTML we can change the look of the web page by changing the font size and color of the
font. CSS plays an important role in building the website. Well written CSS file can be used to change the
presentation of each web page. By including only one CSS file. It gives web site developer and user more control
over the web pages.
What is difference between HTML and HTML5?
The differences between HTML and HTML5 are:
Document of HTML is very large as compare to the HTML5.
Audio and Video tags are not present in HTML whereas HTML5 contains audio and video tags.
Vector technology is not integral part of HTML whereas HTML5 Vector technology is integral part of it.
HTML supported by all old browsers whereas HTML5 is supported by new browser.
In HTML web sockets are not available whereas in HTML5 Full duplex communication channel is
present.
How to insert Javascript in HTML?
We can insert JavaScript in HTML using <Script tag>. JavaScript can be enclosed in <script type =
text/javascript> and ending with </script>.
<html>
<body>
<script type="text/javascript">
....
</script>
</body>
</html>
What is the Use of SPAN in HTML and give one example?
SPAN: Used for the following things:
Highlight the any color text
For adding colored text
For adding background image to text.
<p>
<span style="color:#000000;">
In this page we use span.
</span>
</p>
URL: Uniform Resource Locator; an address that specifies the location of a file on the Internet.
Following is how the basic HTML layout:
<html>
<head><title>Title of page</title></head>
<body>This is my first homepage. <b>This text is bold</b></body>
</html>
What is tag?
In HTML, a tag tells the browser what to do. When you write an HTML page, you enter tags for many reasons --
to change the appearance of text, to show a graphic, or to make a link to another page.
HTML- What are the various text formatting tag in HTML?
<b>: Defines bold text
<br>: Inserts a single line break
<center>: Deprecated. Defines centered text
<em>: Defines emphasized text
<hr>: Defines a horizontal rule
<i>: Defines italic text
<p>: Defines a paragraph
<u>: Deprecated. Defines underlined text
<a>: The <a> tag defines an anchor. It can be used to create a link to another document by using the href attribute
or to create a bookmark inside a document, by using the name or id attribute.
<meta>: <meta> element provides meta-information about your page, such as descriptions and keywords for
search engines and refresh rates. <meta> tags always goes inside the <head> element. Metadata is always passed
as name/value pairs.
e.g: <head>
<meta name="description" content="Free Web tutorials">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="Stle Refsnes">
<meta charset="UTF-8">
</head>
What is image mapping in HTML?
Making one image link to several pages is called as image mapping.
For example, if you have a map of India , then clicking on a state can take to to another page and likewise for
other states.
How to read and write a file using javascript?
There are two ways to do it:
1. Using JavaScript extensions (runs from JavaScript Editor), or
2. Using a web page and ActiveX objects (Internet Explorer only)
In JavaScript Extensions, you can use:
fh = fopen(getScriptPath(), 0); to open a file
Using ActiveX objects, following should be included in your code to read a file:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.OpenTextFile("C:\\example.txt", 1, true);
How to upload file in web browser?
These things are necessary for Web-based uploads:
* An HTTP server that accepts uploads.
* Access to the /cgi-bin/ to put the receiving script. Prewritten CGI file-upload scripts are available.
* A form implemented something like this:
<form method="post" enctype="multipart/form-data" action="fup.cgi">
File to upload: <input type=file name=upfile><br>
Notes about the file: <input type=text name=note><br>
<input type=submit value=Press> to upload the file!
</form>
Is it possible to make the HTML source not viewable?
In short, there is no real method or script for making standard HTML source code not viewable.
You may consider doing any of the below if they are concerned about your source code.
1. Create the web page in Macromedia Flash or a similar program.
The visitor would need to download the Macromedia Flash plug-in and would be unable to view the source code
for the flash applet.
2. There are various scripts that will disable the right click feature, preventing the user from saving images or
viewing the source.
However, this will not protect the source code of your page.
For example, Internet Explorer users may still click "View" and "Source" to view the source code of the page, or a
user could disable scripts and images can be saved by simply saving the web page to the hard drive.
3. There are several programs that will help scramble your code, making it difficult (not impossible) to read.
Again, this is not going to prevent someone from viewing your code.
Difference bw GET and POST method:
GET method characters were restricted only to 256 characters.But in the case of POST method characters were
not restricted.
Get method will be visible to the user as it sended appended to the URL, put Post will not be visible as it is sent
encapsulated within the HTTP request body.
Get method you can only use text as it sent as a string appended with the URL, but with post is can text or binary.
How do I rename all the files from .htm to .html after copying them from a PC to a UNIX machine?
UNIX's mv (`move') command won't handle wildcard filenames.
However, there's a program called htmaddl (for `HTM-add-"L"'), so you can login and type htmaddl.
This will rename all .htm files to .html If you haven't got this program on your UNIX machine, you can type it
into a file called htmaddl:
#! /bin/sh for f in *.htm;
do base=`basename
$f .htm` mv $f $base.html
After saving it and exiting your editor, make it executable by typing the command chmod ugo+x htmaddl Best of
all, move it into your ~/bin directory, or ask your WebMeister to put it in /usr/local/bin so everyone can use it.
How to transferring user to new web page automatically?
You will need to use the below meta tag.
<meta http-equiv="Refresh" content="2" ;="" url="http://www.yourname.com">
Placing the above tag in your will load yousite.com in 2 seconds.
Changing the 2 value on CONTENT="2" to another value will increase or decrease the delay until loading the
new page.
Why does the browser show my plain HTML source?
If Microsoft Internet Explorer displays your document normally, but other browsers display your plain HTML
source, then most likely your web server is sending the document with the MIME type "text/plain".
Your web server needs to be configured to send that filename with the MIME type "text/html".
Often, using the filename extension ".html" or ".htm" is all that is necessary.
If you are seeing this behavior while viewing your HTML documents on your local Windows filesystem, then
your text editor may have added a ".txt" filename extension automatically.
You should rename filename.html.txt to filename.html so that Windows will treat the file as an HTML document.
Can I prevent a form from being submitted again?
No. The server-side program that processes the form submission must handle duplicate submissions gracefully.
You could generate the form with a server-side program that adds a hidden field with a unique session ID.
Then the server-side program that processes the form submission can check the session ID against a list of
previously used session IDs.
If the session ID has already been used, then an appropriate action can be taken (e.g., reject the submission, or
update the previously submitted data). Ultimately, your server-side program must be smart enough to handle
resubmitted data. But you can avoid getting resubmitted data by not expiring the confirmation page from form
submissions.
Since you want to expire pages quickly when they have transient data, you might want to avoid putting transient
data on the confirmation page. You could provide a link to a database query that returns transient data though.
What is a Hypertext link?
A hypertext link is a special tag that links one page to another page or resource. If you click the link, the browser
jumps to the link's destination.
What is a DOCTYPE? Which one do I use?
According to HTML standards, each HTML document begins with a DOCTYPE declaration that specifies which
version of HTML the document uses.
Originally, the DOCTYPE declaration was used only by SGML-based tools like HTML validators, which needed
to determine which version of HTML a document used (or claimed to use).
How do I create frames? What is a frameset?
Frames allow an author to divide a browser window into multiple (rectangular) regions.
Multiple documents can be displayed in a single window, each within its own frame.
Graphical browsers allow these frames to be scrolled independently of each other, and links can update the
document displayed in one frame without affecting the others.
You can't just "add frames" to an existing document. Rather, you must create a frameset document that defines a
particular combination of frames, and then display your content documents inside those frames.
When is it appropriate to use frames?
Frames can make navigating a site much easier. If the main links to the site are located in a frame that appears at
the top or along the edge of the browser, the content for those links can be displayed in the remainder of the
browser window.
Can I have two or more actions in the same form?
No. A form must have exactly one action. However, the server-side (e.g., CGI) program that processes your form
submissions can perform any number of tasks (e.g., updating a database, sending email, logging a transaction) in
response to a single form submission.
How do I create a link that sends me email?
Use a mailto link, for example, send me email at:
<A HREF="mailto:me@mydomain.com">me@mydomain.com</A>
What is image map?
Image map lets you link to many different web pages using a single image. You can define shapes in images that
you want to make part of an image mapping.
e.g: <area>: Defines a clickable area inside an image-map
<p>Click on the sun or on one of the planets to watch it closer:</p>
<img src="planets.gif" width="145" height="126" alt="Planets"
usemap="#planetmap">
<map name="planetmap">
<area shape="rect" coords="0,0,82,126" alt="Sun" href="sun.htm">
<area shape="circle" coords="90,58,3" alt="Mercury"
href="mercur.htm">
<area shape="circle" coords="124,58,8" alt="Venus"
href="venus.htm">
</map>
Click on the sun or on one of the planets
to watch it closer:

in a table the persons name is in lower case "abc" and is there any SQL query to obtain that persons name
as "ABC" as an output?
SELECT UPPER(name) FROMTABLE;
How do you make a picture into a background image of a web page?
<body background = image.gif>
Do <th> tags always need to come at the start of a row or column?
Any <tr> tag can be changed to a <th> tag. This causes the text contained within the <th> tag to be displayed as
bold in the browser. Although <th> tags are mainly used for headings, they do not need to be used exclusively for
headings.
<table border="1">
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
What are applets?
Applets are small programs that can be embedded within web pages to perform some specific functionality, such
as computations, animations, and information processing. Applets are written using the Java language.
HTML Attributes Reference
Below is a list of some attributes that can be used on any HTML element:
Attribute Description
class Specifies one or more classnames for an element (refers to a class in a style sheet)
id Specifies a unique id for an element
style Specifies an inline CSS style for an element
title Specifies extra information about an element (displayed as a tool tip)
<hr>
The <hr>tag creates a horizontal line in an HTML page. The hr element can be used to separate content:
<p>This is a paragraph.</p>
<hr>
display as:
This is a paragraph.
<br>:
Use the <br> tag if you want a line break (a new line) without starting a new paragraph: The <br> element is an
empty HTML element. It has no end tag.
<p>This is<br>a para<br>graph with line breaks</p>
display as:
This is
a para
graph with line breaks
<b>, <strong>, <i>, <em>, <code>, <sub>, <sup> tags:
example:
<p><b>This text is bold</b></p>
<p><strong>This text is strong</strong></p>
<p><i>This text is italic</i></p>
<p><em>This text is emphasized</em></p>
<p><code>This is computer output</code></p>
<p>This is<sub> subscript</sub> and <sup>superscript</sup></p>
display as:
This text is bold
This text is strong
This text is italic
This text is emphasized
This is computer output
This is
subscript
and
superscript
Tag Description
<b> Defines bold text
<em> Defines emphasized text
<i> Defines a part of text in an alternate voice or mood
<small> Defines smaller text
<strong> Defines important text
<sub> Defines subscripted text
<sup> Defines superscripted text
<ins> Defines inserted text
<del> Defines deleted text
HTML "Computer Output" Tags
Tag Description
<code> Defines computer code text
<kbd> Defines keyboard text
<samp> Defines sample computer code
<var> Defines a variable
<pre> Defines preformatted text
HTML Citations, Quotations, and Definition Tags
Tag Description
<abbr> Defines an abbreviation or acronym
<address> Defines contact information for the author/owner of a document
<bdo> Defines the text direction
<blockquote> Defines a section that is quoted from another source
<q> Defines an inline (short) quotation
<cite> Defines the title of a work
<dfn> Defines a definition term
<p>The <abbr title="World Health Organization">WHO</abbr> was founded in 1948.</p>
Display as: WHO was founded in 1948. (when put cursor at WHO, shows 'World Health Organization')
address example:
<address> Written by W3Schools.com<br>
<a href="mailto:us@example.org">Email us</a><br>
Address: Box 564, Disneyland<br>
Phone: +12 34 56 78</address>
Written by W3Schools.com
Email us
Address: Box 564, Disneyland
Phone: +12 34 56 78
<pre> tag example:
<pre>
for i = 1 to 10
print i
next i
</pre>
for i = 1 to 10
print i
next i
If your browser supports bi-directional override (bdo), the next line will be written from the right to the left (rtl):
<bdo dir="rtl">Here is some Hebrew text</bdo> Here is some Hebrew text
Quote tag:
<p>WWF's goal is to:<q>Build a future where people
live in harmony with nature.</q>We hope they
succeed.</p>
WWF's goal is to: Build a future where people live in
harmony with nature. We hope they succeed.
Mark deleted and inserted tag:
<p>My favorite color is
<del>blue</del><ins>red</ins>!</p>
Jump to another part of a document (on the same page) :
<p><a href="#C4">See also Chapter 4.</a></p>
<h2>Chapter 1</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 2</h2>
<p>This chapter explains ba bla bla</p>
<h2><a id="C4">Chapter 4</a></h2>
<p>This chapter explains ba bla bla</p>
HTML Links - The target Attribute
The target attribute specifies where to open the linked document.
The example below will open the linked document in a new browser window or a new tab:
<a href="http://www.w3schools.com/" target="_blank">Visit W3Schools!</a>
HTML head Elements
Tag Description
<head> Defines information about the document
<title> Defines the title of a document
<base> Defines a default address or a default target for all links on a page
<link> Defines the relationship between a document and an external resource
<meta> Defines metadata about an HTML document
<script> Defines a client-side script
<style> Defines style information for a document
Example:
<head>
<base href="http://www.w3schools.com/images/"
target="_blank">
</head>
<body>
<img src="stickman.gif" width="24" height="39"> -
Notice that we have only specified a relative address
for the image. Since we have specified a base URL in
the head section, the browser will look for the image at
"http://www.w3schools.com/images/stickman.gif"
<br><br>
<a href="http://www.w3schools.com">W3Schools</a>
- Notice that the link opens in a new window, even if it
has no target="_blank" attribute. This is because the
target attribute of the base element is set to "_blank".
</body>
- Notice that we have only specified a relative
address for the image. Since we have specified a base
URL in the head section, the browser will look for the
image at
"http://www.w3schools.com/images/stickman.gif
W3Schools- Notice that the link opens in a new
window, even if it has no target="_blank" attribute.
This is because the target attribute of the base element
is set to "_blank".
<meta> Tags:
Define keywords for search engines: <meta name="keywords" content="HTML, CSS, XML, XHTML,
JavaScript">
Define a description of your web page: <meta name="description" content="Free Web tutorials on HTML and
CSS">
Define the author of a page: <meta name="author" content="Hege Refsnes">
Refresh document every 30 seconds: <meta http-equiv="refresh" content="30">
<img> tag:
Syntax for defining an image: <img src="url" alt="some_text" width=.., height=.. border=..>
The alt attribute provides alternative information for an image if a user for some reason cannot view it (because of
slow connection, an error in the src attribute, or if the user uses a screen reader).
The height and width attributes are used to specify the height and width of an image. The attribute values are
specified in pixels by default.
How to make a link that is not underlined, with the style attribute.
<a href="http://www.w3schools.com" style="text-decoration:none;">Visit W3Schools.com!</a>
HTML Table Tags
Tag Description
<table> Defines a table
<th> Defines a header cell in a table
<tr> Defines a row in a table
<td> Defines a cell in a table
<caption> Defines a table caption
<colgroup> Specifies a group of one or more columns in a table for formatting
<col> Specifies column properties for each column within a <colgroup> element
<thead> Groups the header content in a table
<tbody> Groups the body content in a table
<tfoot> Groups the footer content in a table
Table with caption:
<table border="1">
<caption>Monthly savings</caption>
<tr><th>Month</th><th>Savings</th></tr>
<tr><td>January</td><td>$100</td></tr>
<tr><td>February</td><td>$50</td></tr>
</table>
Table without border. Just set <table border="0">
Table contain a list in cell:
<td>This cell contains a list
<ul><li>apples</li>
<li>bananas</li>
<li>pineapples</li>
</ul></td></tr>
cell padding:
<h4>Without cellpadding:</h4>
<table border="1">
<tr><td>First</td><td>Row</td></tr>
<tr><td>Second</td><td>Row</td></tr>
</table>
<h4>With cellpadding:</h4>
<table border="1" cellpadding="10">
<tr><td>First</td><td>Row</td></tr>
<tr><td>Second</td><td>Row</td></tr>
</table>
Cell spacing:
<h4>Without cellspacing:</h4>
<table border="1">
<tr><td>First</td><td>Row</td></tr>
<tr><td>Second</td><td>Row</td></tr>
</table>
<h4>With cellspacing="0":</h4>
<table border="1" cellspacing="0">
<tr><td>First</td><td>Row</td></tr>
<tr><td>Second</td><td>Row</td></tr>
</table>
<h4>With cellspacing="10":</h4>
<table border="1" cellspacing="10">
<tr><td>First</td><td>Row</td></tr>
<tr><td>Second</td><td>Row</td></tr>
</table>
Cell Padding: it refers to the gap or space between the cell content and cell border.
Cell Spacing: It refers to the gap between the two cells of same tables.
HTML Definition Lists
<dl> Defines a definition list
<dt> Defines an item in a definition list
<dd> Defines a description of an item in a definition list
A definition list is a list of items, with a description of each item. The <dl> tag defines a definition list. The <dl>
tag is used in conjunction with <dt> (defines the item in the list) and <dd> (describes the item in the list):
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
How the HTML code above looks in a browser:
Coffee
- black hot drink
Milk
- white cold drink
ordered list:
<ol> 1. Apples
<ol type="A"> A. Apples
<ol type="a"> a. Apples
<ol type="I"> I. Apples
<ol type="i"> i. Apples
unordered list:
<ul style="list-style-type:disc">
<ul style="list-style-type:circle">
<ul style="list-style-type:square">
nested list:
<h4>A nested List:</h4>
<ul>
<li>Coffee</li>
<li>Tea
<ul>
<li>Black tea</li>
<li>Green tea</li>
</ul>
</li>
<li>Milk</li>
</ul>
HTML Block and Inline Elements
Block level elements normally start (and end) with a new line when displayed in a browser.
Examples: <h1>, <p>, <ul>, <table>
Inline elements are normally displayed without starting a new line.
Examples: <b>, <td>, <a>, <img>
The HTML <div> element is a block level element that can be used as a container for grouping other HTML
elements. The <div> element has no special meaning. Except that, because it is a block level element, the browser
will display a line break before and after it.
The HTML <span> element is an inline element that can be used as a container for text. When used together with
CSS, the <span> element can be used to set style attributes to parts of the text.
<div> Defines a section in a document (block-level)
<span> Defines a section in a document (inline)
HTML Layouts - Using <div> Elements
example:
<div id="container" style="width:500px">
<div id="header" style="background-color:#FFA500;">
<h1 style="margin-bottom:0;">Main Title of Web
Page</h1></div>
<div id="menu" style="background-
color:#FFD700;height:200px;width:100px;float:left;">
<b>Menu</b><br>
HTML<br>
CSS<br>
JavaScript</div>
<div id="content" style="background-
color:#EEEEEE;height:200px;width:400px;float:left;">
Content goes here</div>
<div id="footer" style="background-
color:#FFA500;clear:both;text-align:center;">
Copyright W3Schools.com</div>
</div>
HTML Forms - The Input Element
An <input> element can vary in many ways, depending on the type attribute. An <input> element can be of type
text field, checkbox, password, radio button, submit button, and more.
text: First name: <input type="text" name="firstname"><br>
password: Password: <input type="password" name="pwd">
<input type="radio"> defines a radio button. Radio buttons let a user select ONLY ONE of a limited number of.
e.g: <input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
<input type="checkbox"> defines a checkbox. Checkboxes let a user select ZERO or MORE options of a limited
number of choices.
e.g: <input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
<input type="submit"> defines a submit button.
A submit button is used to send form data to a server. The data is sent to the page specified in the form's action
attribute. The file defined in the action attribute usually does something with the received input:
<form name="input" action="html_form_action.asp" method="get">
Username: <input type="text" name="user">
<input type="submit" value="Submit">
</form>
simple drop-down list:
<form action="">
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
</form>
Drop-down list with a pre-selected value:
<form action="">
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat" selected>Fiat</option>
<option value="audi">Audi</option>
</select>
</form>
textarea:
<textarea rows="10" cols="30">
The cat was playing in the garden.
</textarea>
create a button:
<form action=""><input type="button" value="Hello world!"></form>
Send e-mail to someone@example.com:
<form action="MAILTO:someone@example.com" method="post" enctype="text/plain">
E-mail:<input type="text" name="mail" value="your email">
Comment:<input type="text" name="comment" value="your comment" size="50">
<input type="submit" value="Send">
</form>
Fieldset around form-data:
to create a border around elements in a form.
<form action="">
<fieldset>
<legend>Personal information:</legend>
Name: <input type="text" size="30"><br>
E-mail: <input type="text" size="30"><br>
Date of birth: <input type="text" size="10">
</fieldset>
</form>
<form> Defines an HTML form for user input
<input> Defines an input control
<textarea> Defines a multiline input control (text area)
<label> Defines a label for an <input> element
<fieldset> Groups related elements in a form
<legend> Defines a caption for a <fieldset> element
<select> Defines a drop-down list
<optgroup> Defines a group of related options in a drop-down list
<option> Defines an option in a drop-down list
<button> Defines a clickable button
Iframe
An iframe is used to display a web page within a web page.
<iframe src="URL"></iframe>
The URL points to the location of the separate page.
e.g: <iframe src="demo_iframe.htm" width="200" height="200"></iframe>
The frameborder attribute specifies whether or not to display a border around the iframe. Set the attribute value to
"0" to remove the border:
<iframe src="demo_iframe.htm" frameborder="0"></iframe>
An iframe can be used as the target frame for a link. The target attribute of a link must refer to the name attribute
of the iframe:
<iframe src="demo_iframe.htm" name="iframe_a"></iframe>
<p><a href="http://www.w3schools.com" target="iframe_a">W3Schools.com</a></p>
The HTML <noscript> Tag
The <noscript> tag is used to provide an alternate content for users that have disabled scripts in their browser or
have a browser that doesnt support client-side scripting. The content inside the <noscript> element will only be
displayed if scripts are not supported, or are disabled in the users browser.
HTML Useful Character Entities
Result Description Entity Name Entity Number
non-breaking space &nbsp; &#160;
< less than &lt; &#60;
> greater than &gt; &#62;
& ampersand &amp; &#38;
cent &cent; &#162;
pound &pound; &#163;
yen &yen; &#165;
euro &euro; &#8364;
section &sect; &#167;
copyright &copy; &#169;
registered trademark &reg; &#174;
trademark &trade; &#8482;
XHTML
XHTML is HTML written as XML.
The Most Important Differences from HTML:
Document Structure
XHTML DOCTYPE is mandatory
The XML namespace attribute in <html> is mandatory
<html>, <head>, <title>, and <body> is mandatory
XHTML Elements
XHTML elements must be properly nested
XHTML elements must always be closed
XHTML elements must be in lowercase
<BODY><P>This is a paragraph</P></BODY> is wrong
<body><p>This is a paragraph</p></vody> is correct
XHTML documents must have one root element
XHTML Attributes
Attribute names must be in lower case
Attribute values must be quoted
<table width=100%> is wrong, <table width=100%> is correct.
Attribute minimization is forbidden
How to Convert from HTML to XHTML
1. Add an XHTML <!DOCTYPE> to the first line of every page
2. Add an xmlns attribute to the html element of every page
3. Change all element names to lowercase
4. Close all empty elements
5. Change all attribute names to lowercase
6. Quote all attribute values
html media:
Using The <embed> Element: The <embed> tag defines a container for external (non-HTML) content. The
following code fragment should play an MP3 file embedded in a web page:
<embed height="50" width="100" src="horse.mp3">
Using the HTML5 <audio> Element: The HTML5 <audio> tag defines sound, such as music or other audio
streams. The <audio> element works in all modern browsers.
The following example uses the <audio> tag, and specifies one MP3 file (for Internet Explorer, Chrome, and
Safari), and one OGG file (for Firefox and Opera). If anything fails it displays a text:
<audio controls>
<source src="horse.mp3" type="audio/mpeg">
<source src="horse.ogg" type="audio/ogg">
Your browser does not support this audio format.
</audio>
The example below uses the HTML5 <audio> element and tries to play the audio either as MP3 or OGG. If it
fails, the code "falls back" to try the <embed> element:
<audio controls height="100" width="100">
<source src="horse.mp3" type="audio/mpeg">
<source src="horse.ogg" type="audio/ogg">
<embed height="50" width="100" src="horse.mp3">
</audio>
Using A Hyperlink: If a web page includes a hyperlink to a media file, most browsers will use a "helper
application" to play the file. The following code fragment displays a link to an MP3 file. If a user clicks on the
link, the browser will launch a helper application to play the file:
<p><a href="horse.mp3">Click here to play the sound</a></p>
Playing Videos in HTML
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
<source src="movie.webm" type="video/webm">
<object data="movie.mp4" width="320" height="240">
<embed src="movie.swf" width="320" height="240">
</object>
</video>
script to paly or pause a video:
var myVideo=document.getElementById("video1");
function playPause()
{
if (myVideo.paused) myVideo.play();
else myVideo.pause();
}
The <embed> Element: The purpose of the <embed> tag is to embed multimedia elements in HTML pages. The
following HTML fragment displays a Flash video embedded in a web page:
<embed src="intro.swf" width="200" height="200"><p>If you cannot see this, your computer doesn't support the
format</p>
Using The <object> Element: The purpose of the <object> tag is to embed multimedia elements in HTML pages.
The following HTML fragment displays a Flash video embedded in a web page:
<object data="intro.swf" height="200" width="200"></object>
The Best HTML Solution: The example below uses 4 different video formats. The HTML 5 <video> element tries
to play the video either in MP4, OGG, or WEBM format. If this fails, the code "falls back" to try the <object>
element. If this also fails, it "falls back" to the <embed> element:
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
<source src="movie.webm" type="video/webm">
<object data="movie.mp4" width="320" height="240">
<embed src="movie.swf" width="320" height="240">
</object>
</video>
Using A Hyperlink: If a web page includes a hyperlink to a media file, most browsers will use a "helper
application" to play the file. The following code fragment displays a link to a Flash video. If a user clicks on the
link, the browser will launch a helper application to play the file:
<a href="intro.swf">Play a video file</a>
Playing a YouTube Video in HTML: If you want to play a video in a web page, you can upload the video to
YouTube and insert the proper HTML code to display the video:
youtube iframe:
<iframe width="420" height="345" src="http://www.youtube.com/embed/XGSy3_Czz8k">
</iframe>
youtube embeded:
<embed width="420" height="345" src="http://www.youtube.com/v/XGSy3_Czz8k"
type="application/x-shockwave-flash">
</embed>
HTML5
In HTML5 there is only one <!doctype> declaration, and it is very simple: <!DOCTYPE html>
minimum html5 document:
<!DOCTYPE html>
<html>
<head><title>Title of the document</title></head>
<body>The content of the document......</body>
</html>
What is Canvas?
The HTML5 <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript).
The <canvas> element is only a container for graphics. You must use a script to actually draw the graphics.
Canvas has several methods for drawing paths, boxes, circles, characters, and adding images.
A canvas is a rectangular area on an HTML page, and it is specified with the <canvas> element.
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>
Draw Onto The Canvas With JavaScript
All drawing on the canvas must be done inside a JavaScript:
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d"); //(you must pass the string
"2d" to the getContext() method)
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);
//Start at the upper-left corner (0,0) and draw a 150x75
pixels rectangle.
</script>
To draw straight lines on a canvas, we will use the following two methods:
moveTo(x,y) defines the starting point of the line
lineTo(x,y) defines the ending point of the line
To actually draw the line, we must use one of the "ink" methods, like stroke().
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
To draw a circle on a canvas, we will use the following method:
arc(x,y,r,start,stop)
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
To draw text on a canvas, the most important property and methods are:
font - defines the font properties for text
fillText(text,x,y) - Draws "filled" text on the canvas
strokeText(text,x,y) - Draws text on the canvas (no fill)
Using fillText():
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="30px Arial";
ctx.fillText("Hello World",10,50);
Write a 30px high text (no fill) on the canvas, using the font "Arial":
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="30px Arial";
ctx.strokeText("Hello World",10,50);
To draw an image on a canvas, we will use the following method: drawImage(image,x,y)
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
ctx.drawImage(img,10,10);
Make an Element Draggable
First of all: To make an element draggable, set the draggable attribute to true: <img draggable="true">
code:
<script>
function allowDrop(ev)
{ ev.preventDefault(); }
function drag(ev)
{ ev.dataTransfer.setData("Text",ev.target.id); }
function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
}
</script>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">
Code explained:
Call preventDefault() to prevent the browser default handling of the data (default is open as link on drop)
Get the dragged data with the dataTransfer.getData("Text") method. This method will return any data that
was set to the same type in the setData() method
The dragged data is the id of the dragged element ("drag1")
Append the dragged element into the drop element
HTML5 New Input Types
Select a color from a color picker: Select favorite color: <input type="color" name="favcolor">
Define a date control: Birthday: <input type="date" name="bday">
Define a date and time control (with time zone): Birthday (date and time): <input type="datetime"
name="bdaytime">
Define a date and time control (no time zone): Birthday (date and time): <input type="datetime-local"
name="bdaytime">
Define a field for an e-mail address (will be automatically validated when submitted):
E-mail: <input type="email" name="email">
Define a month and year control (no time zone):
Birthday (month and year): <input type="month" name="bdaymonth">
Define a numeric field (with restrictions):
Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5">
The range type is used for input fields that should contain a value from a range of numbers.
Define a control for entering a number whose exact value is not important (like a slider control):
<input type="range" name="points" min="1" max="10">
Define a search field (like a site search, or Google search):
Search Google: <input type="search" name="googlesearch">
Define a field for entering a telephone number:
Telephone: <input type="tel" name="usrtel">
Define a control for entering a time (no time zone):
Select a time: <input type="time" name="usr_time">
The url type is used for input fields that should contain a URL address.
The value of the url field is automatically validated when the form is submitted.
Add your homepage: <input type="url" name="homepage">
HTML5 <keygen> Element
The <keygen> tag specifies a key-pair generator field in a form. When the form is submitted, two keys are
generated, one private and one public. The private key is stored locally, and the public key is sent to the server.
The public key could be used to generate a client certificate to authenticate the user in the future.
<form action="demo_keygen.asp" method="get">
Username: <input type="text" name="usr_name">
Encryption: <keygen name="security">
<input type="submit">
</form>
HTML5 New Form Attributes
<form> / <input> autocomplete Attribute
The autocomplete attribute specifies whether a form or input field should have autocomplete on or off. When
autocomplete is on, the browser automatically complete values based on values that the user has entered before.
<form action="demo_form.asp" autocomplete="on">
Last name: <input type="text" name="lname"><br>
E-mail: <input type="email" name="email" autocomplete="off"><br>
<input type="submit">
</form>
<form> novalidate Attribute
The novalidate attribute is a boolean attribute. When present, it specifies that the form-data (input) should not be
validated when submitted.
<form action="demo_form.asp" novalidate>
E-mail: <input type="email" name="user_email">
<input type="submit">
</form>
<input> autofocus Attribute
When present, it specifies that an <input> element should automatically get focus when the page loads.
Let the "First name" input field automatically get focus when the page loads:
First name:<input type="text" name="fname" autofocus>
<input> form Attribute
The form attribute specifies one or more forms an <input> element belongs to.
An input field located outside the HTML form (but still a part of the form), The "Last name" field below is outside
the form element, but still part of the form:
<form action="demo_form.asp" id="form1">
First name: <input type="text" name="fname"><br>
<input type="submit" value="Submit">
</form>
Last name: <input type="text" name="lname" form="form1">
<input> formaction Attribute
The formaction attribute specifies the URL of a file that will process the input control when the form is submitted.
The formaction attribute overrides the action attribute of the <form> element.
An HTML form with two submit buttons, with different actions:
<form action="demo_form.asp">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit"><br>
<input type="submit" formaction="demo_admin.asp"
value="Submit as admin">
</form>
<input> formenctype Attribute
The formenctype attribute specifies how the form-data should be encoded when submitting it to the server (only
for forms with method="post")
The formenctype attribute overrides the enctype attribute of the <form> element.
Send form-data that is default encoded (the first submit button), and encoded as "multipart/form-data" (the second
submit button):
<form action="demo_post_enctype.asp" method="post">
First name: <input type="text" name="fname"><br>
<input type="submit" value="Submit">
<input type="submit" formenctype="multipart/form-data"
value="Submit as Multipart/form-data">
</form>
<input> formmethod Attribute
The formmethod attribute defines the HTTP method for sending form-data to the action URL.
The formmethod attribute overrides the method attribute of the <form> element.
The second submit button overrides the HTTP method of the form:
<form action="demo_form.asp" method="get">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
<input type="submit" formmethod="post" formaction="demo_post.asp"
value="Submit using POST">
</form>
<input> formnovalidate Attribute
The novalidate attribute is a boolean attribute. When present, it specifies that the <input> element should not be
validated when submitted.
A form with two submit buttons (with and without validation):
<form action="demo_form.asp">
E-mail: <input type="email" name="userid"><br>
<input type="submit" value="Submit"><br>
<input type="submit" formnovalidate value="Submit without validation">
</form>
<input> formtarget Attribute
The formtarget attribute specifies a name or a keyword that indicates where to display the response that is
received after submitting the form.
A form with two submit buttons, with different target windows:
<form action="demo_form.asp">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit as normal">
<input type="submit" formtarget="_blank"
value="Submit to a new window">
</form>
<input> placeholder Attribute
The placeholder attribute specifies a short hint that describes the expected value of an input field (e.g. a sample
value or a short description of the expected format). The hint is displayed in the input field when it is empty, and
disappears when the field gets focus.
<input type="text" name="fname" placeholder="First name">
<input> required Attribute
The required attribute is a boolean attribute. When present, it specifies that an input field must be filled out before
submitting the form.
Username: <input type="text" name="usrname" required>
image as button:
Define an image as the submit button, with height and width attributes:
<input type="image" src="img_submit.gif" alt="Submit" width="48" height="48">
web storage
What is HTML5 Web Storage?
With HTML5, web pages can store data locally within the user's browser. Web Storage is more secure and faster
than cookie. The data is not included with every server request, but used ONLY when asked for. It is also possible
to store large amounts of data, without affecting the website's performance. The data is stored in key/value pairs,
and a web page can only access data stored by itself.
localStorage and sessionStorage
There are two new objects for storing data on the client:
localStorage - stores data with no expiration date
sessionStorage - stores data for one session
Before using web storage, check browser support for localStorage and sessionStorage:
if(typeof(Storage)!=="undefined")
{
// Yes! localStorage and sessionStorage support!
//Some code.....
}
else
// Sorry! No web storage support..
The localStorage Object
The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is
closed, and will be available the next day, week, or year.
e.g: localStorage.lastname="Smith";
document.getElementById("result").innerHTML="Last name: "+localStorage.lastname;
explained:
Create a localStorage key/value pair with key="lastname" and value="Smith"
Retrieve the value of the "lastname" key and insert it into the element with id="result"
example: The following example counts the number of times a user has clicked a button. In this code the value
string is converted to a number to be able to increase the counter.
if (localStorage.clickcount)
localStorage.clickcount=Number(localStorage.clickcount)+1;
else
localStorage.clickcount=1;
document.getElementById("result").innerHTML="Have clicked button"+ localStorage.clickcount + " time(s).";
The sessionStorage Object
The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session.
The data is deleted when the user closes the browser window.
The following example counts the number of times a user has clicked a button, in the current session:
if (sessionStorage.clickcount)
sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
else
sessionStorage.clickcount=1;
document.getElementById("result").innerHTML="You have clicked the button " + sessionStorage.clickcount + "
time(s) in this session.";
What is Application Cache?
HTML5 introduces application cache, which means that a web application is cached, and accessible without an
internet connection. Application cache gives an application three advantages:
1. Offline browsing - users can use the application when they're offline
2. Speed - cached resources load faster
3. Reduced server load - the browser will only download updated/changed resources from the server
Once a file is cached, the browser will continue to show the cached version, even if you change the file on the
server. To ensure the browser updates the cache, you need to change the manifest file.
To enable application cache, include the manifest attribute in the document's <html> tag:
<!DOCTYPE HTML>
<html manifest="demo.appcache">
...
</html>
Every page with the manifest attribute specified will be cached when the user visits it. If the manifest attribute is
not specified, the page will not be cached.
The Manifest File
The manifest file is a simple text file, which tells the browser what to cache (and what to never cache). The
manifest file has three sections:
CACHE MANIFEST- Files listed under this header will be cached after they are downloaded for the first
time
NETWORK- Files listed under this header require a connection to the server, and will never be cached
FALLBACK- Files listed under this header specifies fallback pages if a page is inaccessible
CACHE MANIFEST
The first line, CACHE MANIFEST, is required:
CACHE MANIFEST
/theme.css
/logo.gif
/main.js
The manifest file above lists three resources: a CSS file, a GIF image, and a JavaScript file. When the manifest
file is loaded, the browser will download the three files from the root directory of the web site. Then, whenever
the user is not connected to the internet, the resources will still be available.
NETWORK
The NETWORK section below specifies that the file "login.asp" should never be cached, and will not be available
offline:
NETWORK:
login.asp
An asterisk can be used to indicate that all other resources/files require an internet connection:
NETWORK:
*
FALLBACK
The FALLBACK section below specifies that "offline.html" will be served in place of all files in the /html/
catalog, in case an internet connection cannot be established:
FALLBACK:
/html/ /offline.html
Updating the Cache
Once an application is cached, it remains cached until one of the following happens:
The user clears the browser's cache
The manifest file is modified (see tip below)
The application cache is programmatically updated
What is a Web Worker?
When executing scripts in an HTML page, the page becomes unresponsive until the script is finished. A web
worker is a JavaScript that runs in the background, independently of other scripts, without affecting the
performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web
worker runs in the background.
Before creating a web worker, check whether the user's browser supports it:
if(typeof(Worker)!=="undefined")
{
// Yes! Web worker support!
// Some code.....
}
else
{
// Sorry! No Web Worker support..
}
Now, let's create our web worker in an external JavaScript. Here, we create a script that counts. The script is
stored in the "demo_workers.js" file:
var i=0;
function timedCount()
{
i=i+1;
postMessage(i);
setTimeout("timedCount()",500);
}
timedCount();
The important part of the code above is the postMessage() method - which is used to posts a message back to the
HTML page.
Now that we have the web worker file, we need to call it from an HTML page.
The following lines checks if the worker already exists, if not - it creates a new web worker object and runs the
code in "demo_workers.js":
if(typeof(w)=="undefined")
{ w=new Worker("demo_workers.js");}
Then we can send and receive messages from the web worker. Add an "onmessage" event listener to the web
worker.
w.onmessage=function(event){
document.getElementById("result").innerHTML=event.data; };
When the web worker posts a message, the code within the event listener is executed. The data from the web
worker is stored in event.data.
Terminate a Web Worker
When a web worker object is created, it will continue to listen for messages (even after the external script is
finished) until it is terminated. To terminate a web worker, and free browser/computer resources, use the
terminate() method: w.terminate();
full code:
<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
<br><br>
<script>
var w;
function startWorker()
{
if(typeof(Worker)!=="undefined")
{
if(typeof(w)=="undefined")
w=new Worker("demo_workers.js");
w.onmessage = function (event) {document.getElementById("result").innerHTML=event.data;};
}
else
document.getElementById("result").innerHTML="Sorry, your browser does not support Web Workers...";
}
function stopWorker()
{ w.terminate();}
</script>
--------------------------------------------------------------------------------------------------------------------------------
Javascript
external js: <body> <script src="myScript.js"></script></body>
Manipulating HTML Elements
To access an HTML element from JavaScript, you can use the document.getElementById(id) method.
Use the "id" attribute to identify the HTML element:
<p id="demo">My First Paragraph</p>
<script>
document.getElementById("demo").innerHTML="My First JavaScript";
</script>
Writing to The Document Output
The example below writes a <p> element directly into the HTML document output:
<h1>My First Web Page</h1>
<script>
document.write("<p>My First JavaScript</p>");
</script>
If you execute document.write after the document has finished loading, the entire HTML page will be overwritten:
<h1>My First Web Page</h1>
<p>My First Paragraph.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction(){ document.write("Oops! The document disappeared!");}
</script>
Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable, it will not lose its value:.
The value of the variable carname will still have the value "Volvo" after the execution of the following two
statements:
var carname="Volvo";
var carname;
JavaScript Numbers
JavaScript has only one type of numbers. Numbers can be written with, or without decimals:
var x1=34.00; //Written with decimals
var x2=34; //Written without decimals
Extra large or extra small numbers can be written with scientific (exponential) notation:
var y=123e5; // 12300000
var z=123e-5; // 0.00123
Octal and Hexadecimal
JavaScript interprets numeric constants as octal if they are preceded by a zero, and as hexadecimal if they are
preceded by a zero and x.
var y=0377;
var z=0xFF;
Number.MAX_VALUE; --Returns the largest number possible in JavaScript
Number.MIN_VALUE; --Returns the smallest number possible in JavaScript
Number.NEGATIVE_INFINITY; --Return negative infinity:
Number.NaN Represents a "Not-a-Number" value. Use the isNaN() global function to check if a value is a NaN
value.
Convert a number into an exponential notation:
var num = 5.56789;
var n=num.toExponential()
The result of n will be: 5.56789e+0
Convert a number into a string, keeping only two decimals:
var num = 5.56789;
var n=num.toFixed(2);
The result of n will be: 5.57
Format a number into a specified length:
var num = new Number(13.3714);
var n=num.toPrecision(2);
The result of n will be: 13
var num = 15;
var n = num.toString();
The result of n will be: 15
var num = 15;
var n = num.valueOf();
The result of n will be: 15
JavaScript String
Finding a String in a String: The indexOf() method returns the position (as a number) of the first found occurrence
of a specified text inside a string: var n=str.indexOf("welcome");
The lastIndexOf() method starts searching at the end of the string instead of at the beginning.
The match() method can be used to search for a matching content in a string:
e.g: var str="Hello world!";
document.write(str.match("world") + "<br>");
display: world
The replace() method replaces a specified value with another value in a string.
e.g: str="Please visit Microsoft!"
var n=str.replace("Microsoft","W3Schools");
A string is converted to upper/lower case with the methods toUpperCase() / toLowerCase():
var txt="Hello World!"; // String
var txt1=txt.toUpperCase(); // txt1 is txt converted to upper
var txt2=txt.toLowerCase(); // txt2 is txt converted to lower
A string is converted to an array with the built in method string.split():
var str="a,b,c,d,e,f";
var n=str.split(","); //or split(|), split( )
document.getElementById("demo").innerHTML=n[0];
Special Characters
The backslash (\) can be used to insert apostrophes, new lines, quotes, and other special characters into a string.
To place a backslash (\) before each double quote in "Viking". This turns each double quote into a string literal:
var txt="We are the so-called \"Vikings\" from the north.";
document.write(txt);
charAt()
Returns the character at the specified index
e.g: var str = "HELLO WORLD";
var n = str.charAt(2)
charCodeAt()
Returns the Unicode of the character at the specified index
e.g: var str = "HELLO WORLD";
var n = str.charCodeAt(0);
result: 72
concat()
Joins two or more strings, and returns a copy of the joined strings
e.g: var str1 = "Hello ";
var str2 = "world!";
var n = str1.concat(str2);
fromCharCode
()
Converts Unicode values to characters
var n = String.fromCharCode(65);
result: A
search()
Searches for a match between a regular expression and a string, and returns the position of the
match
e.g: var str="The rain in SPAIN stays mainly in the plain";
var n=str.match(/ain/g);
result: ain,ain,ain
slice()
Extracts a part of a string and returns a new string
e.g: var str="Hello world!";
var n=str.slice(1,5);
result: ello
substr()
Extracts the characters from a string, beginning at a specified start position, and through the
specified number of character
var str="Hello world!";
var n=str.substr(2,3)
result: llo
substring()
Extracts the characters from a string, between two specified indices
string.substring(from, to)
from: required, he index where to start the extraction. First character is at index 0
to: Optional. index where to stop the extraction. If omitted, it extracts rest of the string
JavaScript Date:
Return today's date and time: to get today's date.
var d=new Date();
document.write(d);
getFullYear(): to get the year.
var x = document.getElementById("demo");
x.innerHTML=new Date().getFullYear();
GetTime(): returns the number of milliseconds since 01.01.1970.
var x = document.getElementById("demo");
x.innerHTML=new Date().getTime();
setFullYear(): to set a specific date.
var d = new Date();
d.setFullYear(2020,10,3);
var x = document.getElementById("demo");
x.innerHTML=d;
ToUTCString(): to convert today's date (according to UTC) to a string.
var x = document.getElementById("demo");
x.innerHTML=new Date().toUTCString()
Display a clock: display a clock on your web page.
<head>
<script>
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout(function(){startTime()},500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
Create a Date Object
The Date object is used to work with dates and times. Date objects are created with the Date() constructor.There
are four ways of initiating a date:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Set Dates
We can easily manipulate the date by using the methods available for the Date object.
In the example below we set a Date object to a specific date (14th January 2010):
var myDate=new Date();
myDate.setFullYear(2010,0,14);
And in the following example we set a Date object to be 5 days into the future:
var myDate=new Date();
myDate.setDate(myDate.getDate()+5);
Compare Two Dates
The following example compares today's date with the 14th January 2100:
var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();
if (x>today)
alert("Today is before 14th January 2100");
else
alert("Today is after 14th January 2100");
JavaScript Booleans
Booleans can only have two values: true or false.
var x=true;
var y=false;
If the Boolean object has no initial value, or if the passed value is one of the following:
0
-0
null
""
false
undefined
NaN
the object is set to false. For any other value it is set to true!
JavaScript Arrays
The following code creates an Array called cars:
1. var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
2. var cars=new Array("Saab","Volvo","BMW");
3. var cars=["Saab","Volvo","BMW"];
Join three arrays concat()
var parents = ["Jani", "Tove"];
var brothers = ["Stale", "Kai Jim", "Borge"];
var children = ["Cecilie", "Lone"];
var family = parents.concat(brothers, children);
document.write(family);
display: Jani,Tove,Stale,Kai Jim,Borge,Cecilie,Lone
Join all elements of an array into a string join()
function myFunction()
{
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x=document.getElementById("demo");
x.innerHTML=fruits.join();
}
display: Banana,Orange,Apple,Mango
Remove the last element of an array pop()
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function myFunction()
{
fruits.pop();
var x=document.getElementById("demo");
x.innerHTML=fruits;
}
display: Banana,Orange,Apple
Add new elements to the end of an array push()
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function myFunction()
{
fruits.push("Kiwi")
var x=document.getElementById("demo");
x.innerHTML=fruits;
}
display: Banana,Orange,Apple, Mongo, Kiwi
Reverse the order of the elements in an array reverse()
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function myFunction()
{
fruits.reverse();
var x=document.getElementById("demo");
x.innerHTML=fruits;
}
display: Mango,Apple,Orange,Banana
Remove the first element of an array shift()
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function myFunction()
{
fruits.shift();
var x=document.getElementById("demo");
x.innerHTML=fruits;
}
display: Orange,Apple,Mango
Add new elements to the beginning of an array - unshift()
function myFunction()
{
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon","Pineapple");
var x=document.getElementById("demo");
x.innerHTML=fruits;
}
display: Lemon,Pineapple,Banana,Orange,Apple,Mango
Select elements from an array slice()
function myFunction()
{
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1,3);
var x=document.getElementById("demo");
x.innerHTML=citrus;
}
display: Orange,Lemon
Sort an array (alphabetically and ascending) sort()
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
var x=document.getElementById("demo");
x.innerHTML=fruits;
display: Apple,Banana,Mango,Orange
Sort numbers (numerically and ascending) sort()
var points = [40,100,1,5,25,10];
points.sort(function(a,b){return a-b});
var x=document.getElementById("demo");
x.innerHTML=points;
display: 1,5,10,25,40,100
Sort numbers (numerically and descending) sort()
var points = [40,100,1,5,25,10];
points.sort(function(a,b){return b-a});
var x=document.getElementById("demo");
x.innerHTML=points;
display: 100,40,25,10,5,1
Add an element to position 2 in an array splice()
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2,0,"Lemon","Kiwi");
var x=document.getElementById("demo");
x.innerHTML=fruits;
display: Banana,Orange,Lemon,Kiwi,Apple,Mango
Convert an array to a string - toString()
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.toString();
var x=document.getElementById("demo");
x.innerHTML=fruits;
JavaScript Objects
var person={
firstname : "John",
lastname : "Doe",
id : 5566
};
You can address the object properties in two ways:
name=person.lastname;
name=person["lastname"];
When you declare a new variable, you can declare its type using the "new" keyword:
var carname=new String;
var x= new Number;
var y= new Boolean;
var cars= new Array;
var person= new Object;
Creating JavaScript Objects
Almost "everything" in JavaScript is an object. Strings, Dates, Arrays, Functions. You can also create your own
objects. This example creates an object called "person", and adds four properties to it:
person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
The syntax for accessing the property of an object is: objectName.propertyName
e.g: var message="Hello World!";
var x=message.length;
You can call a method with the following syntax: objectName.methodName()
This example uses the toUpperCase() method of the String object, to convert a text to uppercase:
var message="Hello world!";
var x=message.toUpperCase();
Local JavaScript Variables
The lifetime JavaScript variables starts when they are declared. A variable declared (using var) within a JavaScript
function becomes LOCAL and can only be accessed from within that function. Local variables are deleted as
soon as the function is completed.
Global JavaScript Variables
The lifetime JavaScript variables starts when they are declared. Variables declared outside a function,
become GLOBAL, and all scripts and functions on the web page can access it. Global variables are deleted when
you close the page.
Assigning Values to Undeclared JavaScript Variables
If you assign a value to variable that has not yet been declared, the variable will automatically be declared as
a GLOBAL variable.
This statement: carname="Volvo";
will declare the variable carname as a global variable , even if it is executed inside a function.
The + Operator Used on Strings
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
The result of txt3 will be: What a verynice day
Adding two numbers, will return the sum, but adding a number and a string will return a string:
x=5+5;
y="5"+5;
z="Hello"+5;
The result of x,y, and z will be:
10
55
Hello5
The rule is: If you add a number and a string, the result will be a string!
Conditional Operator
If the variable age is a value below 18, the value of the variable voteable will be "Too young, otherwise the value
of voteable will be "Old enough":
voteable=(age<18)?"Too young":"Old enough";
The JavaScript Switch Statement
switch(n)
{
case 1: execute code block 1 break;
case 2: execute code block 2 break;
default: code to be executed if n is different from case 1 and 2
}
If it is NOT Saturday or Sunday, then write a default message:
e.g: var day=new Date().getDay();
switch (day){
case 6: x="Today it's Saturday"; break;
case 0: x="Today it's Sunday"; break;
default: x="Looking forward to the Weekend";
}
The while /For/In Loop
The JavaScript for/in statement loops through the properties of an object:
var person={fname:"John",lname:"Doe",age:25};
for (x in person)
txt=txt + person[x];
display: JohnDoe25
cars=["BMW","Volvo","Saab","Ford"];
var i=0;
while (cars[i])
{
document.write(cars[i] + "<br>");
i++;
}
display:
BMW
Volvo
Saab
Ford
The Throw Statement
The throw statement allows you to create a custom error.
Syntax: throw exception
The exception can be a JavaScript String, a Number, a Boolean or an Object.
This example examines the value of an input variable. If the value is wrong, an exception (error) is thrown. The
error is caught by the catch statement and a custom error message is displayed:
<script>
function myFunction()
{
try
{
var x=document.getElementById("demo").value;
if(x=="") throw "empty";
if(isNaN(x)) throw "not a number";
if(x>10) throw "too high";
if(x<5) throw "too low";
}
catch(err)
{ var y=document.getElementById("mess");
y.innerHTML="Error: " + err + ".";
}
}
</script>
<h1>My First JavaScript</h1>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="mess"></p>
Validations
required field validation:
The function below checks if a field has been left empty. If the field is blank, an alert box alerts a message, the
function returns false, and the form will not be submitted:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
The function above could be called when a form is submitted:
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
email validation:
The function below checks if the content has the general syntax of an email.This means that the input data must
contain an @ sign and at least one dot (.). Also, the @ must not be the first character of the email address, and the
last dot must be present after the @ sign, and minimum 2 characters before the end:
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
The function above could be called when a form is submitted:
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
The HTML DOM (Document Object Model)
When a web page is loaded, the browser creates a Document Object Model of the page. The HTML DOMmodel
is constructed as a tree of Objects:
The HTML DOM Tree
Often, with JavaScript, you want to manipulate HTML elements. To do so, you have to find the elements first.
There are a couple of ways to do this:
Finding HTML elements by id
Finding HTML elements by tag name
Finding HTML elements by class name
This example finds the element with id="intro": var x=document.getElementById("intro");
This example finds the element with tag name:
<div id="main">
<p>The DOM is very useful.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method</p>
</div>
<script>
var x=document.getElementById("main");
var y=x.getElementsByTagName("p");
document.write('First paragraph inside "main" is ' + y[0].innerHTML);
</script>
display:
The DOM is very useful.
This example demonstrates the getElementsByTagName method
First paragraph inside "main" is The DOM is very useful.
Changing HTML Content
The easiest way to modify the content of an HTML element is by using the innerHTML property.
To change the content of an HTML element, use this syntax:
document.getElementById(id).innerHTML=new HTML
This example changes the content of a <p> element:
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
Changing an HTML Attribute
To change the attribute of an HTML element, use this syntax:
document.getElementById(id).attribute=new value
This example changes the src attribute of an <img> element:
<img id="image" src="smiley.gif">
<script>
document.getElementById("image").src="landscape.jpg";
</script>
Changing HTML Style
To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=new style
The following example changes the style of a <p> element:
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color="blue";
</script>
Change visibility
<p id="p1">This is a text. </p>
<input type="button" value="Hide text" onclick="document.getElementById('p1').style.visibility='hidden'" />
<input type="button" value="Show text" onclick="document.getElementById('p1').style.visibility='visible'" />
Reacting to Events
A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element. To execute
code when a user clicks on an element, add JavaScript code to an HTML event attribute:
onclick=JavaScript
Examples of HTML events:
When a user clicks the mouse
When a web page has loaded
When an image has been loaded
When the mouse moves over an element
When an input field is changed
When an HTML form is submitted
When a user strokes a key
e.g: change context
<script>
function changetext(id)
{ id.innerHTML="Ooops!"; }
</script>
<h1 onclick="changetext(this)">Click on this text!</h1>
e.g: display date when click btn
<button onclick="displayDate()">Try it</button>
<script>
function displayDate()
{ document.getElementById("demo").innerHTML=Date();}
</script>
<p id="demo"></p>
another way:
<button id="myBtn">Try it</button>
<script>
document.getElementById("myBtn").onclick=function(){displayDate()};
function displayDate()
{ document.getElementById("demo").innerHTML=Date();}
</script>
<p id="demo"></p>
The onload and onunload Events
The onload and onunload events are triggered when the user enters or leaves the page. The onload event can be
used to check the visitor's browser type and browser version, and load the proper version of the web page based
on the information. The onload and onunload events can be used to deal with cookies.
e.g:
<body onload="checkCookies()">
<script>
function checkCookies()
{
if (navigator.cookieEnabled==true)
alert("Cookies are enabled")
else
alert("Cookies are not enabled")
}
</script>
e.g: When you leave the input field, a function is triggered which transforms the input text to upper case.
<script>
function myFunction()
{
var x=document.getElementById("fname");
x.value=x.value.toUpperCase();
}
</script>
Enter your name: <input type="text" id="fname" onchange="myFunction()">
e.g: When the input field gets focus, a function is triggered which changes the background-color.
<script>
function myFunction(x)
{ x.style.background="yellow"; }
</script>
Enter your name: <input type="text" onfocus="myFunction(this)">
The onmouseover and onmouseout Events
The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of,
an HTML element.
e.g:
<div onmouseover="mOver(this)" onmouseout="mOut(this)" style="background-
color:#D94A38;width:120px;height:20px;padding:40px;">Mouse Over Me</div>
<script>
function mOver(obj)
{ obj.innerHTML="Thank You" }
function mOut(obj)
{ obj.innerHTML="Mouse Over Me" }
</script>
The onmousedown, onmouseup and onclick Events
The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when a mouse-button is
clicked, the onmousedown event is triggered, then, when the mouse-button is released, the onmouseup event is
triggered, finally, when the mouse-click is completed, the onclick event is triggered.
<div onmousedown="mDown(this)" onmouseup="mUp(this)" style="background-
color:#D94A38;width:90px;height:20px;padding:40px;">Click Me</div>
<script>
function mDown(obj)
{
obj.style.backgroundColor="#1ec5e5";
obj.innerHTML="Release Me"
}
function mUp(obj)
{
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You"
}
</script>
Creating New HTML Elements
To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to
an existing element.
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para=document.createElement("p"); //creates a new <p> element
var node=document.createTextNode("This is new.");//create a text node first
para.appendChild(node);//append the text node to the <p> element
var element=document.getElementById("div1");//finds an existing element
element.appendChild(para);//appends the new element to the existing element
</script>
Removing Existing HTML Elements
To remove an HTML element, you must know the parent of the element:
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent=document.getElementById("div1");//Find the element with id="div1"
var child=document.getElementById("p1");//Find the <p> element with id="p1"
parent.removeChild(child); //Remove the child from the parent
</script>
What is RegExp?
A regular expression is an object that describes a pattern of characters. When you search in a text, you can use a
pattern to describe what you are searching for. A simple pattern can be one single character.
var patt=new RegExp(pattern,modifiers);
or: var patt=/pattern/modifiers;
Modifiers are used to perform case-insensitive and global searches.
The i modifier is used to perform case-insensitive matching.
The g modifier is used to perform a global match (find all matches rather than stopping after the first match).
Do a case-insensitive search for "w3schools" in a string:
var str="Visit W3Schools";
var patt1=/w3schools/i;
display: W3Schools
Do a global search for "is":
var str="Is this all there is?";
var patt1=/is/g;
output: is,is
Do a global, case-insensitive search for "is":
var str="Is this all there is?";
var patt1=/is/gi;
output: Is,is,is
other example:
Do a global search for the character-span [a-h] in a string:
var str="Is this all there is?";
var patt1=/[a-h]/g;
The marked text below shows where the expression gets a match:
Is this all there is?
The output: h,a,h,e,e
Do a global search for characters not inside the character-span [a-h]:
var str="Is this all there is?";
var patt1=/[^a-h]/g;
The marked text below shows where the expression gets a match:
Is this all there is?
The output: I,s, ,t,i,s, ,l,l, ,t,r, ,i,s,?
[0-9] Find any digit from 0 to 9
[A-Z] Find any character from uppercase A to uppercase Z
[a-z] Find any character from lowercase a to lowercase z
[A-z] Find any character from uppercase A to lowercase z
[adgk] Find any character in the given set
[^adgk] Find any character outside the given set
(red|blue|green) Find any of the alternatives specified
The \w metacharacter is used to find a word character.
A word character is a character from a-z, A-Z, 0-9, including the _ (underscore) character.
Do a global search for word characters in a string:
var str="Give 100%!";
var patt1=/\w/g;
The marked text below shows where the expression gets a match:
Give 100%!
output: G,i,v,e,1,0,0
The \W metacharacter is used to find a non-word character.
Example
Do a global search for non-word characters in a string:
var str="Give 100%!";
var patt1=/\W/g;
The marked text below shows where the expression gets a match:
Give 100%!
output: ,%,!
The \d metacharacter is used to find a digit from 0-9.
Example: Do a global search for digits:
var str="Give 100%!";
var patt1=/\d/g;
The marked text below shows where the expression gets a match:
Give 100%!
output: 1,0,0
The \D metacharacter is used to find a non-digit character.
var str="Give 100%!";
var patt1=/\D/g;
The marked text below shows where the expression gets a match:
Give 100%!
output: G,i,v,e, ,%,!
The \s metacharacter is used to find a whitespace character.
A whitespace character can be:
A space character
A tab character
A carriage return character
A new line character
A vertical tab character
A form feed character
Do a global search for whitespace characters in a string:
var str="Is this all there is?";
var patt1=/\s/g;
All the spaces in the text will get a match (four matches):
Is this all there is?
Output: , , ,
The \S metacharacter is used to find a non-whitespace character.
var str="Is this all there is?";
var patt1=/\S/g;
The marked text below shows where the expression gets a match (matches everything except the whitespaces):
Is this all there is?
Output: I,s,t,h,i,s,a,l,l,t,h,e,r,e,i,s,?
The \b metacharacter is used to find a match at the beginning or end of a word.
Do a global search for "W3" at the beginning or end of a word in a string:
var str="Visit W3Schools";
var patt1=/\bW3/g;
The marked text below shows where the expression gets a match:
Visit W3Schools
output: W3
The \B metacharacter is used to find a match not at the beginning or end of a word.
Do a global search for "Schools" NOT at the beginning or end of a word in a string:
var str="Visit W3Schools";
var patt1=/\BSchool/g;
The marked text below shows where the expression gets a match:
Visit W3Schools
output: School
The \n character is used to find a newline character.
\n returns the position where the newline character was found. If no match is found, it returns -1.
Search for a newline character in a string:
var str="Visit W3Schools.\nLearn Javascript.";
var patt1=/\n/;
The marked text below shows where the expression gets a match:
Visit W3Schools.\nLearn Javascript.
Output: 16
test()
The test() method searches a string for a specified value, and returns true or false, depending on the result. The
following example searches a string for the character "e":
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
output: true
exec()
The exec() method searches a string for a specified value, and returns the text of the found value. If no match is
found, it returns null. The following example searches a string for the character "e":
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));
output: e
The Window Object
The window object is supported by all browsers. It represent the browsers window.
Window Size
The example displays the browser window's height and width
var w=window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h=window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
Some other methods:
window.open() - open a new window
window.close() - close the current window
window.moveTo() -move the current window
window.resizeTo() -resize the current window
Window Location
The window.location object can be written without the window prefix.
location.hostname returns the domain name of the web host
location.pathname returns the path and filename of the current page
location.port returns the port of the web host (80 or 443)
location.protocol returns the web protocol used (http:// or https://)
The location.href property returns the URL of the current page.
Example: Return the entire URL (of the current page):
<script>
document.write(location.href);
</script>
The output of the code above is:
http://www.w3schools.com/js/js_window_location.asp
Window History Back
The history.back() method loads the previous URL in the history list.
This is the same as clicking the Back button in the browser.
function goBack()
{ window.history.back();}
The history forward() method loads the next URL in the history list.
This is the same as clicking the Forward button in the browser.
function goForward()
{ window.history.forward();}
The window.navigator object can be written without the window prefix.
<div id="example"></div>
<script>
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>";
document.getElementById("example").innerHTML=txt;
</script>
output:
Browser CodeName: Mozilla
Browser Name: Netscape
Browser Version: 5.0 (Windows NT 6.0) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.77
Safari/534.24
Cookies Enabled: true
Platform: Win32
User-agent header: Mozilla/5.0 (Windows NT 6.0) AppleWebKit/534.24 (KHTML, like Gecko)
Chrome/11.0.696.77 Safari/534.24
User-agent language: undefined
Confirm Box
A confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the
user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user
clicks "Cancel", the box returns false.
var r=confirm("Press a button");
if (r==true)
x="You pressed OK!";
else
x="You pressed Cancel!";
Prompt Box
A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops
up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks
"OK" the box returns the input value. If the user clicks "Cancel" the box returns null.
e.g: var person=prompt("Please enter your name","Harry Potter");
if (person!=null)
{
x="Hello " + person + "! How are you today?";
document.getElementById("demo").innerHTML=x;
}
Create and Store a Cookie
In this example we will create a cookie that stores the name of a visitor. The first time a visitor arrives to the web
page, he or she will be asked to fill in her/his name. The name is then stored in a cookie. The next time the visitor
arrives at the same page, he or she will get welcome message.
First, we create a function that stores the name of the visitor in a cookie variable:
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
Get a Cookie Value
Then, we create another function that returns the value of a specified cookie:
function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1)
{
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1)
c_value = null;
else
{
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1)
{
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
The code above uses the indexOf() method to search for a cookie name inside the document's cookie string.
The first indexOf() method will return the position where the cookie is found. The " " + and +"=" is added so that
the method don't find names or values containing the name.
If the method returns -1, the cookie may still exist at the very beginning of the cookie string. To eliminate this,
another search is added, this time without the " " +.
Check a Cookie Value
Last, we create the function that displays a welcome message if the cookie is set, and if the cookie is not set it will
display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the
setCookie function:
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
alert("Welcome again " + username);
else
{
username=prompt("Please enter your name:","");
if (username!=null && username!="")
setCookie("username",username,365);
}
}
CSS
CSS can be added to HTML in the following ways:
Inline - using the style attribute in HTML elements
Internal - using the <style> element in the <head> section
External - using an external CSS file
Inline style takes priority over embedded style sheets, which takes priority over external style sheets.
Background Color: The background-color property defines the background color for an element.
<h2 style="background-color:red;">This is a heading</h2>
Font, Color and Size: The font-family, color, and font-size properties defines the font, color, and size of the text in
an element.
<p style="font-family:arial;color:red;font-size:20px;">A paragraph.</p>
Text Alignment :The text-align property specifies the horizontal alignment of text in an element.
<h1 style="text-align:center;">Center-aligned heading</h1>
CSS Backgrounds
Set the background color of a page
<style>
body
{ background-color:#b0c4de; }
</style>
Set the background color of different elements
<style>
h1{ background-color:#6495ed; }
p { background-color:#e0ffff; }
div { background-color:#b0c4de;}
</style>
Set an image as the background of a page
<style>
body {background-image:url('paper.gif');}
</style>
How to repeat a background image only horizontally
<style>
body
{ background-image:url('gradient2.png');
background-repeat:repeat-x;
}
</style>
How to position a background image
<style>
body
{ background-image:url('img_tree.png');
background-repeat:no-repeat;
background-position:right top;
margin-right:200px;
}
</style>
A fixed background image (this image will not scroll with the rest of the page)
body {
background-image:url('w3css.gif');
background-repeat:no-repeat;
background-attachment:fixed;
}
CSS Text
Set the text color of different elements
<style>
body {color:red;}
h1 {color:#00ff00;}
p.ex {color:rgb(0,0,255);}
</style>
<p class="ex">This is a paragraph with class="ex". This text is blue.</p>
Align the text
<style>
h1 {text-align:center;}
p.date {text-align:right;}
p.main {text-align:justify;}
</style>
<h1>CSS text-align Example</h1>
<p class="date">May, 2009</p>
<p class="main">In my younger and more vulnerable years my father gave me some advice</p>
Remove the line under links
<style>
a {text-decoration:none;}
</style>
<p>Link to: <a href="http://www.w3schools.com">W3Schools.com</a></p>
Decorate the text
<style>
h1 {text-decoration:overline;}
h2 {text-decoration:line-through;}
h3 {text-decoration:underline;}
h4 {text-decoration:blink;}
</style>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
Control the letters in a text
<style>
p.uppercase {text-transform:uppercase;}
p.lowercase {text-transform:lowercase;}
p.capitalize {text-transform:capitalize;}
</style>
<p class="uppercase">This is some text.</p>
<p class="lowercase">This is some text.</p>
<p class="capitalize">This is some text.</p>
Indent text
<style>
p {text-indent:50px;}
</style>
<p>In my younger and more vulnerable</p>
Specify the space between characters
<style>
h1 {letter-spacing:2px;}
h2 {letter-spacing:-3px;}
</style>
Specify the space between lines
<style>
p.small {line-height:70%;}
p.big {line-height:200%;}
</style>
Set the text direction of an element
<style>
div.ex1 {direction:rtl;}
</style>
Increase the white space between words
<style>
p{ word-spacing:30px;}
</style>
Vertical alignment of an image inside text
<style>
img.top {vertical-align:text-top;}
img.bottom {vertical-align:text-bottom;}
</style>
<p>An <img class="top" src="w3schools_logo.gif" alt="W3Schools" width="270" height="50" /> image with a
text-top alignment.</p>
<p>An <img class="bottom" src="w3schools_logo.gif" alt="W3Schools" width="270" height="50" /> image with
a text-bottom alignment.</p>
CSS Fonts
All CSS Font Properties
Property Description
font Sets all the font properties in one declaration
font-family Specifies the font family for text
font-size Specifies the font size of text
font-style Specifies the font style for text
font-variant Specifies whether or not a text should be displayed in a small-caps font
font-weight Specifies the weight of a font
Set the font of a text
<style>
p.serif{font-family:"Times New Roman",Times,serif;}
p.sansserif{font-family:Arial,Helvetica,sans-serif;}
</style>
Set the size of the font
<style>
h1 {font-size:250%;}
h2 {font-size:200%;}
p {font-size:100%;}
</style>
Set the style of the font
<style>
p.normal {font-style:normal;}
p.italic {font-style:italic;}
p.oblique {font-style:oblique;}
</style>
Set the variant of the font
<style>
p.normal {font-variant:normal;}
p.small {font-variant:small-caps;}
</style>
Set the boldness of the font
<style>
p.thick {font-weight:bold;}
</style>
XML:
The Difference Between XML and HTML
XML is not a replacement for HTML.
XML and HTML were designed with different goals:
XML was designed to transport and store data, with focus on what data is
HTML was designed to display data, with focus on how data looks
HTML is about displaying information, while XML is about carrying information.
XML language has no predefined tags. The tags used in HTML are predefined.
XML is a software- and hardware-independent tool for carrying information.
XML Documents Form a Tree Structure
XML documents must contain a root element. This element is "the parent" of all other elements.
The elements in an XML document form a document tree. The tree starts at the root and branches to the lowest
level of the tree.
All elements can have sub elements (child elements):
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
Example:
The image above represents one book in the XML below:
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
The root element in the example is <bookstore>. All <book> elements in the document are contained within
<bookstore>. The <book> element has 4 children: <title>,< author>, <year>, <price>.
XML Attribute Values Must be Quoted
In XML, the attribute values must always be quoted. Study the two XML documents below. The first one is
incorrect, the second is correct:
<note date=12/11/2007>
<to>Tove</to>
<from>Jani</from>
</note>
<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>
There are 5 predefined entity references in XML:
&lt; < less than
&gt; > greater than
&amp; & ampersand
&apos; ' apostrophe
&quot; " quotation mark
e.g: <message>if salary &lt; 1000 then</message>
Avoid XML Attributes?
Some of the problems with using attributes are:
attributes cannot contain multiple values (elements can)
attributes cannot contain tree structures (elements can)
attributes are not easily expandable (for future changes)
Attributes are difficult to read and maintain. Use elements for data. Use attributes for information that is not
relevant to the data.
XML Attributes for Metadata
Sometimes ID references are assigned to elements. These IDs can be used to identify XML elements in much the
same way as the id attribute in HTML. This example demonstrates this:
<messages>
<note id="501">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note id="502">
<to>Jani</to>
<from>Tove</from>
<heading>Re: Reminder</heading>
<body>I will not</body>
</note>
</messages>
The id attributes above are for identifying the different notes. It is not a part of the note itself.
What I'm trying to say here is that metadata (data about data) should be stored as attributes, and the data itself
should be stored as elements.
A "Well Formed" XML document has correct XML syntax.
The syntax rules were described in the previous chapters:
XML documents must have a root element
XML elements must have a closing tag
XML tags are case sensitive
XML elements must be properly nested
XML attribute values must be quoted
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Displaying your XML Files with CSS?
It is possible to use CSS to format an XML document. Below is an example of how to use a CSS style sheet to
format an XML document:
.xml:
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
</CATALOG>
.css:
CATALOG
{
background-color: #ffffff;
width: 100%;
}
CD
{
display: block;
margin-bottom: 30pt;
margin-left: 0;
}
TITLE
{
color: #FF0000;
font-size: 20pt;
}
ARTIST
{
color: #0000FF;
font-size: 20pt;
}
COUNTRY,PRICE,YEAR,COMPANY
{
display: block;
color: #000000;
margin-left: 20pt;
}
The XMLHttpRequest Object
The XMLHttpRequest object is used to exchange data with a server behind the scenes.
Update a web page without reloading the page
Request data from a server after the page has loaded
Receive data from a server after the page has loaded
Send data to a server in the background
Syntax for creating an XMLHttpRequest object:
xmlhttp=new XMLHttpRequest();
XML parser
An XML parser converts an XML document into an XML DOM object - which can then be manipulated with
JavaScript.
Parse an XML Document:
The following code fragment parses an XML document into an XML DOM object:
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","books.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
Parse an XML String:
The following code fragment parses an XML string into an XML DOM object:
txt="<bookstore><book>";
txt=txt+"<title>Everyday Italian</title>";
txt=txt+"<author>Giada De Laurentiis</author>";
txt=txt+"<year>2005</year>";
txt=txt+"</book></bookstore>";
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
Load an XML File
The following example parses an XML document ("note.xml") into an XML DOM object and then extracts some
info from it with a JavaScript:
<body>
<h1>W3Schools Internal Note</h1>
<div>
<b>To:</b> <span id="to"></span><br>
<b>From:</b> <span id="from"></span><br>
<b>Message:</b> <span id="message"></span>
</div>
<script>
txt="<note>";
txt=txt+"<to>Tove</to>";
txt=txt+"<from>Jani</from>";
txt=txt+"<heading>Reminder</heading>";
txt=txt+"<body>Don't forget me this weekend!</body>";
txt=txt+"</note>";
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
document.getElementById("to").innerHTML=xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValu
e;
document.getElementById("from").innerHTML=xmlDoc.getElementsByTagName("from")[0].childNodes[0].nod
eValue;
document.getElementById("message").innerHTML=xmlDoc.getElementsByTagName("body")[0].childNodes[0].
nodeValue;
</script>
display:
W3Schools Internal Note
To: Tove
From: Jani
Message: Don't forget me this weekend!
Load an XML String
<h1>W3Schools Internal Note</h1>
<div>
<b>To:</b> <span id="to"></span><br>
<b>From:</b> <span id="from"></span><br>
<b>Message:</b> <span id="message"></span>
</div>
<script>
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
xmlhttp.open("GET","note.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.getElementById("to").innerHTML=xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValu
e;
document.getElementById("from").innerHTML=xmlDoc.getElementsByTagName("from")[0].childNodes[0].nod
eValue;
document.getElementById("message").innerHTML=xmlDoc.getElementsByTagName("body")[0].childNodes[0].
nodeValue;
</script>
CDATA:
Everything inside a CDATA section is ignored by the parser.
A CDATA section starts with "<![CDATA[" and ends with "]]>":
Get the Value of an Element
The XML file used in the examples below: books.xml.
The following example retrieves the text value of the first <title> element:
txt=xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
Get the Value of an Attribute
The following example retrieves the text value of the "lang" attribute of the first <title> element:
txt=xmlDoc.getElementsByTagName("title")[0].getAttribute("lang");
Change the Value of an Element
The following example changes the text value of the first <title> element:
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Cooking";
Create a New Attribute
The XML DOM setAttribute() method can be used to change the value of an existing attribute, or to create a new
attribute.
The following example adds a new attribute (edition="first") to each <book> element:
x=xmlDoc.getElementsByTagName("book");
for(i=0;i<x.length;i++)
x[i].setAttribute("edition","first");
Create an Element
The XML DOM createElement() method creates a new element node.
The XML DOM createTextNode() method creates a new text node.
The XML DOM appendChild() method adds a child node to a node (after the last child).
To create a new element with text content, it is necessary to both create a new element node and a new text node,
and then append it to an existing node.
The following example creates a new element (<edition>), with the following text: First, and adds it to the first
<book> element:
newel=xmlDoc.createElement("edition");
newtext=xmlDoc.createTextNode("First");
newel.appendChild(newtext);
x=xmlDoc.getElementsByTagName("book");
x[0].appendChild(newel);
display:
title: Everyday Italian
author: Giada De Laurentiis
year: 2005
price: 30.00
edition: First
Example explained:
Create an <edition> element
Create a text node with the following text: First
Append the text node to the new <edition> element
Append the <edition> element to the first <book> element
Remove an Element
The following example removes the first node in the first <book> element:
x=xmlDoc.getElementsByTagName("book")[0];
x.removeChild(x.childNodes[0]);
JSON
JSON: JavaScript Object Notation.
JSON is syntax for storing and exchanging text information. Much like XML.
JSON is smaller than XML, and faster and easier to parse.
e.g: {
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
The employees object is an array of 3 employee records (objects).
JSON uses JavaScript syntax for describing data objects, but JSON is still language and platform independent.
JSON parsers and JSON libraries exists for many different programming languages.
The JSON text format is syntactically identical to the code for creating JavaScript objects. Because of this
similarity, instead of using a parser, a JavaScript program can use the built-in eval() function and execute JSON
data to produce native JavaScript objects.
E.g:
<p>
Name: <span id="jname"></span><br>
Age: <span id="jage"></span><br>
Address: <span id="jstreet"></span><br>
Phone: <span id="jphone"></span><br>
</p>
<script>
var JSONObject = {
"name":"John Johnson",
"street":"Oslo West 16",
"age":33,
"phone":"555 1234567"};
document.getElementById("jname").innerHTML=JSONObject.name
document.getElementById("jage").innerHTML=JSONObject.age
document.getElementById("jstreet").innerHTML=JSONObject.street
document.getElementById("jphone").innerHTML=JSONObject.phone
</script>
display:
Name: John Johnson
Age: 33
Address: Oslo West 16
Phone: 555 1234567
Much Like XML
JSON is plain text
JSON is "self-describing" (human readable)
JSON is hierarchical (values within values)
JSON can be parsed by JavaScript
JSON data can be transported using AJAX
Much Unlike XML
No end tag
Shorter
Quicker to read and write
Can be parsed using built-in JavaScript eval()
Uses arrays
No reserved words
For AJAX applications, JSON is faster and easier than XML:
Using XML
Fetch an XML document
Use the XML DOM to loop through the document
Extract values and store in variables
Using JSON
Fetch a JSON string
eval() the JSON string
JSON data is written as name/value pairs.
A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:
"firstName" : "John"
JSON values can be:
A number (integer or floating point)
A string (in double quotes)
A Boolean (true or false)
An array (in square brackets)
An object (in curly brackets)
null
JSON Uses JavaScript Syntax
Because JSON uses JavaScript syntax, no extra software is needed to work with JSON within JavaScript.
With JavaScript you can create an array of objects and assign data to it like this:
var employees = [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
];
The first entry in the JavaScript object array can be accessed like this:
employees[0].lastName;
Converting a JSON Text to a JavaScript Object
One of the most common use of JSON is to fetch JSON data from a web server (as a file or as an HttpRequest),
convert the JSON data to a JavaScript object, and then it uses the data in a web page.
JSON Example - Object From String
Create a JavaScript string containing JSON syntax:
var txt = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
Since JSON syntax is a subset of JavaScript syntax, the JavaScript function eval() can be used to convert a JSON
text into a JavaScript object.
The eval() function uses the JavaScript compiler which will parse the JSON text and produce a JavaScript object.
The text must be wrapped in parenthesis to avoid a syntax error:
var obj = eval ("(" + txt + ")");
Use the JavaScript object in your page:
<p>
First Name: <span id="fname"></span><br />
Last Name: <span id="lname"></span><br />
</p>
<script>
document.getElementById("fname").innerHTML = obj.employees[1].firstName
document.getElementById("lname").innerHTML = obj.employees[1].lastName
</script>
display:
First Name: Anna
Last Name: Smith
Xquery
e.g:
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
The doc() function is used to open the "books.xml" file:
doc("books.xml")
The following path expression is used to select all the title elements in the "books.xml" file:
doc("books.xml")/bookstore/book/title
The XQuery above will extract the following:
<title lang="en">Everyday Italian</title>
<title lang="en">Harry Potter</title>
<title lang="en">XQuery Kick Start</title>
<title lang="en">Learning XML</title>
The following predicate is used to select all the book elements under the bookstore element that have a price
element with a value that is less than 30:
doc("books.xml")/bookstore/book[price<30]
Xquery FLWOR Expressions
doc("books.xml")/bookstore/book[price>30]/title
The expression above will select all the title elements under the book elements that are under the bookstore
element that have a price element with a value that is higher than 30.
The following FLWOR expression will select exactly the same as the path expression above:
for $x in doc("books.xml")/bookstore/book
where $x/price>30
return $x/title
With FLWOR you can sort the result:
for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title
Present the Result In an HTML List
Look at the following XQuery FLWOR expression:
for $x in doc("books.xml")/bookstore/book/title
order by $x
return $x
The expression above will select all the title elements under the book elements that are under the bookstore
element, and return the title elements in alphabetical order. Now we want to list all the book-titles in our bookstore
in an HTML list. We add <ul> and <li> tags to the FLWOR expression:
<ul>
{
for $x in doc("books.xml")/bookstore/book/title
order by $x
return <li>{$x}</li>
}
</ul>
The result of the above will be:
<ul>
<li><title lang="en">Everyday Italian</title></li>
<li><title lang="en">Harry Potter</title></li>
<li><title lang="en">Learning XML</title></li>
<li><title lang="en">XQuery Kick Start</title></li>
</ul>
Now we want to eliminate the title element, and show only the data inside the title element:
<ul>
{
for $x in doc("books.xml")/bookstore/book/title
order by $x
return <li>{data($x)}</li>
}
</ul>
The result will be (an HTML list):
<ul>
<li>Everyday Italian</li>
<li>Harry Potter</li>
<li>Learning XML</li>
<li>XQuery Kick Start</li>
</ul>
XQuery Basic Syntax Rules
Some basic syntax rules:
XQuery is case-sensitive
XQuery elements, attributes, and variables must be valid XML names
An XQuery string value can be in single or double quotes
An XQuery variable is defined with a $ followed by a name, e.g. $bookstore
XQuery comments are delimited by (: and :), e.g. (: XQuery Comment :)
XQuery Conditional Expressions
"If-Then-Else" expressions are allowed in Xquery. Look at the following example:
for $x in doc("books.xml")/bookstore/book
return if ($x/@category="CHILDREN")
then <child>{data($x/title)}</child>
else <adult>{data($x/title)}</adult>
Notes on the "if-then-else" syntax: parentheses around the if expression are required. else is required, but it can be
just else (). The result of the example above will be:
<adult>Everyday Italian</adult>
<child>Harry Potter</child>
<adult>Learning XML</adult>
<adult>XQuery Kick Start</adult>
Add HTML Elements and Text
Now, we want to add some HTML elements to the result. We will put the result in an HTML list - together with
some text:
<html>
<body>
<ul>
{
for $x in doc("books.xml")/bookstore/book
order by $x/title
return <li>{data($x/title)}. Category: {data($x/@category)}</li>
}
</ul>
</body>
</html>
The XQuery expression above will generate the following result:
<html>
<body>
<ul>
<li>Everyday Italian. Category: COOKING</li>
<li>Harry Potter. Category: CHILDREN</li>
<li>Learning XML. Category: WEB</li>
<li>XQuery Kick Start. Category: WEB</li>
</ul>
</body>
</html>
Add Attributes to HTML Elements
Next, we want to use the category attribute as a class attribute in the HTML list:
<ul>
{
for $x in doc("books.xml")/bookstore/book
order by $x/title
return <li class="{data($x/@category)}">{data($x/title)}</li>
}
</ul>
The XQuery expression above will generate the following result:
<body>
<ul>
<li class="COOKING">Everyday Italian</li>
<li class="CHILDREN">Harry Potter</li>
<li class="WEB">Learning XML</li>
<li class="WEB">XQuery Kick Start</li>
</ul>
</body>
The for Clause
for $x in (1 to 5)
return <test>{$x}</test>
The at keyword can be used to count the iteration:
for $x at $i in doc("books.xml")/bookstore/book/title
return <book>{$i}. {data($x)}</book>
Result:
<book>1. Everyday Italian</book>
<book>2. Harry Potter</book>
<book>3. XQuery Kick Start</book>
<book>4. Learning XML</book>
It is also allowed with more than one in expression in the for clause. Use comma to separate each in expression:
for $x in (10,20), $y in (100,200)
return <test>x={$x} and y={$y}</test>
Result:
<test>x=10 and y=100</test>
<test>x=10 and y=200</test>
<test>x=20 and y=100</test>
<test>x=20 and y=200</test>
The let Clause
The let clause allows variable assignments and it avoids repeating the same expression many times. The let clause
does not result in iteration.
let $x := (1 to 5)
return <test>{$x}</test>
Result:
<test>1 2 3 4 5</test>
The where Clause
The where clause is used to specify one or more criteria for the result:
where $x/price>30 and $x/price<100
The order by Clause
The order by clause is used to specify the sort order of the result. Here we want to order the result by category and
title:
for $x in doc("books.xml")/bookstore/book
order by $x/@category, $x/title
return $x/title
The return Clause
The return clause specifies what is to be returned.
for $x in doc("books.xml")/bookstore/book
return $x/title
Examples of Function Calls
A call to a function can appear where an expression may appear. Look at the examples below:
Example 1: In an element
<name>{upper-case($booktitle)}</name>
Example 2: In the predicate of a path expression
doc("books.xml")/bookstore/book[substring(title,1,5)='Harry']
Example 3: In a let clause
let $name := (substring($booktitle,1,4))
Xpath
XPath is used to navigate through elements and attributes in an XML document.
Selecting Nodes
XPath uses path expressions to select nodes in an XML document. The node is selected by following a path or
steps. The most useful path expressions are listed below:
Expression Description
nodename Selects all nodes with the name "nodename" bookstore Selects all nodes with the name "bookstore"
/ Selects from the root node /bookstore Selects the root element bookstore
// Selects nodes in the document from the
current node that match the selection no
matter where they are
Bookstore/book Selects all book elements that are children of
bookstore
. Selects the current node //book Selects all book elements no matter where they are
in the document
.. Selects the parent of the current node Bookstore//book Selects all book elements that are descendant of the
bookstore element, no matter where they are under
the bookstore element
@ Selects attributes //@lang Selects all attributes that are named lang
Predicates
Predicates are used to find a specific node or a node that contains a specific value.
Predicates are always embedded in square brackets.
In the table below we have listed some path expressions with predicates and the result of the expressions:
Path Expression Result
/bookstore/book[1] Selects the first book element that is the child of the bookstore element.
/bookstore/book[last()] Selects the last book element that is the child of the bookstore element
/bookstore/book[last()-1] Selects the last but one book element that is the child of the bookstore element
/bookstore/book[position()<3] Selects the first two book elements that are children of the bookstore element
//title[@lang] Selects all the title elements that have an attribute named lang
//title[@lang='eng'] Selects all the title elements that have an attribute named lang with a value of 'eng'
/bookstore/book[price>35.00] Selects all the book elements of the bookstore element that have a price element with a
value greater than 35.00
/bookstore/book[price>35.00]/title Selects all the title elements of the book elements of the bookstore element that have a
price element with a value greater than 35.00
Database
DB2
What is a data page?
-A data page is a unit of data which can be retrieved. It could be either 4K or 32K (depending on the way
table is defined).
What is meant by DB2 bind?
A DB2 bind is a process that builds an access path of the application to the relational database i.e. DB2 tables.
DB2 bind process does the following
Validates :-Sql statements are validated for valid tables, view and column names. Syntax errors are checked
so that these can be corrected.
Verifies :- Bind process verifies that the user or the process is authorized to bind the plan.
Selects :-Selects the access path from the application program to the DB2 objects.
What is cursor stability?
Ans:-Cursor stability is a type of isolation level which makes sure that the data read by an application program is
locked only while its used, as soon as the cursor moves away to another page of data the lock on the previous page
is released so that other programs can access the data for updation. This form of isolation level is high on
concurrency but low on integrity of data.
How to fetch data from more than one table in a single SQL statement?
For this we can use Joins, unions or nested selects.
What is CHECK constraint. Explain with example
A CHECK constraint is one of the constraints to ensure data integrity
- CHECK constraint is specified as a condition / criteria
- The value that is to be inserted or updated in a table, need to be tested by the CHECK constraint
- If the value is meeting the criteria, then the data is inserted or updated in the designated column of a
table
- CHECK constraint is used at the time of creation of a table
The following example illustrates the use of CHECK constraint
CREATE TABLE PRODUCT (PROD_ID INTEGER NOT NULL,
QUANTITY INTEGER CHECK (QUANTITY >= 1).
What is an access path? The path that is used to get to data specified in SQL statements.
What is an alias?
It is an alternate name that can be used in SQL statements to refer to a table or view in the same or remote DB2
subsystem.
Explain what a plan is?
Plan is a DB2 object (produced during the bind process) that associates one or more database request modules
with a plan name.
Where are plans stored?
Each plan is defined uniquely in the SYSIBM.SYSPLANS table to correspond to the transaction (s) that are to
execute that plan.
What is a DB2 bind?
Bind is a process that builds access paths to DB2 tables. A bind uses the Database Request Modules(s) from the
DB2 pre-compile step as input and produces an application plan. It also checks the users authority and validates
the SQL statements in the DBRM(s).
What information is used as input to the bind process?
The database request module produced during the pre-compile. The SYSIBM.SYSSTMT table of the DB2
catalog.
What is meant by AUTO COMMIT?
AUTO COMMIT is a SPUFI option that commits the effects of SQL statements automatically if they are
successfully executed.
What is a base table?
A base table is a real table a table that physically exists in that there are physical stored records.
What is the function of buffer manager?
The buffer manager is the DB2 component responsible for physically transferring data between an external
medium and (virtual) storage (performs the actual I/O operations). It minimizes the amount of physical I/O
actually performed with sophisticated buffering techniques(i.e., read-ahead buffering and look-aside buffering).
What is a buffer pool?
A buffer pool is main storage that is reserved to satisfy the buffering requirements for one or more tablespaces or
indexes, and is made up of either 4K or 32K pages.
How many buffer pools are there in DB2? There are four buffer pools: BP0, BP1, BP2, and BP32.
On the create tablespace, what does the CLOSE parameter do?
CLOSE physically closes the tablespace when no one is working on the object. DB2 will logically close
tablespaces.
What will the COMMIT accomplish?
COMMIT will allow data changes to be permanent. This then permits the data to be accessed by other units of
work. When a COMMIT occurs, locks are freed so other applications can reference the just committed data.
What is the function of the Data Manager?
The Data Manager is a DB2 component that manager the physical databases. It invokes other system components,
as necessary, to perform detailed functions such as locking, logging, and physical I/O operations (such as search,
retrieval, update, and index maintenance).
What is a Database Request Module(DBRM)?
A DBRM is a DB2 component created by the DB2 pre-compiler containing the SQL source statements extracted
from the application program. DBRMs are input to the bind process.
What is a data page?
A data page is a unit of retrievable data, either 4K or 32K (depending on how the table is defined), containing user
or catalog information.
What are data types?
They are attributes of columns, literals, and host variables. The data types are SMALLINT, INTEGER, FLOAT,
DECIMAL, CHAR, VARCHAR, DATE and TIME.
What does DSNDB07 database do?
DSNDB07 is where DB2 does its sorting. It includes DB2s sort work area and external storage.
What will the FREE command do to a plan? It will drop(delete) that existing plan.
What will the DB2 optimizer do?
The optimizer is a DB2 component that processes SQL statements and selects the access paths.
What is a page? This is the unit of storage within a table space or indexspace that is accessed by DB2.
What is pagespace?
Pagespace refers to either to an unpartitioned table, to an index space, or to a single partition of a partitioned table
of index space.
What is a recovery log?
A recovery log is a collection of records that describes the sequence of events that occur in DB2. The information
is needed for recovery in the event of a failure during execution.
What are the three types of page locks that can be held? Exclusive, update, and share.
How are write I/Os from the buffer pool executed? Asynchronously.
What is a DB2 catalog?
The DB2 catalog is a set of tables that contain information about all of the DB2 objects(tables, views, plans etc.).
What information can you find in SYSIBM.SYSLINKS table?
The SYSIBM.SYSLINKS table contains information about the links between tables created by referential
constraints.
Where would you find information about the type of database authority held by the user?SYSIBM.SYSDBAUTH.
Where could you look if you had a question about whether a column has been defined as an index?
This information can be found in SYSIBM.SYSINDEXES.
Once you create a view, where would information about the view be stored?
When a view is created, system information about the view is stored in SYSIBM.SYSVIEWS.
How do you leave the cursor open after issuing a COMMIT?
Use WITH HOLD option in DECLARE CURSOR statement.
What is the physical storage length of each of the following DB2 data types: DATE, TIME, TIMESTAMP?
DATE: 4bytes, TIME: 3bytes, TIMESTAMP: 10bytes
How can you quickly find out the number of rows updated after an update statement?
Check the value stored in SQLERRD(3).
What are the various locking levels available? PAGE, TABLE, TABLESPACE
What are the disadvantages of PAGE level lock? High resource utilization if large updates are to be done
What are the various locks available? SHARE, EXCLUSIVE, UPDATE
Can I use LOCK TABLE on a view? No. To lock a view, take lock on the underlying tables.
What happens to the PLAN if index used by it is dropped?
Plan is marked as invalid. The next time the plan is accessed, it is rebound.
What are PACKAGES ? They contain executable code for SQL statements for one DBRM.
What are the advantages of using a PACKAGE?
The advantages of using PACKAGE are:
1. Avoid having to bind a large number of DBRM members into a plan
2. Avoid cost of a large bind
3. Avoid the entire transaction being unavailable during bind and automatic rebind of a plan
4. Minimize fallback complexities if changes result in an error.
5.
Lot of updates have been done on a table due to which indexes have gone haywire. What do you do?
Looks like index page split has occurred. DO a REORG of the indexes.
What is dynamic SQL? Dynamic SQL is a SQL statement created at program execution time.
When is the access path determined for dynamic SQL? At run time, when the PREPARE statement is issued.
How does DB2 store NULL physically?
As an extra-byte prefix to the column value. Physically, the null prefix is Hex 00 if the value is present and Hex
FF if it is not.
What is RUNSTATS?
A DB2 utility used to collect statistics about the data values in tables which can be used by the optimizer to decide
the access path. It also collects statistics used for space management. These statistics are stored in DB2 catalog
tables.
1. inner join vs. outer join
select * from employee left outer join location
on employee.empID = location.empID;
select * from employee right join location
on employee.empID = location.empID;
select * from employee, location where employee.empID = location.empID
Whats referential integrity?
Suppose company X has 2 tables, an Employee table, and an Employee Salary table. In the Employee table we
have 2 columns the employee ID and the employee name. In the Employee Salary table, we have 2 columns
the employee ID and the salary for the given ID.
Now, suppose we wanted to remove an employee because he no longer works at company X. Then, we would
remove his entry in the Employee table. Because he also exists in the Employee Salary table, we would also have
to manually remove him from there also. Manually removing the employee from the Employee Salary table can
become quite a pain.
By enforcing referential integrity, we wouldnt have to manually delete him from the Employee Salary table (or
any others). Heres how: first we would define the employee ID column in the Employee table to be our primary
key. Then, we would define the employee ID column in the Employee Salary table to be a foreign key that points
to a primary key that is the employee ID column in the Employee table. Once we define our foreign to primary
key relationship, we would need to add constraint to the Employee Salary table. The constraint that we would add
in particular is called a cascading delete this would mean that any time an employee is removed from the
Employee table, any entries that employee has in the Employee Salary table would also automatically be removed
from the Employee Salary table.
In SQL, whats the difference between the having clause and the where clause?
The difference between the having and where clause is best illustrated by an example. Suppose we have a table
called emp_bonus as shown below. Note that the table has multiple entries for employees A and B.
If we want to calculate the total bonus that each employee received, then we would write a SQL statement like
this:
select employee, sum(bonus) from emp_bonus group by employee;
Running the SQL above would return this:
Now, suppose we wanted to find the employees who received more than $1,000 in bonuses for the year of 2007.
You might think that we could write a query like this:
select employee, sum(bonus) from emp_bonus
group by employee where sum(bonus) > 1000;
but The WHERE clause does not work with aggregates like SUM
Now, the correct sql will look like this:
select employee, sum(bonus) from emp_bonus
group by employee having sum(bonus) > 1000;
So we can see that the difference between the having and where clause in sql is that the where clause can not be
used with aggregates, but the having clause can. One way to think of it is that the having clause is an additional
filter to the where clause.
What is an index?
So, what is an index? Well, an index is a data structure (most commonly a B- tree) that stores the values for a
specific column in a table. An index is created on a column of atable. So, the key points to remember are that an
index consists of column values from one table, and that those values are stored in a data structure.
B- trees are the most commonly used data structures for indexes. The reason B- trees are the most popular data
structure for indexes is because of the fact that they time efficient because look-ups, deletions, and insertions
can all be done in logarithmic time. And, another major reason B- trees are more commonly used is because the
data that is stored inside the B- tree can be sorted.
Hash tables are another data structure that you may see being used as indexes these indexes are commonly
referred to as hash indexes. The reason hash indexes are used is because hash tables are extremely efficient when
it comes to just looking up values. So, queries that compare for equality to a string can retrieve values very fast if
they use a hash index. For instance, the query we discussed earlier (SELECT * FROM Employee WHERE
Employee_Name = Jesus) could benefit from a hash index created on the Employee_Name column. The way a
hash index would work is that the column value will be the key into the hash table and the actual value mapped to
that key would just be a pointer to the row data in the table. Since a hash table is basically an associative array, a
typical entry would look something like Jesus => 028939, where 028939 is a reference to the table row
where Jesus is stored in memory.
The disadvantages of a hash index
Hash tables are not sorted data structures, and there are many types of queries which hash indexes can not even
help with. For instance, suppose you want to find out all of the employees who are less than 40 years old. How
could you do that with a hash table index? Well, its not possible because a hash table is only good for looking up
key value pairs.
How does an index improve performance?
Because an index is basically a data structure that is used to store column values, looking up those values becomes
much faster. And, if an index is using the most commonly used data structure type a B- tree then the data
structure is also sorted. Having the column values be sorted can be a major performance enhancement read on to
find out why.
What exactly is inside a database index?
So, now you know that a database index is created on a column in a table, and that the index stores the values in
that specific column. But, it is important to understand that a database index does not store the values in the other
columns of the same table. For example, if we create an index on the Employee_Name column, this means that
the Employee_Age and Employee_Address column values are not also stored in the index. If we did just store all
the other columns in the index, then it would be just like creating another copy of the entire table which would
take up way too much space and would be very inefficient.
An index also stores a pointer to the table row
So, the question is if the value that we are looking for is found in an index (like Jesus) , how does it find the
other values that are in the same row (like the address of Jesus and his age)? Well, its quite simple database
indexes also store pointers to the corresponding rows in the table. A pointer is just a reference to a place in
memory where the row data is stored on disk. So, in addition to the column value that is stored in the index, a
pointer to the row in the table where that value lives is also stored in the index. This means that one of the values
(or nodes) in the index for an Employee_Name could be something like (Jesus, 082829), where 082829 is the
address on disk (the pointer) where the row data for Jesus is stored. Without that pointer all you would have is a
single value, which would be meaningless because you would not be able to retrieve the other values in the same
row like the address and the age of an employee.
How does a database know when to use an index?
When a query like SELECT * FROM Employee WHERE Employee_Name = Jesus is run, the database will
check to see if there is an index on the column(s) being queried. Assuming the Employee_Name column does
have an index created on it, the database will have to decide whether it actually makes sense to use the index to
find the values being searched because there are some scenarios where it is actually less efficient to use the
database index, and more efficient just to scan the entire table.
How to create an index in SQL:
Heres what the actual SQL would look like to create an index on the Employee_Name column from our example
earlier:
CREATE INDEX name_index ON Employee (Employee_Name)
How to create a multi-column index in SQL:
We could also create an index on two of the columns in the Employee table , as shown in this SQL:
CREATE INDEX name_index ON Employee (Employee_Name, Employee_Age)
What is a self join?
Explain it with an example
A self join is basically when a join is done on the same table the best way to think of it is that we have 2
identical copies of the table, and we want to join them based on some condition that we define. That condition will
be our join predicate
we want to find all the employees who have the same location as Joe so if we are doing a join we would want to
make sure that the location is the same and that the employee name is Joe. So, our join predicate would be where
e1.employee_location = e2.employee_location AND employee_name = "Joe". Note that e1 and e2 will represnt
the 2 employee tables that we are doing a self join on. Now, here is what the SQL for a self join would look like to
solve this problem:
SELECT e1.employee_name
FROM employee e1, employee e2
WHERE e1.employee_location = e2.employee_location
AND e2.employee_name="Joe";
Nosql
NoSQLNoSQL Database Types
1. Column Store Each storage block containsEach storage block contains
data from only one columndata from only one column
2. Document Store stores documents made up ofstores documents made up of
tagged elementstagged elements
3. Key-Value Store Hash table of keysHash table

Вам также может понравиться