HTML and Java Script
HTML and Java Script
INTRODUCTION:
</body>
</html>
Example Explained
The <!DOCTYPE html> declaration defines this document to be HTML
The <html> element is the root element of an HTML page
The <head> element contains meta information about the document
The <title> element specifies a title for the document
The <body> element contains the visible page content
The <h1> element defines a large heading
The <p> element defines a paragraph
HTML Tags
Web Browsers
The purpose of a web browser (Chrome, IE, Firefox, Safari) is to read HTML documents
and display them.
The browser does not display the HTML tags, but uses them to determine how to
display the document:
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
Note: Only the content inside the <body> section (the white area above) is displayed in
a browser.
The <!DOCTYPE> declaration represents the document type, and helps browsers to
display web pages correctly.
It must only appear once, at the top of the page (before any HTML tags).
The <!DOCTYPE> declaration is not case sensitive.
The <!DOCTYPE> declaration for HTML5 is:
<!DOCTYPE html>
JAVASCRIPT
INTRODUCTION:
ACCESSING DOCUMENT:
Being a scripting language, JavaScript cannot run on its own. In fact, the browser is
responsible for running JavaScript code. When a user requests an HTML page with
JavaScript in it, the script is sent to the browser and it is up to the browser to execute
it. The main advantage of JavaScript is that all modern web browsers support
JavaScript. So, you do not have to worry about whether your site visitor uses Internet
Explorer, Google Chrome, Firefox or any other browser. JavaScript will be supported.
Also, JavaScript runs on any operating system including Windows, linux or Mac.
Thus, JavaScript overcomes the main disadvantages of VBScript (Now deprecated)
which is limited to just IE and Windows.
Example:
<html>
<head>
<script type="text/javascript">
alert("Hello World!");
</script>
</head>
<body>
</body>
</html>
HTML BASIC:
HTML Documents
All HTML documents must start with a document type declaration: <!DOCTYPE html>.
The HTML document itself begins with <html> and ends with </html>.
The visible part of the HTML document is between <body> and </body>.
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
HTML Headings
<h1> defines the most important heading. <h6> defines the least important heading:
Example
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
HTML Paragraphs
Example
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
HTML Links
HTML links are defined with the <a> tag:
Example
<a href="https://www.w3schools.com">This is a link</a>
HTML Images
The source file (src), alternative text (alt), width, and height are provided as attributes:
Example
<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">
HTML Buttons
Example
<button>Click me</button>
HTML Lists
Example
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
HTML Elements
An HTML element usually consists of a start tag and end tag, with the content inserted
in between:
HTML elements with no content are called empty elements. Empty elements do not
have an end tag, such as the <br> element (which indicates a line break).
</body>
</html>
Example Explained
<html>
<body>
</body>
</html>
The <body> element defines the document body.
It has a start tag <body> and an end tag
</body>.
The element content is two other HTML elements (<h1> and <p>).
<body>
</body>
Example
<html>
<body>
<p>This is a paragraph
<p>This is a paragraph
</body>
</html>
The example above works in all browsers, because the closing tag is considered
optional.
Never rely on this. It might produce unexpected results and/or errors if you forget
the end tag.
<br> is an empty element without a closing tag (the <br> tag defines a line break). Empty elements can
HTML does not require empty elements to be closed. But if you want stricter validation, or if you need to m
HTML Attributes
Example
<img src="img_girl.jpg">
The width and height Attributes
Images in HTML have a set of size attributes, which specifies the width and height of
the image:
Example
<img src="img_girl.jpg" width="500" height="600">
The image size is specified in pixels: width="500" means 500 pixels wide.
The alt attribute specifies an alternative text to be used, when an image cannot be displayed.
The value of the attribute can be read by screen readers. This way, someone "listening"
to the webpage, e.g. a vision impaired person, can "hear" the element.
Example
<img src="img_girl.jpg" alt="Girl with a jacket">
The alt attribute is also useful if the image does not exist.
Example
See what happens if we try to display an image that does not exist:
The style attribute is used to specify the styling of an element, like color, font, size etc.
Example
<p style="color:red">I am a
paragraph</p> The lang Attribute
The language of the document can be declared in the <html> tag.
The language is declared with the lang attribute.
Declaring a language is important for accessibility applications (screen readers) and
search engines:
<!DOCTYPE html>
<html lang="en-US">
<body>
...
</body>
</html>
The first two letters specify the language (en). If there is a dialect, use two more letters
(US).
Here, a title attribute is added to the <p> element. The value of the title attribute will be
displayed as a tooltip when you mouse over the paragraph:
Example
<p title="I'm a
tooltip"> This is a
paragraph.
</p>
The title attribute can be written with uppercase or lowercase like title or TITLE.
W3C recommends lowercase in HTML, and demands lowercase for stricter document
types like XHTML.
The HTML standard does not require quotes around attribute values.
The href attribute, demonstrated above, can be written without quotes:
Bad
<a href=https://www.w3schools.com>
Good
<a href="https://www.w3schools.com">
W3C recommends quotes in HTML, and demands quotes for stricter document types
like XHTML.
Sometimes it is necessary to use quotes. This example will not display the title attribute
correctly, because it contains a space:
Example
<p title=About W3Schools>
Single or Double Quotes?
Double quotes around attribute values are the most common in HTML, but single quotes can also be us
In some situations, when the attribute value itself contains double quotes, it is necessary to use single q
Or vice versa:
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
The color property defines the text color for an HTML element:
Example
<h1 style="color:blue;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>
HTML Fonts
The font-family property defines the font to be used for an HTML element:
Example
<h1 style="font-family:verdana;">This is a heading</h1>
<p style="font-family:courier;">This is a paragraph.</p>
HTML Text Size
The font-size property defines the text size for an HTML element:
Example
<h1 style="font-size:300%;">This is a heading</h1>
<p style="font-size:160%;">This is a paragraph.</p>
The text-align property defines the horizontal text alignment for an HTML element:
Example
<h1 style="text-align:center;">Centered Heading</h1>
<p style="text-align:center;">Centered paragraph.</p>
Common uses for JavaScript are image manipulation, form validation, and dynamic
changes of content.
To select an HTML element, JavaScript very often uses the document.getElementById() method.
This JavaScript example writes "Hello JavaScript!" into an HTML element with id="demo":
Example
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
A Taste of JavaScript
The <noscript> tag is used to provide an alternate content for users that have disabled
scripts in their browser or have a browser that doesn't support client-side scripts:
Example
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
<noscript>Sorry, your browser does not support JavaScript!</noscript>
<!DOCTYPE html>
<meta charset="UTF-8">
A viewport meta tag should make the web site work on all devices and screen resolutions:
W3.CSS should take care of all our styling needs and all device and browser differences:
Inside the <body> element of our web site we will use our "Layout Picture" and create:
A navigation bar
A slide show
A header
Some sections and articles
A footer
SEMANTIC ELEMENTS
HTML introduced several new semantic elements. Semantic elements are important to
use because they define the structure of web pages and helps screen readers and
search engines to read the page correctly.
The <section> element can be used to define a part of a website with related content. The <article> elem
The <header> element can be used to define a header (in a document, a section, or an article).
The <footer> element can be used to define a footer (in a document, a section, or an
article).
We can use a <nav> or <div> element as a container for the navigation links.
The w3-bar class is a container for navigation links.
The w3-black class defines the color of the navigation bar.
The w3-bar-item and w3-button class styles the navigation links inside the bar.
Slide Show
For the slide show we can use a <section> or <div> element as a picture container:
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex =
1} x[myIndex-1].style.display =
"block"; setTimeout(carousel, 3000);
}
SECTIONS AND ARTICLES
Looking at the "Layout Draft" we can see that the next step is to create articles.
First we will create a <section> or <div> element containing band information:
<section class="w3-container w3-center" style="max-width:600px">
<h2 class="w3-wide">THE BAND</h2>
<p class="w3-opacity"><i>We love music</i></p>
</section>
The w3-container class takes care of standard padding.
The w3-center class centers the content.
The w3-wide class provides a wider heading.
The w3-opacity class provides text transparency.
The max-width style sets a maximum with of the band description
section. Then we will add a paragraph describing the band:
<section class="w3-container w3-content w3-center" style="max-width:600px">
<p class="w3-justify">
We have created a fictional band website. Lorem ipsum dolor sit amet, consectetur
adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua.</p>
</section>
The w3-justify class justifies the text's right and left margins.
Then create a <section> or <div> with an <article> or <div> about each band-member:
Footer
CSS Syntax
Example
p{
color: red;
text-align: center;
}
CSS Selectors
CSS selectors are used to "find" (or select) HTML elements based on their element name,
id, class, attribute, and more.
You can select all <p> elements on a page like this (in this case, all <p> elements will
be center-aligned, with a red text color):
Example
p{
text-align: center;
color: red;
}
The id Selector
The id selector uses the id attribute of an HTML element to select a specific element.
The id of an element should be unique within a page, so the id selector is used to select
one unique element!
To select an element with a specific id, write a hash (#) character, followed by the id of
the element.
The style rule below will be applied to the HTML element with id="para1":
Example
#para1 {
text-align: center;
color: red;
}
The class Selector
To select elements with a specific class, write a period (.) character, followed by the
name of the class.
In the example below, all HTML elements with class="center" will be red and center-
aligned:
Example
.center {
text-align: center;
color: red;
}
You can also specify that only specific HTML elements should be affected by a class.
In the example below, only <p> elements with class="center" will be center-aligned:
Example
p.center {
text-align: center;
color: red;
}
In the example below, the <p> element will be styled according to class="center" and to
class="large":
Example
Grouping Selectors
If you have elements with the same style definitions, like this:
h1 {
text-align: center;
color: red;
}
p{
text-align: center; color: red;
}
It will be better to group the selectors, to minimize the code. To group
selectors, separate each selector with a comma.
h2 {
text-align: center;
color: red;
}
In the example below we have grouped the selectors from the code above:
Example
h1, h2, p {
text-align: center;
color: red;
}
Colors are specified using predefined color names, or RGB, HEX, HSL, RGBA, HSLA
values.
Color Names
Background Color
Example
Text Color
You can set the color of text:
Example
Example
Color Values
In HTML, colors can also be specified using RGB values, HEX values, HSL values,
RGBA values, and HSLA values:
Example
HINTS
Use the style attribute for styling HTML elements
Use background-color for background color
Use color for text colors
Use font-family for text fonts
All HTML elements can have attributes
The title attribute provides additional "tool-tip" information
The href attribute provides address information for links
The width and height attributes provide size information for images
The alt attribute provides text for screen readers
we always use lowercase attribute names
we always quote attribute values with double quotes
JavaScript is a client-side scripting language developed by Brendan Eich.
JavaScript can be run on any operating systems and almost all web browsers.
You need a text editor to write JavaScript code and a browser to display
your web page.
UNIT-II - HTML Tables, Forms, and Lists: The table Element: Basic Table Formatting -
Merging Cells across Rows and Columns. The form Element - Creating Pull-Down Lists
- Combining Tables and Forms - E-Mailing the Contents of Forms - The List Elements.
HTML Tables
Definition
An HTML table is defined with the <table> tag. Each table row is defined with
the <tr> tag. A table header is defined with the <th> tag. By default, table headings are
bold and centered. A table data/cell is defined with the <td> tag.
Example:
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr> <tr <td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Note: The <td> elements are the data containers of the table.
They can contain all sorts of HTML elements; text, images, lists, other tables, etc.
Remember to define borders for both the table and the table cells.
If you want the borders to collapse into one border, add the CSS border-
collapse property:
Example
table, th, td
{
border: 1px solid black;
border-collapse: collapse;
}
HTML Table - Adding Cell Padding
Cell padding specifies the space between the cell content and its borders.
If you do not specify a padding, the table cells will be displayed without padding.
To set the padding, use the CSS padding property:
Example
th, td {
padding: 15px;
}
HTML Table - Left-align Headings
To set the border spacing for a table, use the CSS border-spacing property:
Example
table {
border-spacing: 5px;
}
Note: The <caption> tag must be inserted immediately after the <table> tag.
An Ordered List:
1. First item
2. Second item
3. Third item
4. Fourth item
An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
The list items will be marked with bullets (small black circles) by default:
Example
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Unordered HTML List - Choose List Item Marker
The CSS list-style-type property is used to define the style of the list item marker:
Example - Disc
<ul style="list-style-type:disc">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Example - Circle
<ul style="list-style-type:circle">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Example - Square
<ul style="list-style-type:square">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Example - None
<ul style="list-style-type:none">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Ordered HTML List
An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
The list items will be marked with numbers by default:
Example
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Ordered HTML List - The Type Attribute
The type attribute of the <ol> tag, defines the type of the list item marker:
Numbers:
<ol type="1">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Uppercase Letters:
<ol type="A">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Lowercase Letters:
<ol type="a">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Uppercase Roman Numbers:
<ol type="I">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Lowercase Roman Numbers:
<ol type="i">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
HTML Description Lists
Example
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
Nested HTML Lists
Example
<ul>
<li>Coffee</li>
<li>Tea
<ul>
<li>Black tea</li>
<li>Green tea</li>
</ul>
</li>
<li>Milk</li>
</ul>
Note: List items can contain new list, and other HTML elements, like images and links,
etc.
By default, an ordered list will start counting from 1. If you want to start counting
from a specified number, you can use the start attribute:
Example
<ol start="50">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Horizontal List with CSS
Example
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333333;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 16px;
text-decoration: none;
}
li a:hover {
background-color: #111111;
}
</style>
</head>
<body>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</body>
</html>
HTML FORMS
HTML Form Example
First name:
Mickey
Last name:
Mouse
Submit
The HTML <form> element defines a form that is used to collect user input:
<form>
.
form elements
.
</form>
Form elements are different types of input elements, like text fields, checkboxes,
radio buttons, submit buttons, and more.
The <input> element can be displayed in several ways, depending on the type
attribute. Here are some examples:
Text Input
<input type="text"> defines a one-line input field for text input:
Example
<form>
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname">
</form>
Last name:
Note: The form itself is not visible. Also note that the default width of a text field is 20
characters.
Male
Female
Other
The Submit Button
<input type="submit"> defines a button for submitting the form data to a form-
handler.
The form-handler is typically a server page with a script for processing input data.
The form-handler is specified in the form's action attribute:
Example
<form action="/action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
This is how the HTML code above will be displayed in a browser:
First name:
Last name:
Mouse
Mickey
Submit
The action attribute defines the action to be performed when the form is submitted.
Normally, the form data is sent to a web page on the server when the user clicks on the
submit button.
In the example above, the form data is sent to a page on the server called
"/action_page.php". This page contains a server-side script that handles the form data:
<form action="/action_page.php">
If the action attribute is omitted, the action is set to the current page.
The target attribute specifies if the submitted result will open in a new browser tab, a
frame, or in the current window.
The default value is "_self" which means the form will be submitted in the current
window.
To make the form result open in a new browser tab, use the value
"_blank": Example
<form action="/action_page.php" target="_blank">
Other legal values are "_parent", "_top", or a name representing the name of an iframe.
The method attribute specifies the HTTP method (GET or POST) to be used when
submitting the form data:
Example
<form action="/action_page.php" method="get">
or:
Example
<form action="/action_page.php" method="post">
When to Use GET?
The default method when submitting form data is GET.
However, when GET is used, the submitted form data will be visible in the
page address field:
/action_page.php?firstname=Mickey&lastname=Mouse
Notes on GET:
Notes on POST:
POST has no size limitations, and can be used to send large amounts of data.
Form submissions with POST cannot be bookmarked
If the name attribute is omitted, the data of that input field will not be sent at all.
This example will only submit the "Last name" input field:
Example
<form action="/action_page.php">
First name:<br>
<input type="text"
value="Mickey"><br> Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
Grouping Form Data with <fieldset>
Example
<form action="/action_page.php">
<fieldset>
<legend>Personal information:</legend>
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</fieldset>
</form>
Submit
If the type attribute is omitted, the input field gets the default type: "text".
Example
<option value="fiat"
selected>Fiat</option> Visible Values:
Use the size attribute to specify the number of visible values:
Example
<select name="cars" size="3">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
Allow Multiple Selections:
Use the multiple attribute to allow the user to select more than one value:
Example
<select name="cars" size="4" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
The <textarea> Element
The rows attribute specifies the visible number of lines in a text area.
The cols attribute specifies the visible width of a text area.
This is how the HTML code above will be displayed in a browser:
You can also define the size of the text area by using CSS:
Example
<textarea name="message" style="width:200px; height:600px">
The cat was playing in the garden.
</textarea>
The <button> Element
Example
<button type="button" onclick="alert('Hello World!')">Click Me!</button>
This is how the HTML code above will be displayed in a browser:
Click Me!
Note: Always specify the type attribute for the button element. Different browsers
may use different default types for the button element
HINTS
JavaScript Statements
Example
var x, y, z; // Statement
1 x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement
4
JavaScript Programs
This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
Most JavaScript programs contain many JavaScript statements.
The statements are executed, one by one, in the same order as they are written.
Semicolons ;
JavaScript ignores multiple spaces. You can add white space to your script to make it
more readable.
var person =
"Hege"; var
person="Hege";
For best readability, programmers often like to avoid code lines longer than 80
characters.
If a JavaScript statement does not fit on one line, the best place to break it is after
an operator:
Example
document.getElementById("demo").innerHTML =
"Hello Dolly!";
JavaScript Code Blocks
JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
The purpose of code blocks is to define statements to be executed together.
One place you will find statements grouped together in blocks, is in JavaScript
functions:
Example
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed. JavaScript keywords are reserved words. Reserved words cannot be used as
names for variables.
JavaScript Syntax
JavaScript syntax is the set of rules, how JavaScript programs are
constructed: var x, y; // How to declare variables
x = 5; y = 6; // How to assign values
z = x + y; // How to compute values
JavaScript Values
The JavaScript syntax defines two types of values: Fixed values and variable values.
Fixed values are called literals. Variable values are called variables.
JavaScript Literals
'John Doe'
JavaScript Variables
JavaScript Operators
var x, y;
x = 5;
y = 6;
JavaScript Expressions
x * 10
JavaScript Comments
JavaScript Identifiers
In JavaScript, identifiers are used to name variables (and keywords, and functions, and
labels).
The rules for legal names are much the same in most programming languages.
In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign
($).
Subsequent characters may be letters, digits, underscores, or dollar signs.
Numbers are not allowed as the first character.
This way JavaScript can easily distinguish identifiers from numbers.
var lastname,
lastName; lastName =
"Doe"; lastname =
"Peterson";
Unicode covers (almost) all the characters, punctuations, and symbols in the world.
.JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to make it more
readable.
Any text between // and the end of the line will be ignored by JavaScript (will not be
executed).
This example uses a single-line comment before each code
line: Example
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
This example uses a single line comment at the end of each line to explain the code:
Example
var x = 5; // Declare x, give it the value of 5
var y = x + 2; // Declare y, give it the value of x + 2
Multi-line Comments
Multi-line comments start with /* and end with */.
Adding // in front of a code line changes the code lines from an executable line to a
comment.
This example uses // to prevent execution of one of the code
lines: Example
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
This example uses a comment block to prevent execution of multiple lines:
Example
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/
JavaScript Variables
The general rules for constructing names for variables (unique identifiers) are:
In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.
This is different from algebra. The following does not make sense in algebra:
x=x+5
(It calculates the value of x + 5 and puts the result into x. The value of x is incremented
by 5.)
JavaScript variables can hold numbers like 100 and text values like "John Doe".
In programming, text values are called text strings.
JavaScript can handle many types of data, but for now, just think of numbers and
strings.
Strings are written inside double or single quotes. Numbers are written without
quotes. If you put a number in quotes, it will be treated as a text string.
Example
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
Declaring (Creating) JavaScript Variables
After the declaration, the variable has no value. (Technically it has the value
of undefined)
carName = "Volvo";
You can also assign a value to the variable when you declare
it: var carName = "Volvo";
In the example below, we create a variable called carName and assign the value
"Volvo" to it.
Then we "output" the value inside an HTML paragraph with id="demo":
Example
<p id="demo"></p>
<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
Start the statement with var and separate the variables by comma:
var person = "John Doe", carName = "Volvo", price = 200;
A declaration can span multiple lines:
In computer programs, variables are often declared without a value. The value can
be something that has to be calculated, or something that will be provided later, like
user input.
The variable carName will have the value undefined after the execution of this
statement:
Example
var carName;
The variable carName will still have the value "Volvo" after the execution of these
statements:
Example
var carName = "Volvo";
var carName;
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators like =
and +:
Example
var x = 5 + 2 + 3;
Example
var x = "John" + " " + "Doe";
Also try this:
Example
var x = "5" + 2 + 3;
If you put a number in quotes, the rest of the numbers will be treated as strings,
and concatenated.
Example
var x = 2 + 3 + "5";
JavaScript Operators
Example
Assign values to variables and add them
together: var x = 5; // assign the value 5 to x
var y = 2; // assign the value 2 to y
var z = x + y; // assign the value 7 to z (x + y)
Assignment
var x = 10;
The addition operator (+) adds numbers:
Adding
var x = 5;
var y = 2;
var z = x + y;
Multiplying
var x = 5;
var y = 2;
var z = x * y;
JavaScript Arithmetic Operators
Assignment
var x = 10;
x += 5;
JavaScript String Operators
Example
var txt1 = "John";
var txt2 = "Doe";
var txt3 = txt1 + " " + txt2;
The result of txt3 will be:
John Doe
Adding two numbers, will return the sum, but adding a number and a string will return
a string:
Example
var x = 5 + 5;
var y = "5" + 5;
var z = "Hello" + 5;
Operator Description
== equal to
!= not equal
!== not equal value or not equal type
? ternary operator
Operator Description
|| logical or
! logical not
Operator Description Example Same as Result Decimal
Operator Description
Any numeric operand in the operation is converted into a 32 bit number. The result is
converted back to a JavaScript number.
JavaScript Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Remainder)
++ Increment
--
Decrement
Arithmetic Operations
The operation (to be performed between the two operands) is defined by an operator.
100 + 50
Adding
Example
var x = 5;
var y = 2;
var z = x - y;
Multiplying
Example
var x = 5;
var y = 2;
var z = x * y;
Dividing
Example
var x = 5;
var y = 2;
var z = x / y;
Remainder
Example
var x = 5;
var y = 2;
var z = x % y;
In arithmetic, the division of two integers produces a quotient and a remainder.
In mathematics, the result of a modulo operation is the remainder of an arithmetic
division.
Incrementing
Example
var x =
5; x++;
var z = x;
Decrementing
The decrement operator (--) decrements numbers.
Example
var x = 5;
x--;
var z = x;
Operator Precedence
Example
var x = 100 + 50 * 3;
Is the result of example above the same as 150 * 3, or is it the same as 100 + 150?
Is the addition or the multiplication done first?
As in traditional school mathematics, the multiplication is done first.
Multiplication (*) and division (/) have higher precedence than addition (+) and
subtraction (-).
And (as in school mathematics) the precedence can be changed by using parentheses:
Example
var x = (100 + 50) * 3;
When using parentheses, the operations inside the parentheses are computed first.
When many operations have the same precedence (like addition and subtraction), they
are computed from left to right:
Example
var x = 100 + 50 - 3;
20 () Expression grouping (3 + 4)
19 . Member person.name
19 [] Member person["name"]
15 ** Exponentiation (ES7) 10 ** 2
14 * Multiplication 10 * 5
14 / Division 10 / 5
14 % Division Remainder 10 % 5
13 + Addition 10 + 5
13 - Subtraction 10 - 5
10 == Equal x == y
10 != Unequal x != y
7 | Bitwise OR x| y
5 || Logical OR x || y
3 += Assignment x += y
3 += Assignment x += y
3 -= Assignment x -= y
3 *= Assignment x *= y
3 %= Assignment x %= y
3 ^= Assignment x ^= y
3 |= Assignment x |= y
1 , Comma 5,6
Expressions in parentheses are fully computed before the value is used in the rest of the
expression.
JavaScript Assignment Operators
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
^= x ^= y x=x^y
|= x |= y x=x|y
**= x **= y x = x ** y
Assignment Examples
Assignment
var x = 10;
The += assignment operator adds a value to a variable.
Assignment
var x = 10;
x += 5;
Assignment
var x = 10;
x -= 5;
Assignment
var x = 10;
x *= 5;
Assignment
var x = 10;
x %= 5;
JavaScript Data Types
JavaScript variables can hold many data types: numbers, strings, objects and more:
var length = 16; // Number
var lastName = "Johnson"; // String
var x = {firstName:"John", lastName:"Doe"}; // Object
The Concept of Data Types
In programming, data types is an important concept.
Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it
produce a result?
When adding a number and a string, JavaScript will treat the number as a string.
Example
var x = 16 + "Volvo";
Example
var x = "Volvo" + 16;
JavaScript evaluates expressions from left to right. Different sequences can produce
different results:
JavaScript:
var x = 16 + 4 + "Volvo";
Result:
20Volvo
JavaScript:
var x = "Volvo" + 16 + 4;
Result:
Volvo164
In the first example, JavaScript treats 16 and 4 as numbers, until it reaches "Volvo".
In the second example, since the first operand is a string, all operands are treated as
strings.
JavaScript has dynamic types. This means that the same variable can be used to
hold different data types:
Example
var x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String
JavaScript Strings
Example
var answer = "It's alright"; // Single quote inside double quotes
var answer = "He is called 'Johnny'"; // Single quotes inside double quotes
var answer = 'He is called "Johnny"'; // Double quotes inside single quotes
JavaScript Numbers
Example
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:
Example
var y = 123e5; // 12300000
var z = 123e-5; // 0.00123
JavaScript Booleans
Example
var x = 5;
var y =
5; var z =
6;
(x == y) // Returns true
(x == z) // Returns false
You will learn more about conditional testing later in this tutorial.
JavaScript Objects
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
The object (person) in the example above has 4 properties: firstName, lastName, age,
and eyeColor.
In JavaScript, a variable without a value, has the value undefined. The type is
also undefined.
Example
var car; // Value is undefined, type is undefined
Any variable can be emptied, by setting the value to undefined. The type will
also be undefined.
Example
car = undefined; // Value is undefined, type is undefined
Empty Values
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = undefined; // Now both value and type is undefined
Difference Between Undefined and Null
A primitive data value is a single simple data value with no additional properties and
methods.
Example
typeof "John" // Returns "string"
typeof 3.14 // Returns
"number"
typeof true // Returns "boolean"
typeof false // Returns "boolean"
typeof x // Returns "undefined" (if x has no value)
Complex Data
function
object
The typeof operator returns object for both objects, arrays, and null.
The typeof operator does not return object for functions.
Example
typeof {name:'John', age:34} // Returns "object"
typeof [1,2,3,4] // Returns "object" (not "array", see note below)
typeof null // Returns "object"
typeof function myFunc(){} // Returns "function"
The typeof operator returns "object" for arrays because in JavaScript arrays are objects.
JavaScript Objects
Real Life Objects, Properties, and
Methods In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.
JavaScript Objects
You have already learned that JavaScript variables are containers for data values.
This code assigns a simple value (Fiat) to a variable named car:
var car = "Fiat";
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
var car = {type:"Fiat", model:"500", color:"white"};
The values are written as name:value pairs (name and value separated by a colon).
Object Definition
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Spaces and line breaks are not important. An object definition can span multiple lines:
Example
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
Object Properties
firstName John
lastName Doe
age 50
eyeColor blue
objectName.propertyName
or
objectName["propertyName"]
Example1
person.lastName;
Example2
person["lastName"];
Object Methods
firstName John
lastName Doe
age 50
eyeColor blue
Example
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
The this Keyword
In the example above, this is the person object that "owns" the fullName function.
In other words, this.firstName means the firstName property of this object.
Read more about the this keyword at JS this
Keyword. Accessing Object Methods
You access an object method with the following syntax:
objectName.methodName()
Example
name = person.fullName();
If you access a method without the () parentheses, it will return the function definition:
Example
name = person.fullName;
When a JavaScript variable is declared with the keyword "new", the variable is
created as an object:
Avoid String, Number, and Boolean objects. They complicate your code and slow down
execution speed.
JavaScript Loops
Loops are handy, if you want to run the same code over and over again, each time with
a different value.
Often this is the case when working with
arrays: Instead of writing:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
You can write:
var i;
for (i = 0; i<cars.length; i++) {
text += cars[i] + "<br>";
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example
for (i = 0; i< 5; i++) {
text += "The number is " + i + "<br>";
}
Statement 2 defines the condition for the loop to run (i must be less than 5).
Statement 3 increases a value (i++) each time the code block in the loop has been
executed.
Statement 1
Normally you will use statement 1 to initialize the variable used in the loop (i = 0).
This is not always the case, JavaScript doesn't care. Statement 1 is optional.
You can initiate many values in statement 1 (separated by comma):
Example
for (i = 0, len = cars.length, text = ""; i<len; i++) {
text += cars[i] + "<br>";
}
And you can omit statement 1 (like when your values are set before the loop starts):
Example
var i = 2;
var len =
cars.length; var text
= "";
for (; i<len; i++) {
text += cars[i] + "<br>";
}
Statement 2
This is not always the case, JavaScript doesn't care. Statement 2 is also optional.
If statement 2 returns true, the loop will start over again, if it returns false, the loop will
end.
Statement 3
This is not always the case, JavaScript doesn't care, and statement 3 is optional.
Statement 3 can do anything like negative increment (i--), positive increment (i = i + 15),
or anything else.
Statement 3 can also be omitted (like when you increment your values inside the loop):
Example
var i = 0;
var len = cars.length;
for (; i<len; ) {
text += cars[i] + "<br>";
i++;
}
Example
var person = {fname:"John", lname:"Doe", age:25};
Syntax
while (condition) {
code block to be executed
}
Example
In the following example, the code in the loop will run, over and over again, as long as a
variable (i) is less than 10:
Example
while (i< 10) {
text += "The number is " + i;
i++;
}
The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop as
long as the condition is true.
Syntax
do {
code block to be executed
}
while (condition);
Example
The example below uses a do/while loop. The loop will always be executed at least
once, even if the condition is false, because the code block is executed before the
condition is tested:
Example
do {
text += "The number is " + i;
i++;
}
while (i< 10);
Do not forget to increase the variable used in the condition, otherwise the loop will
never end!
If you have read the previous chapter, about the for loop, you will discover that a while
loop is much the same as a for loop, with statement 1 and statement 3 omitted.
The loop in this example uses a for loop to collect the car names from the cars array:
Example
var cars = ["BMW", "Volvo", "Saab",
"Ford"]; var i = 0;
var text = "";
for (;cars[i];) {
text += cars[i] + "<br>";
i++;
}
The loop in this example uses a while loop to collect the car names from the cars array:
Example
var cars = ["BMW", "Volvo", "Saab",
"Ford"]; var i = 0;
var text = "";
while (cars[i]) {
text += cars[i] + "<br>";
i++;
}
Example
The getDay() method returns the weekday as a number between 0 and
6. (Sunday=0, Monday=1, Tuesday=2 ..)
This example uses the weekday number to calculate the weekday name:
Tuesday
When JavaScript reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need for
more testing.
A break can save a lot of execution time because it "ignores" the execution of all the
rest of the code in the switch block.
It is not necessary to break the last case in a switch block. The block breaks (ends) there
anyway.
The default keyword specifies the code to run if there is no case match:
Example
The getDay() method returns the weekday as a number between 0 and 6.
If today is neither Saturday (6) nor Sunday (0), write a default message:
switch (new Date().getDay()) {
case 6:
text = "Today is
Saturday"; break;
case 0:
text = "Today is
Sunday"; break;
default:
text = "Looking forward to the Weekend";
}
The default case does not have to be the last case in a switch block:
Example
switch (new Date().getDay()) {
default:
text = "Looking forward to the Weekend";
break;
case 6:
text = "Today is
Saturday"; break;
case 0:
text = "Today is Sunday";
}
Common Code Blocks
Sometimes you will want different switch cases to use the same code.
In this example case 4 and 5 share the same code block, and 0 and 6 share another code
block:
Example
switch (new Date().getDay()) {
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
break;
default:
text = "Looking forward to the Weekend";
}
Switching Details
If no matching cases are found, the program continues to the default label.
If no default label is found, the program continues to the statement(s) after the switch.
Strict Comparison
Switch cases use strict comparison (===).
A strict comparison can only be true if the operands are of the same
type. In this example there will be no match for x:
Example
var x = "0";
switch (x) {
case 0:
text = "Off";
break;
case 1:
text = "On";
break;
default:
text = "No value found";
}
The if Statement
Syntax
if (condition) {
block of code to be executed if the condition is true
}
Example
Make a "Good day" greeting if the hour is less than 18:00:
if (hour < 18) {
greeting = "Good day";
}
Good day
Good day
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}
Example
If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than
20:00, create a "Good day" greeting, otherwise a "Good evening":
Array
An array is an indexed collection. An array can be used to store a list of items (elements) under
a single name with an integral index. You can reference individual element via the integral
index in the form of anArrayName[anIndexNumber]. Furthermore, you can conveniently
process all
the elements of an array collectively via a loop.
Accessing an Item
You can access individual element of an array via an integral index, in the form
of anArrayName[anIndexNumber]. The index of the array begins at 0, and shall be a non-
negative integer.
Array's length
The length of the array is maintained in a variable called length, which can be accessed
via anArrayName.length. In fact, the property .length returns the last integral index plus 1, as
JavaScript's array index is 0-based. Nonetheless, you are allow to manipulate the .length. For
example,
a = ['11', '22', '33'];
console.log(a); // ["11", "22", "33"]
console.log(a.length); // 3
a.length = 10;
console.log(a); // ["11", "22", "33"]
console.log(a.length); // 10
Clearly, setting the .length does not affect the array elements.
Dynamic Array
Unlike Java/C/C++, the JavaScript array is dynamically allocated. You can add more elements to
an array. You can also remove the content of an element using keyword delete. For examples,
var days = ["sun", "mon", "tue"];
console.log(days.length); // 3
console.log(days); // ["sun", "mon",
"tue"]
// Negative index?
days[-9] = 'hello';
console.log(days.length); // 6
console.log(days); // ["sun", 2: "tue", 5: "fri", -9: "hello"]
// The index -9 is considered as an object property,
// outside the numerical indexes (to be discussed later)
Add/Remove item(s)
You can:
Use array.length to add one item to the end of an array.
Use delete to remove a particular index (set it to undefined).
Use push() to add one or more items to the end of an array. push() returns the resultant
length of the array.
Use unshift() to add one or more items to the beginning of an array. unshift() returns the
resultant length of the array.
Use pop() to remove and return the last item of an array.
Use shift() to remove and return the first item of an array.
Associative Array
An associative array is an array of key-value pair. Instead of using numbers 0, 1, 2,... as keys as
in the regular array, you can use anything (such as string) as key in an associative array.
Associative arrays are used extensively in JavaScript and jQuery.
JavaScript does not support native associative array (it actually does not support native array
too). In JavaScript, associative arrays (and arrays) are implemented as objects (to be elaborate
later).
You can create an associative array via the Object Initializer. For example,
// Create an associative array of key-value
pairs varaStudent = {
name: 'peter', // string
id: 8888, // number
isMarried: false // boolean
};
Note: The elements in the collection are sorted as they appear in the source code.
Note: The elements collection returns all elements inside the <form> element, not all <form>
elements in the document. To get all <form> elements in the document, use
the document.forms collection instead.
Syntax
formObject.elements
Properties
P r o p e r t yDescription
Methods
MethodD e s c r i p t i o n
[index]Returns the element in <form> with the specified index (starts at 0).
i t e m ( i n d e x )Returns the element in <form> with the specified index (starts at 0).
Example
Find out how many elements there are in a specified <form> element:
var x = document.getElementById("myForm").elements.length;
The result of x will be:
Example
[index]
var x = document.getElementById("myForm").elements[0].value;
The result of x will be:
Donald
Example
item(index)
var x = document.getElementById("myForm").elements.item(0).value;
The result of x will be:
Donald
Example
namedItem(id)
var x = document.getElementById("myForm").elements.namedItem("fname").value;
The result of x will be:
Donald
Example
Loop through all elements in a form and output the value of each element:
var x = document.getElementById("myForm");
var txt = "";
var i;
for (i = 0; i<x.length; i++) {
txt = txt + x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = txt;
The result of txt will be:
Donald
Duck
Submit
HIDING THE CONTENT OF JAVASCRIPT
Style display property is used to hide and show the content of HTML DOM by accessing the
DOM element using JavaScript/jQuery.
To hide an element, set the style display property to “none”.
document.getElementById("element").style.display = "none";
To show an element, set the style display property to “block”.
document.getElementById("element").style.display = "block";
Steps to show the working of style display property:
1. Create some div and assign them an id or class and then add styling to it.
<div class=”circle” id=”circle”></div>
<div class=”rounded” id=”rounded”></div>
<div class=”square” id=”square”></div>
2. Width and height will set the width and height of the content, border-radius 0% will make a
square border, 50% will make a circle and 25% will make a rounded shape and float will
make the divs get positioned, margin-right will make them separated with a space at right.
<style type=”text/css”>
circle
{
width:130px; height:130px;
border-radius:50%; float: left; margin-right;50px;
}
rounded
{
width:130px; height:130px;
border-radius:25%; float: left; margin-right;50px;
}
square
{
width:130px; height:130px;
border-radius:25%; float: left; margin-right;50px;
}
l >
.
JAVASCRIPT FUNCTIONS
Example
function myFunction(p1, p2) {
return p1 * p2; // The function returns the product of p1 and p2
}
A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
A Function is much the same as a Procedure or a Subroutine, in other programming languages.
Functions
f1(1, 2);
// a1: type is number, value is 1
// a2: type is number, value is 2
// a3: type is undefined, value is undefined
f1('hello', 1, 2);
// a1: type is string, value is hello
// a2: type is number, value is 1
// a3: type is number, value is 2
You can use this feature to provide default value to function argument, for example,
// Define a function with default arguments
function f2(a1, a2, a3) {
// Set default for a2, if a2 is missing or null in function call
if (a2 === undefined || a2 === null) a2 = 88;
// Set default to a3
// a3 evaluates to false for undefined, null, '', 0, NaN,
false a3 = a3 || 'myDefault'; // more concise
Function Variables
In JavaScript, a variable can hold a primitive (number, string, boolean). It can also hold a function
object. For example,
// Define a named function f1()
function f1(a1) {
return'run f1()';
}
console.log(f1); // function f1(a1)
console.log(f1('hello')); // run f1()
Function as Argument
Recall that a function takes zero or more arguments from the caller. In JavaScript, the argument can be
of any types: primitive, object or even function. That is, a function may take another function as its
argument.
For example, the following function take a function and an array as its arguments, and apply the
function to the array.
// Define a function, which takes a function and an array as its arguments,
// and apply the function to each item of the array.
functionprocessArray (inFun, inArray) {
varresultArray = [];
for (vari in inArray) {
// apply function to each item of the inArray
resultArray[i] = inFun(inArray[i]);
}
returnresultArray;
}
Nested Function
In JavaScript, you can define a function inside a function. For example,
function f1(msg1) {
console.log('in f1() with message:' + msg1);
// Define a function inside a function
function f2(msg2) {
console.log('in f2() with message:' + msg2);
return'f2:' + msg2;
}
// Invoke the nested function
return'f1:' + f2(msg1);
}
console.log(main('mul')(3, 4));
// in mul
// 12
When you declare a variable outside of any function, it is called a global variable, and available to all
codes in the current document. When you declare a variable within a function, it is called a local
variable, and available only within that function. For example,
// global variable
vargvar = 8;
functionsayHello() {
// local variable
varlvar = 'hello';
console.log(gvar); // can access global variable
console.log(lvar);
returnlvar;
}
sayHello();
Recursion is a programming pattern that is useful in situations when a task can be naturally split into
several tasks of the same kind, but simpler. Or when a task can be simplified into an easy action plus a
simpler variant of the same task.
There are two ways to implement it.
Iterative thinking: the for loop:
function pow(x, n) {
let result = 1;
// multiply result by x n times in the loop
for (let i = 0; i< n; i++) {
result *= x;
}
return result;
}
alert( pow(2, 3) ); // 8
Recursive thinking: simplify the task and call self:
function pow(x, n) {
if (n == 1) {
return x;
} else {
return x * pow(x, n - 1);
}
}
alert(pow(2, 3) ); // 8
Please note how the recursive variant is fundamentally different.
When pow(x, n) is called, the execution splits into two branches:
if n==1 = x
/
pow(x, n) =
\
else = x * pow(x, n - 1)
If n == 1, then everything is trivial. It is called the base of recursion, because it immediately
produces the obvious result: pow(x, 1) equals x.
Otherwise, we can represent pow(x, n) as x * pow(x, n - 1). In maths, one would write xn = x *
xn-1. This is called a recursive step: we transform the task into a simpler action (multiplication
by x) and a simpler call of the same task (powwith lower n). Next steps simplify it further and
further until n reaches 1.
We can also say that pow recursively calls itself till n == 1.
For example, to calculate pow(2, 4) the recursive variant does these steps:
pow(2, 4) = 2 * pow(2, 3)
pow(2, 3) = 2 * pow(2, 2)
pow(2, 2) = 2 * pow(2, 1)
pow(2, 1) = 2
So, the recursion reduces a function call to a simpler one, and then – to even more simpler, and so on,
until the result becomes obvious.
INTRODUCTION TO EVENTS
JavaScript are often event-driven. That is, a piece of program (called event handler) fires in response
to a certain user's or browser's action that generates an event.
The commonly-used events are:
click: generated when the user clicks on an HTML element.
mouseover, mouseout: generated when the user positions the mouse pointer inside/away from the
HTML element.
load, unload: generated after the browser loaded a document, and before the next document is
loaded, respectively.
The event handler, called oneventname (such as onclick, onmousemove, onload), is the codes that responses
to an event. The event handler is typically attached to the target HTML tag, e.g.,
<!DOCTYPE html>
<!--"JSEventDemo.html" -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Event Demo</title>
<script>
function say(message) {
alert(message);
}
</script>
</head>
<body>
<h2 onmouseover="this.style.color='red'"
onmouseout="this.style.color=''">Hello</h2>
<input type="button" value="click me to say Hello"onclick="say('Hello')">
<p onclick="say('Hi')">This paragraph can say Hi...</p>
</body>
</html>
You can attach event handler (e.g., onclick, onmouseover) to a specific HTML tag as the tag's attribute, as
follows:
<tagNameeventHandler="JavaScript statement(s)"otherAttributes>contents</tagName>
The event handler can be a single JavaScript statement, a series of JavaScript statements (separated by
semicolon), or most often, a function call. For example,
<!-- Event handler calls built-in functions -->
<body onload="alert('welcome')"onunload="alert('bye')">
Mouse-Related Events
Including click, mouseup, mousedown, mouseover, mouseout, mousemove. For mouse-related events,
the Event object provides these additional properties:
1. button: integer 1 for left button, 2 for middle, and 3 for right
2. clientX, clientY: mouse location relative to the client area.
3. screenX, screenY: mouse location relative to the screen.
4. altKey, ctrlKey, metaKey, shiftKey: boolean value indicating where these key was pressed when
the mouse event is fired.
Key-Related Events
Including keyup, keydown and keypress. For key-related events, the Event object provides these additional
properties:
keyCode: ASCII code of the key pressed.
altKey, ctrlKey, metaKey, shiftKey: boolean flag indicating whether these key was also pressed.
clientX, clientY: mouse location relative to the client area.
screenX, screenY: mouse location relative to the screen.
The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down).
By default, the sort() method sorts the values as strings in alphabetical and ascending order.
This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as
strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce an incorrect result when sorting numbers.
You can fix this by providing a "compare function" (See "Parameter Values" below).
Syntax
array.sort(compareFunction)
Description
Optional.A function that defines an alternative sort order. The function should return a negative, zero,
or positive value, depending on the arguments, like:
function(a, b){return a-b}
When the sort() method compares two values, it sends the values to the compare function, and sorts
the values according to the returned (negative, zero, positive) value.
Example:
When comparing 40 and 100, the sort() method calls the compare function(40,100).
Example
Sort numbers in an array in ascending order:
Example
Sort numbers in an array in descending order: