HTML5 Programming Essentials Guide
HTML5 Programming Essentials Guide
Syllabus
HTML5: Fundamental Elements of HTML, Formatting Text in HTML, Organizing
Text in HTML, Links and URLs in HTML, Tables in HTML, Images on a Web Page,
Image Formats, Image Maps, Colors, FORMs in HTML, Interactive Elements,
Working with Multimedia - Audio and Video File Formats, HTML elements for
inserting Audio / Video on a web page
HTML HTML5
It didn’t support audio and video without with the use of <audio> and
with the help of various technologies integral a part of HTML5 like SVG
It does not allow drag and drop effects. It allows drag and drop effects.
Not possible to draw shapes like circle, HTML5 allows to draw shapes like
Older version of HTML are less mobile- HTML5 language is more mobile-
friendly. friendly.
Elements like nav, header were not New element for web structure like
complicated. easy.
browser. API.
Attributes like charset, async and ping Attributes of charset, async and ping
Basic Elements
A text header, denoted using the <h1>, <h2>, <h3>, <h4>, <h5>, <h6> tags.
A paragraph, denoted using the <p> tag.
A horizontal ruler, denoted using the <hr> tag.
A link, denoted using the <a> (anchor) tag.
A list, denoted using the <ul> (unordered list), <ol> (ordered list)
and <li> (list element) tags.
An image, denoted using the <img> tag
Internet Programming
The next few pages will give an overview of these basic HTML elements.
Each element can also have attributes - each element has a different set of attributes
relevant to the element. There are a few global elements, the most common of them
are:
There are six different types of text header you can choose from, h1 being the
topmost heading with the largest text, and h6 being the most inner heading with the
smallest text. In general, you should have only one h1 tag with a page, since it
should be the primary description of the HTML page.
As we've seen in the last example, a paragraph is a block of text separated from the
rest of the text around it.
Let's see an example of the <h1>, <h2> and <p> tags in action:
<!DOCTYPE html>
<html>
<head>
<title>First page</title>
</head>
<body>
<h1>My First Page</h1>
<p>This is my first page.</p>
Internet Programming
A horizontal ruler <hr> tag acts as a simple separator between page sections.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>My First Page</h1>
<p>This is my first page.</p>
<hr/>
<p>This is the footer - all rights are reserved to me.</p>
</body>
</html>
HTML | Text Formatting
HTML provides us with the ability for formatting text just like we do it in MS Word
or any text editing software. In this article, we would go through few such options.
1. Making text Bold or Strong: We can make the text bold using the <b> tag.
The tag uses both opening and closing tag. The text that needs to be made bold
must be within <b> and </b> tag.
We can also use the <strong> tag to make the text strong, with added semantic
importance. It also opens with <strong> and ends with </strong> tag. Example:
filter_none
edit
play_arrow
brightness_4
Internet Programming
<!DOCTYPE html>
<html>
<head>
<title>Bold</title>
</head>
<body>
<!--Normal text-->
<p>Hello GeeksforGeeks</p>
<!--Text in Bold-->
<p><b>Hello GeeksforGeeks</b></p>
<!--Text in Strong-->
<p><strong>Hello GeeksforGeeks</strong></p>
</body>
</html>
Output:
2. Making text Italic or emphasize: The <i> tag is used to italicise the text. It
opens with <i> and ends with </i> tag. The
<em> tag is used to emphasize the text, with added semantic importance. It
opens with <em> and ends with </em> tag. Example:
filter_none
edit
play_arrow
brightness_4
<!DOCTYPE html>
Internet Programming
<html>
<head>
<title>Italic</title>
</head>
<body>
<!--Normal text-->
<p>Hello GeeksforGeeks</p>
<!--Text in Italics-->
<p><i>Hello GeeksforGeeks</i></p>
<!--Text in Emphasize-->
<p><em>Hello GeeksforGeeks</em></p>
</body>
</html>
Output:
filter_none
edit
play_arrow
brightness_4
<!DOCTYPE html>
<html>
Internet Programming
<head>
<title>Highlight</title>
</head>
<body>
<!--Text in Normal-->
<p>Hello GeeksforGeeks</p>
<!--Text in Highlight-->
<p><mark>Hello GeeksforGeeks</mark></p>
</body>
</html>
Output:
<p>Hello GeeksforGeeks</p>
<!--Text in Superscript-->
<p>Hello <sup>GeeksforGeeks</sup></p>
<!--Text in Subcript-->
<p>Hello <sub>GeeksforGeeks</sub></p>
</body>
</html>
Output:
5. Making text smaller: The <small> element is used to make the text smaller.
The text that needs to be displayed smaller should be written inside <small>
and </small> tag.
Example:
filter_none
edit
play_arrow
brightness_4
<!DOCTYPE html>
<html>
<head>
<title>Small</title>
</head>
<body>
<!--Text in Normal-->
<p>Hello GeeksforGeeks</p>
Internet Programming
<!--Text in small-->
<p><small>Hello GeeksforGeeks</small></p>
</body>
</html>
Output:
6. Striking through the text: The <del> element is used to strike through the text
marking the part as deleted. It also has an opening and a closing tag. Example:
filter_none
edit
play_arrow
brightness_4
<!DOCTYPE html>
<html>
<head>
<title>Delete</title>
</head>
<body>
<!--Text in Normal-->
<p>Hello GeeksforGeeks</p>
<!--Text in Delete-->
<p><del>Hello GeeksforGeeks</del></p>
</body>
</html>
Internet Programming
Output:
7. Adding a text: The <ins> element is used to underline a text marking the part
as inserted or added. It also has an opening and a closing tag. Example:
filter_none
edit
play_arrow
brightness_4
<!DOCTYPE html>
<html>
<head>
<title>Inserting</title>
</head>
<body>
<!--Text in Normal-->
<p>Hello GeeksforGeeks</p>
<!--Text in Insert-->
<p><ins>Hello GeeksforGeeks</ins></p>
</body>
</html>
Output:
HTML Links
Internet Programming
Links are found in nearly all web pages. Links allow users to click their way from
page to page.
When you move the mouse over a link, the mouse arrow will turn into a little hand.
The HTML <a> tag defines a hyperlink. It has the following syntax:
Each table row is defined with a <tr> tag. Each table header is defined with
a <th> tag. Each table data/cell is defined with a <td> tag.
Example
Text Color
Hello World
Lorem ipsum
Internet Programming
Ut wisi enim
HTML Forms
An HTML form is used to collect user input. The user input is most often sent to
a server for processing.
The <form> Element
The HTML <form> element is used to create an HTML form for user input:
<form>
.
form elements
.
</form>
The <form> element is a container for different types of input elements, such as:
text fields, checkboxes, radio buttons, submit buttons, etc.
Type Description
<input type="radio"> Displays a radio button (for selecting one of many choices)
<input type="checkbox"> Displays a checkbox (for selecting zero or more of many choices)
Text Fields
The <input type="text"> defines a single-line input field for text input.
Example
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
Internet Programming
First name:
Last name:
The <label> element is useful for screen-reader users, because the screen-reader
will read out loud the label when the user focus on the input element.
The <label> element also help users who have difficulty clicking on very small
regions (such as radio buttons or checkboxes) - because when the user clicks the
text within the <label> element, it toggles the radio button/checkbox.
The for attribute of the <label> tag should be equal to the id attribute of
the <input> element to bind them together.
Radio Buttons
Example
<form>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
</form>
Male
Female
Other
Checkboxes
Example
<form>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label>
</form>
Internet Programming
The <input type="submit"> defines a button for submitting the form data to a
form-handler.
The form-handler is typically a file on the server with a script for processing input
data.
Example
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
First name:
Last name:
Internet Programming
Submit
HTML Multimedia
What is Multimedia?
Multimedia comes in many different formats. It can be almost anything you can
hear or see, like images, music, sound, videos, records, films, animations, and
more.
Web pages often contain multimedia elements of different types and formats.
The controls attribute adds video controls, like play, pause, and volume.
It is a good idea to always include width and height attributes. If height and width
are not set, the page might flicker while the video loads.
The <source> element allows you to specify alternative video files which the
browser may choose from. The browser will use the first recognized format.
The text between the <video> and </video> tags will only be displayed in browsers
that do not support the <video> element.
The HTML <audio> element is used to play an audio file on a web page.
<audio controls>
<source src="[Link]" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
Internet Programming
The controls attribute adds audio controls, like play, pause, and volume.
The <source> element allows you to specify alternative audio files which the
browser may choose from. The browser will use the first recognized format.
The text between the <audio> and </audio> tags will only be displayed in browsers
that do not support the <audio> element.
Internet Programming
CSS
Syllabus : CSS: Understanding the Syntax of CSS, CSS Selectors, Inserting CSS in
an HTML Document, CSS properties to work with background of a Page, CSS
properties to work with Fonts and Text Styles, CSS properties for positioning an
element
What is CSS?
CSS stands for Cascading Style Sheets
CSS describes how HTML elements are to be displayed on screen,
paper, or in other media
CSS saves a lot of work. It can control the layout of multiple web pages all
at once
External stylesheets are stored in CSS files.
HTML was NEVER intended to contain tags for formatting a web page!
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
When tags like <font>, and color attributes were added to the HTML 3.2
specification, it started a nightmare for web developers. Development of
large websites, where fonts and color information were added to every single
page, became a long and expensive process.
Internet Programming
To solve this problem, the World Wide Web Consortium (W3C) created
CSS.
CSS Syntax
A CSS rule-set consists of a selector and a declaration block:
<p>This is a paragraph.</p>
Each declaration includes a CSS property name and a value, separated by a colon.
Multiple CSS declarations are separated with semicolons, and declaration blocks
are surrounded by curly braces.
Internet Programming
CSS Selectors
CSS selectors are used to "find" (or select) the HTML elements you want to
style.
The element selector selects HTML elements based on the element name.
<!DOCTYPE html>
<html>
<head>
<style>
#para1 {
text-align: center;
color: red;
}
</style>
</head>
<body>
Internet Programming
</body>
</html>
The CSS class Selector
The class selector selects HTML elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by
the class name.
<!DOCTYPE html>
<html>
<head>
<style>
.center {
text-align: center;
color: red;
}
</style>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
*{
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1>Hello world!</h1>
<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, p {
text-align: center;
color: red;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
<h2>Smaller heading!</h2>
<p>This is a paragraph.</p>
</body>
</html>
Internet Programming
Inline CSS
An inline CSS is used to apply a unique style to a single HTML element.
The following example sets the text color of the <h1> element to blue, and
the text color of the <p> element to red:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Internal CSS
An internal CSS is used to define a style for a single HTML page.
The following example sets the text color of ALL the <h1> elements (on that page)
to blue, and the text color of ALL the <p> elements to red. In addition, the page
will be displayed with a "powderblue" background color:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
External CSS
An external style sheet is used to define the style for many HTML pages.
To use an external style sheet, add a link to it in the <head> section of each HTML
page:
Internet Programming
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
"[Link]":
body {
background-color: powderblue;
}
h1 {
color: blue;
}
p{
color: red;
}
Internet Programming
CSS background
It is also possible to specify all the background properties in one single property.
This is called a shorthand property.
Instead of writing:
body {
background-color: #ffffff;
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}
Example
Use the shorthand property to set the background properties in one declaration:
body {
background: #ffffff url("img_tree.png") no-repeat right top;
}
There are only a few font families. The two most commonly used are "Times New
Roman" and "Arial." To define a font family, use the following CSS code.
Internet Programming
p{
font-family: "Arial", Helvetica, sans-serif;
}
CSS has a "font-style" property that lets you define a style. For instance, suppose
you want to add an italics style to the previously used paragraph class. You can use
the following code for font styles.
p{
font-family: "Arial", Helvetica, sans-serif;
font-style: italic;
}
You can also bold a font, which is usually common among page designs. The
"font-weight" style is used to add bold text. You can stack these styles. In other
words, you can use italics and bold in the same CSS class definition. The browser
will use both styles when it renders the web page text. The following code uses
both italics and bold font.
p{
font-family: "Arial", Helvetica, sans-serif;
font-style: italic;
font-weight: bold;
}
You can use pixels to define your font sizes, but current website design calls for
the "em" property. Em styles use ratios of pixel font sizes. The default pixel size
for any browser is 16 pixels. Since em styles are a ratio of the browser's text size,
Internet Programming
For instance, the <h> tags are common header tags used to create headers and
subheaders within your content. The <h1> tag is the first header on the page, and it
usually is a larger font than the rest of the text on the page. Review the following
CSS class.
h1 {
font-size: 40px;
}
Instead of using the 40 pixel font size, you can use the em standard. The following
code defines 40 pixel font sizes using the em standard.
h1 {
font-size: 2.5em;
}
Static positioned elements are not affected by the top, bottom, left, and right
properties.
An element with position: static; is not positioned in any special way; it is always
positioned according to the normal flow of the page:
<!DOCTYPE html>
<html>
<head>
Internet Programming
<style>
p{
position: static;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<h2>position: static;</h2>
<p>An element with position: static; is not positioned in any special way; it is
always positioned according to the normal flow of the page:</p>
</body>
</html>
position: relative;
An element with position: relative; is positioned relative to its normal position.
Setting the top, right, bottom, and left properties of a relatively-positioned element
will cause it to be adjusted away from its normal position. Other content will not
be adjusted to fit into any gap left by the element.
<!DOCTYPE html>
<html>
<head>
<style>
p{
position: relative;
Internet Programming
left: 30px;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<h2>position: relative;</h2>
<p>An element with position: relative; is positioned relative to its normal
position:</p>
</body>
</html>
position: fixed;
An element with position: fixed; is positioned relative to the viewport, which
means it always stays in the same place even if the page is scrolled. The top, right,
bottom, and left properties are used to position the element.
A fixed element does not leave a gap in the page where it would normally have
been located.
<!DOCTYPE html>
<html>
<head>
<style>
p{
position: fixed;
Internet Programming
width: 300px;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<h2>position: fixed;</h2>
<p>An element with position: fixed; is positioned relative to the viewport, which
means it always stays in the same place even if the page is scrolled:</p>
</body>
</html>
position: absolute;
An element with position: absolute; is positioned relative to the nearest positioned
ancestor (instead of positioned relative to the viewport, like fixed).
<!DOCTYPE html>
<html>
<head>
<style>
p{
position: absolute;
top: 80px;
right: 0;
Internet Programming
width: 200px;
height: 100px;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<h2>position: absolute;</h2>
<p>An element with position: absolute; is positioned relative to the nearest
positioned ancestor (instead of positioned relative to the viewport, like fixed):</p>
</body>
</html>
position: sticky;
An element with position: sticky; is positioned based on the user's scroll position.
A sticky element toggles between relative and fixed, depending on the scroll
position. It is positioned relative until a given offset position is met in the viewport
- then it "sticks" in place (like position:fixed).
JavaScript
SYLLABUS: JavaScript: Using JavaScript in an HTML Document, Programming
Fundamentals of JavaScript – Variables, Operators, Control Flow Statements,
Popup Boxes, Functions – Defining and Invoking a Function, Defining Function
arguments, Defining a Return Statement, Calling Functions with Timer, JavaScript
Objects - String, RegExp, Math, Date, Browser Objects - Window, Navigator,
History, Location, Document, Cookies, Document Object Model, Form Validation
using JavaScript
JavaScript is a text-based programming language used both on the client-side and server-
side that allows you to make web pages interactive. Where HTML and CSS are languages
that give structure and style to web pages, JavaScript gives web pages interactive elements
that engage a user. Common examples of JavaScript that you might use every day include
the search box on Amazon
JavaScript is mainly used for web-based applications and web browsers. But JavaScript is
also used beyond the Web in software, servers and embedded hardware controls.
JavaScript can calculate, manipulate and validate data.
<h2>JavaScript Variables</h2>
<p id="demo"></p>
<script>
var x = 5;
var y = 6;
var z = x + y;
[Link]("demo").innerHTML =
"The value of z is: " + z;
</script>
Ja<v/baSodcryi>pt Operators
Ja<v/hatSmcrl>
ipt operators are symbols that are used to perform operations on operands.
For example:
1. var sum=10+20
Here, + is the arithmetic operator and = is the assignment operator.
There are following types of operators in JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.
Operator Description Example
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus (Remainder) 10%3=1
++ Increment var a=10; a++; Now a = 11
-- Decrement var a=10; a--; Now a = 9
JavaScript Comparison Operators
The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:
JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is true
or false. There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement
JavaScript If statement
It evaluates the content only if the expression is true. The signature of JavaScript if
statement is given below.
if(expression)
{
//content to be evaluated
}
Flowchart of JavaScript If statement
Let’s see the example of if-else statement in JavaScript to find out the even or odd
number.
<html>
<body>
<script>
var a=20;
if(a%2==0){
[Link]("a is even number");
}
else{
[Link]("a is odd number");
}
</script>
</body>
</html>
If...else if statement
It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.
if(expression1)
{
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else
{
//content to be evaluated if no expression is true
}
Let’s see the simple example of if else if statement in javascript.
<html>
<body>
<script>
var a=20;
if(a==10){
[Link]("a is equal to 10");
}
else if(a==15){
[Link]("a is equal to 15");
}
else if(a==20){
[Link]("a is equal to 20");
}
else{
[Link]("a is not equal to 10, 15 or 20");
}
</script>
</body>
</html>
default:
code to be executed if above values are not matched;
}
Let’s see the simple example of switch statement in javascript.
<!DOCTYPE html>
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
[Link](result);
</script>
</body>
</html>
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while
or for-in loops. It makes the code compact. It is mostly used in array.
There are four types of loops in JavaScript.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
[Link](i + "<br/>")
}
</script>
</body>
</html>
while (condition)
{
//code to be executed
}
Let’s see the simple example of while loop in javascript.
<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=15)
{
[Link](i + "<br/>");
i++;
}
</script>
</body>
</html>
Popup Boxes
JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box
An alert box is often used if you want to make sure information comes through to
the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
[Link]("sometext");
The [Link]() method can be written without the window prefix
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Alert</h2>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
</body>
</html>
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.
Syntax
[Link]("sometext");
The [Link]() method can be written without the window prefix.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else { txt = "You pressed Cancel!";
}[Link]("demo").innerHTML = txt;
}</script>
</body>
</html>
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.
Syntax
[Link]("sometext","defaultText");
The [Link]() method can be written without the window prefix.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
var person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "") {
txt = "User cancelled the prompt.";
} else {
txt = "Hello " + person + "! How are you today?";
}
[Link]("demo").innerHTML = txt;
}
</script>
</body>
</html>
Functions
Defining and Invoking a Function, Defining Function arguments, Defining a Return
Statement, Calling Functions with Timer
Defining and Invoking a Function:
JavaScript functions are defined with the function keyword.
functions are declared with the following syntax:
function functionName(parameters)
{
// code to be executed
}
Example
function myFunction(a, b)
{
return a * b;
}
Invoking a JavaScript Function
The code inside a function is not executed when the function is defined.
The code inside a function is executed when the function is invoked(call).
It is common to use the term "call a function" instead of "invoke a function".
It is also common to say "call upon a function", "start a function", or "execute a
function".
<html>
<head>
<script type = "text/javascript">
function sayHello() {
[Link] ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>
</body>
</html>
Defining Function arguments
Function Parameters are the names that are define in the function definition and real
values passed to the function in function definition are known as arguments.
Syntax:
function Name(parameter1, parameter2, paramet3,parameter4)
{
// Statements
}
Parameter Rules:
There is no need to specify the data type for parameters in JavaScript function
definitions.
It does not perform type checking based on passed in JavaScript function.
It does not check the number of received arguments.
Parameters:
Name: It is used to specify the name of the function.
Arguments: It is provided in the argument field of the function.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
[Link] (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the
code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the
"caller":
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation, and returns the
result:</p>
<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
[Link]("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>
<script>
function myFunction() {
setTimeout(function(){ alert("Hello"); }, 3000);
}
</script>
</body>
</html>
The clearTimeout() method stops the execution of the function specified in
setTimeout().
[Link](timeoutVariable)
<!DOCTYPE html>
<html>
<body>
<p>Click "Try it". Wait 3 seconds. The page will alert "Hello".</p>
<p>Click "Stop" to prevent the first function to execute.</p>
<p>(You must click "Stop" before the 3 seconds are up.)</p>
<script>
function myFunction() {
alert("Hello");
}
</script>
</body>
</html>
The setInterval() Method
The setInterval() method repeats a given function at every given time-interval.
[Link](function, milliseconds);
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myVar = setInterval(myTimer, 3000);
function myTimer() {
var d = new Date();
[Link]("demo").innerHTML = [Link]();
}
</script>
</body>
</html>
The clearInterval() method stops the executions of the function specified in the
setInterval() method.
[Link](timerVariable)
JavaScript String
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
By string literal
By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating string using
string literal is given below:
var stringname="string value";
Let's see the simple example of creating string literal.
<script>
var str="This is string literal";
[Link](str);
</script>
Methods Description
substr() It is used to fetch the part of the given string on the basis
of the specified starting position and length.
substring() It is used to fetch the part of the given string on the basis
of the specified index.
split() It splits a string into substring array, then returns that newly
created array.
trim() It trims the white space from the left and right side of the
string.
Example1:
<!DOCTYPE html>
<html>
<body>
<script>
var str="javascript";
[Link]([Link](2));
</script>
</body>
</html>
Example 2:
<!DOCTYPE html>
<html>
<body>
<script>
var s1="JavaScript toLowerCase Example";
var s2=[Link]();
[Link](s2);
</script>
</body>
</html>
Regular expression
A regular expression is an object that describes a pattern of characters.
The JavaScript RegExp class represents regular expressions, and both String and
RegExp define methods that use regular expressions to perform powerful pattern-
matching and search-and-replace functions on text.
Syntax
var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /pattern/attributes;
here/mumbai/i is a city
● pattern − A string that specifies the pattern of the regular expression or another
regular expression.
● attributes − An optional string containing any of the "g", "i", and "m"
attributes that specify global, case-insensitive, and multi-line matches,
respectively.
Brackets
Brackets ([ ]) have a special meaning when used in the context of regular
expressions. They are used to find a range of characters.
[Link]. Expression & Description
1 [...]
Any one character between the brackets.
3 [0-9]
It matches any decimal digit from 0 through 9.
4 [a-z]
It matches any character from lowercase a through lowercase z.
5 [A-Z]
It matches any character from uppercase A through uppercase Z.
6 [a-Z]
It matches any character from lowercase a through uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to match
any decimal digit ranging from 0 through 3, or the range [b-v] to match any
lowercase character ranging from b through v.
Quantifiers
The frequency or position of bracketed character sequences and single characters
can be denoted by a special character. Each special character has a specific
connotation. The +, *, ?, and $ flags all follow a character sequence.
[Link]. Expression & Description
1 p+
It matches any string containing one or more p's.
2 p*
It matches any string containing zero or more p's.
3 p?
It matches any string containing at most one p.
4 p{N}
It matches any string containing a sequence of N p's
5 p{2,3}
It matches any string containing a sequence of two or three p's.
6 p{2, }
It matches any string containing a sequence of at least two p's.
7 p$
It matches any string with p at the end of it.
8 ^p
It matches any string with p at the beginning of it.
Examples
Following examples explain more about matching characters.
[Link] Expression & Description
.
1 [^a-z A-Z]
It matches any string not containing any of the characters ranging from a
through z and A through Z.
2 p.p
It matches any string containing p, followed by any character, in turn
followed by another p.
3 ^.{2}$
It matches any string containing exactly two characters.
4 <b>(.*)</b>
It matches any string enclosed within <b> and </b>.
5 p(hp)*
It matches any string containing a p followed by zero or more instances of
the sequence hp.
Literal characters
[Link] Character & Description
.
1 Alphanumeric
Itself- A to Z ,0-9
2 \0
The NUL character (\u0000)
3 \t
Tab (\u0009
4 \n
Newline (\u000A)
5 \v
Vertical tab (\u000B)
6 \f
Form feed (\u000C)
7 \r
Carriage return (\u000D)
8 \xnn
The Latin character specified by the hexadecimal number nn; for example,
\x0A is the same as \n
9 \uxxxx
The Unicode character specified by the hexadecimal number xxxx; for
example, \u0009 is the same as \t
10 \cX
The control character ^X; for example, \cJ is equivalent to the newline
character \n
Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that
acts to give the combination a special meaning.
For instance, you can search for a large sum of money using the '\d' metacharacter:
/([\d]+)000/, Here \d will search for any string of numerical character.
The following table lists a set of metacharacters which can be used in PERL Style
Regular Expressions.
[Link] Character & Description
.
1 .
a single character
2 \s
a whitespace character (space, tab, newline)
3 \S
non-whitespace character
4 \d
a digit (0-9)
5 \D
a non-digit
6 \w
a word character (a-z, A-Z, 0-9, _)
7 \W
a non-word character
8 [\b]
a literal backspace (special case).
9 [aeiou]
matches a single character in the given set
10 [^aeiou]
matches a single character outside the given set
11 (foo|bar|baz)
matches any of the alternatives specified
Modifiers
Several modifiers are available that can simplify the way you work with regexps,
like case sensitivity, searching in multiple lines, etc.
[Link] Modifier & Description
.
1 i
Perform case-insensitive matching.
2 m
Specifies that if the string has newline or carriage return characters, the ^
and $ operators will now match against a newline boundary, instead of a
string boundary
3 g
Performs a global match that is, find all matches rather than stopping after
the first match.
RegExp Properties
Here is a list of the properties associated with RegExp and their description.
[Link]. Property & Description
1 constructor
Specifies the function that creates an object's prototype.
2 global
Specifies if the "g" modifier is set.
3 ignoreCase
Specifies if the "i" modifier is set.
4 lastIndex
The index at which to start the next match.
5 multiline
Specifies if the "m" modifier is set.
6 source
The text of the pattern.
In the following sections, we will have a few examples to demonstrate the usage of
RegExp properties.
RegExp Methods
Here is a list of the methods associated with RegExp along with their description.
[Link] Method & Description
.
1 exec()
Executes a search for a match in its string parameter.
2 test()
Tests for a match in its string parameter.
3 toSource()
Returns an object literal representing the specified object; you can use this
value to create a new object.
4 toString()
Returns a string representing the specified object.
The math object provides you properties and methods for mathematical constants
and functions. Unlike other global objects, Math is not a constructor. All the
properties and methods of Math are static and can be called by using Math as an
object without creating it.
Thus, you refer to the constant pi as [Link] and you call the sine function as
[Link](x), where x is the method's argument.
Syntax
The syntax to call the properties and methods of Math are as follows
var pi_val = [Link];
var sine_val = [Link](30);
Math Methods
Here is a list of the methods associated with Math object and their description
[Link] Method & Description
.
1 abs()
Returns the absolute value of a number.
2 acos()
Returns the arccosine (in radians) of a number.
3 asin()
Returns the arcsine (in radians) of a number.
4 atan()
Returns the arctangent (in radians) of a number.
5 atan2()
Returns the arctangent of the quotient of its arguments.
6 ceil()
Returns the smallest integer greater than or equal to a number.
7 cos()
Returns the cosine of a number.
8 exp()
Returns EN, where N is the argument, and E is Euler's constant, the base
of the natural logarithm.
9 floor()
Returns the largest integer less than or equal to a number.
10 log()
Returns the natural logarithm (base E) of a number.
11 max()
Returns the largest of zero or more numbers.
12 min()
Returns the smallest of zero or more numbers.
13 pow()
Returns base to the exponent power, that is, base exponent.
14 random()
Returns a pseudo-random number between 0 and 1.
15 round()
Returns the value of a number rounded to the nearest integer.
16 sin()
Returns the sine of a number.
17 sqrt()
Returns the square root of a number.
18 tan()
Returns the tangent of a number.
19 toSource()
Returns the string "Math".
getDay() It returns the integer value between 0 and 6 that represents the
day of the week on the basis of local time.
getFullYears() It returns the integer value that represents the year on the basis
of local time.
getMilliseconds() It returns the integer value between 0 and 999 that represents
the milliseconds on the basis of local time.
getUTCDay() It returns the integer value between 0 and 6 that represents the
day of the week on the basis of universal time.
getUTCFullYears It returns the integer value that represents the year on the basis
() of universal time.
setDate() It sets the day value for the specified date on the basis of local
time.
setDay() It sets the particular day of the week on the basis of local time.
setFullYears() It sets the year value for the specified date on the basis of local
time.
setHours() It sets the hour value for the specified date on the basis of local
time.
setMilliseconds() It sets the millisecond value for the specified date on the basis
of local time.
setMinutes() It sets the minute value for the specified date on the basis of
local time.
setMonth() It sets the month value for the specified date on the basis of
local time.
setSeconds() It sets the second value for the specified date on the basis of
local time.
setUTCDate() It sets the day value for the specified date on the basis of
universal time.
setUTCDay() It sets the particular day of the week on the basis of universal
time.
setUTCFullYears It sets the year value for the specified date on the basis of
() universal time.
setUTCHours() It sets the hour value for the specified date on the basis of
universal time.
setUTCMilliseco It sets the millisecond value for the specified date on the basis
nds() of universal time.
setUTCMinutes() It sets the minute value for the specified date on the basis of
universal time.
setUTCMonth() It sets the month value for the specified date on the basis of
universal time.
setUTCSeconds() It sets the second value for the specified date on the basis of
universal time.
toUTCString() It converts the specified date in the form of string using UTC
time zone.
Example:
<html>
<body>
Current Date and Time: <span id="txt"></span>
<script>
var today=new Date();
[Link]('txt').innerHTML=today;
</script>
</body>
</html>
Window Object
The Browser Object Model (BOM) is used to interact with the browser.
The default object of browser is window means you can call all the functions
of window by specifying window or directly. For example:
[Link]("hello javatpoint");
Method Description
confirm() displays the confirm dialog box containing a message with ok and
cancel buttons.
setTimeou performs action after specified time like calling function, evaluating
t() expressions etc.
<script type="text/javascript">
function msg()
{
open("[Link]
}
</script>
<input type="button" value="javatpoint" onclick="msg()"/>
JavaScript Navigator Object
The JavaScript navigator object is used for browser detection. It can be used to
get browser information such as appName, appCodeName, userAgent etc.
[Link]
<html>
<body>
<script>
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
</script>
</body>
</html>
The JavaScript history object represents an array of URLs visited by the user. By
using this object, you can load previous, forward or any particular page.
[Link]
Location Object
The location object is part of the window object and is accessed through the
[Link] property.
Property Description
<!DOCTYPE html>
<html>
<body>
<p id="a"></p>
<script>
[Link]("a").innerHTML
+ [Link]; </script>
</body></html>
JavaScript HTML DOM Document
If you want to access any element in an HTML page, you always start with accessing
the document object.
Below are some examples of how you can use the document object to access and
manipulate HTML.
Method Description
Method Description
Method Description
Method Description
[Link](id).onclick = Adding event handler code to an
function(){code} onclick event
The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections,
and properties. These are still valid in HTML5.
Later, in HTML DOM Level 3, more objects, collections, and properties were added.
When a user sends a request to the server, then each of that request is treated as a
new request sent by the different user.
So, to recognize the old user, we need to add the cookie with the response from the
server.
Now, whenever a user sends a request to the server, the cookie is added with that
request automatically. Due to the cookie, the server recognizes the users.
JavaScript Cookies
How to create a Cookie in JavaScript?
[Link]="name=value";
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function setCookie()
[Link]="username=Duke Martin";
function getCookie()
if([Link]!=0)
{
alert([Link]);
else
</script>
</body>
</html>
will become easier for programmers and users to glide through the document. With
DOM, we can easily access and manipulate tags, IDs, classes, Attributes or Elements
using commands or methods provided by Document object.
Structure of DOM:
DOM can be thought of as Tree or Forest(more than one tree). The term structure
model is sometimes used to describe the tree-like representation of a document. One
important property of DOM structure models is structural isomorphism: if any two
DOM implementations are used to create a representation of the same document,
they will create the same structure model, with precisely the same objects and
relationships.
6. Form Control Elements:: Form can have many control elements such
as text fields, buttons, radio buttons, and checkboxes, etc.
It is important to validate the form submitted by the user because it can have
inappropriate values. So, validation is must to authenticate users.
JavaScript provides a facility to validate the form on the client-side so data
processing will be faster than server-side validation. Most of the web developers
prefer JavaScript form validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers
and more fields.
JavaScript Form Validation Example
In this example, we are going to validate the name and password. The name can’t be
empty and the password can’t be less than 6 characters long.
Here, we are validating the form on form submit. The user will not be forwarded to
the next page until given values are correct.
<script>
function validateform(){
var name=[Link];
var password=[Link];
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if([Link]<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="[Link]" onsubmit="return
validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
<script>
function validate(){
var num=[Link];
if (isNaN(num)){
[Link]("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>
There are many criteria that need to be follow to validate the email id such as:
<script>
function validateemail()
{
var x=[Link];
var atposition=[Link]("@");
var dotposition=[Link](".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=[Link]){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n
dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return
validateemail();">
Email: <input type="text" name="email"><br/>