0% found this document useful (0 votes)
23 views

HTML-Java Script Basics

HTML is a markup language used to define the structure and layout of web pages. It can be used to create basic static web pages. JavaScript is a scripting language used to make web pages interactive. Key HTML tags include <html>, <head>, <title>, <body>, <h1>, <p> while JavaScript can be inserted within <script> tags and is used to add behaviors and validation to web pages. Common JavaScript examples include alerts, validating forms, and changing content dynamically.

Uploaded by

Sharad Dhumal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

HTML-Java Script Basics

HTML is a markup language used to define the structure and layout of web pages. It can be used to create basic static web pages. JavaScript is a scripting language used to make web pages interactive. Key HTML tags include <html>, <head>, <title>, <body>, <h1>, <p> while JavaScript can be inserted within <script> tags and is used to add behaviors and validation to web pages. Common JavaScript examples include alerts, validating forms, and changing content dynamically.

Uploaded by

Sharad Dhumal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

HTML & JavaScript

● HTML stands for HyperText Markup Language.


● HTML is used to create web pages and web applications.
● HTML is widely used language on the web.
● We can create a static website by HTML only.
● Technically, HTML is a Markup language rather than a programming
language.
<!DOCTYPE>: It defines the document type or it instruct the browser about the version of HTML.

<html > :This tag informs the browser that it is an HTML document.

Text between html tag describes the web document. It is a container for all other elements of HTML
except <!DOCTYPE>

<head>: It should be the first element inside the <html> element, which contains the metadata(information
about the document).

It must be closed before the body tag opens.

<title>: As its name suggested, it is used to add title of that HTML page which appears at the top of the
browser window.

It must be placed inside the head tag and should close immediately. (Optional)

<body> : Text between body tag describes the body content of the page that is visible to the end user.

This tag contains the main content of the HTML document.

<h1> : Text between <h1> tag describes the first level heading of the webpage.

<p> : Text between <p> tag describes the paragraph of the webpage.
Features of HTML
1) It is a very easy and simple language. It can be easily understood and modified.

2) It is very easy to make an effective presentation with HTML because it has a lot of formatting tags.

3) It is a markup language, so it provides a flexible way to design web pages along with the text.

4) It facilitates programmers to add a link on the web pages (by html anchor tag),

so it enhances the interest of browsing of the user.

5) It is platform-independent because it can be displayed on any platform like Windows, Linux, and
Macintosh, etc.

6) It facilitates the programmer to add Graphics, Videos, and Sound to the web pages which makes it
more attractive and interactive.

7) HTML is a case-insensitive language, which means we can use tags either in lower-case or upper-case.
Building blocks of HTML
An HTML document consist of its basic building blocks which are:

● Tags: An HTML tag surrounds the content and apply meaning to it. It is written between < and >
brackets.
● Attribute: An attribute in HTML provides extra information about the element, and it is applied within
the start tag. An HTML attribute contains two fields: name & value.

Syntax
<tag name attribute_name= " attr_value"> content </ tag name>
<p> Paragraph Tag </p>

<h2> Heading Tag </h2>


<b> Bold Tag </b>

<i> Italic Tag </i>

<u> Underline Tag</u>


Unclosed HTML Tags
Some HTML tags are not closed, for example br and hr.
<br> Tag: br stands for break line, it breaks the line of the code.
<hr> Tag: hr stands for Horizontal Rule. This tag is used to put a line across the webpage.

HTML Meta Tags


DOCTYPE, title, link, meta and style

HTML Text Tags


<p>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <strong>, <em>, <abbr>, <acronym>, <address>, <bdo>,
<blockquote>, <cite>, <q>, <code>, <ins>, <del>, <dfn>, <kbd>, <pre>, <samp>, <var> and <br>

HTML Link Tags


<a> and <base>
JavaScript
JavaScript is an object-based scripting language which is lightweight and
cross-platform.
JavaScript is not a compiled language, but it is a translated language.
The JavaScript Translator (embedded in the browser) is responsible for
translating the JavaScript code for the web browser.

What is JavaScript
JavaScript (js) is a light-weight object-oriented programming language which
is used by several websites for scripting the webpages.
It is an interpreted, full-fledged programming language that enables dynamic
interactivity on websites when applied to an HTML document.
It was introduced in the year 1995 for adding programs to the webpages in
the Netscape Navigator browser.
It has been adopted by all other graphical web browsers.
With JavaScript, users can build modern web applications to interact directly
without reloading the page every time.
The traditional website uses js to provide several forms of interactivity and
simplicity.
Although, JavaScript has no connectivity with Java programming language.
The name was suggested and provided in the times when Java was gaining
popularity in the market.
In addition to web browsers, databases such as CouchDB and MongoDB uses
JavaScript as their scripting and query language.
Features of JavaScript

There are following features of JavaScript:

1. All popular web browsers support JavaScript as they provide built-in execution environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is a
structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending on
the operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather than
using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS, etc.
8. It provides good control to the users over the web browsers.
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:

● Client-side validation,
● Dynamic drop-down menus,
● Displaying date and time,
● Displaying pop-up windows and dialog boxes (like an alert dialog box,
confirm dialog box and prompt dialog box),
● Displaying clocks etc.
JavaScript Example
JavaScript provides 3 places to put the JavaScript code:

1. within body tag,


2. within head tag and
3. external JavaScript file.

Let’s create the first JavaScript example.

<script type="text/javascript">

document.write("JavaScript is a simple language");

</script>

The script tag specifies that we are using JavaScript.

The text/javascript is the content type that provides information to the browser about the data.

The document.write() function is used to display dynamic content through JavaScript.


1) Within body Tag

<html>
<body>
<script type="text/javascript">
alert("Hello Javatpoint");
</script>
</body>
</html>
2) Between the Head tag
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello World!");
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
3) External JavaScript file
We can create external JavaScript file and embed it in many html page.
It provides code re usability because single JavaScript file can be used in
several html pages.
An external JavaScript file must be saved by .js extension.
It is recommended to embed all JavaScript files into a single file.
It increases the speed of the webpage.
<html>

<head>

<script type="text/javascript" src="message.js"></script>

</head>

<body>

<p>Welcome to JavaScript</p>

<form>

<input type="button" value="click" onclick="msg()"/>

</form>

</body>

</html>
Advantages of External JavaScript
There will be following benefits if a user creates an external javascript:

1. It helps in the reusability of code in more than one HTML file.


2. It allows easy code readability.
3. It is time-efficient as web browsers cache the external js files, which further
reduces the page loading time.
4. It enables both web designers and coders to work with html and js files
parallelly and separately, i.e., without facing any code conflictions.
5. The length of the code reduces as only we need to specify the location of the
js file.
Disadvantages of External JavaScript
There are the following disadvantages of external files:

1. The stealer may download the coder's code using the url of the js file.
2. If two js files are dependent on one another, then a failure in one file may affect
the execution of the other dependent file.
3. The web browser needs to make an additional http request to get the js code.
4. A tiny to a large change in the js code may cause unexpected results in all its
dependent files.
5. We need to check each file that depends on the commonly created external
javascript file.
6. If it is a few lines of code, then better to implement the internal javascript code.
JavaScript comments
The JavaScript comments are meaningful way to deliver message.

It is used to add information about the code, warnings or suggestions so that end user can easily interpret
the code.

Advantages of JavaScript comments

There are mainly two advantages of JavaScript comments.

1. To make code easy to understand It can be used to elaborate the code so that end user can easily
understand the code.
2. To avoid the unnecessary code It can also be used to avoid the code being executed.

Sometimes, we add the code to perform some action.

But after sometime, there may be need to disable the code. In such case, it is better to use
Types of JavaScript Comments
There are two types of comments in JavaScript.

1. Single-line Comment
2. Multi-line Comment

<script>

// It is single line comment

/* abc

Defg */

</script>
JavaScript Variable
A JavaScript variable is simply a name of storage location.

There are two types of variables in JavaScript :

local variable and global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).

1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.


2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.

Correct JavaScript variables


1. var x = 10;
2. var _value="sonoo";

Incorrect JavaScript variables


1. var 123=30;
2. var *aa=320;
global variable
A JavaScript global variable is accessible from any function.

A variable i.e. declared outside the function or declared with window object is known as global variable.

JavaScript global variable within function

To declare JavaScript global variables inside function, you need to use window object.

For example:

1. window.value=90;
Javascript Data Types
JavaScript provides different data types to hold different types of values. There are two types of data types in JavaScript.

1. Primitive data type


2. Non-primitive (reference) data type

JavaScript is a dynamic type language, means you don't need to specify type of the variable because it is dynamically used by
JavaScript engine.

You need to use var here to specify the data type.

It can hold any type of values such as numbers, strings etc. For example:

1. var a=40;//holding number


2. var b="Rahul";//holding string
Primitive Data types:
String -> represents sequence of characters e.g. "hello"
Number -> represents numeric values e.g. 100
Boolean -> represents boolean value either false or true
Undefined -> represents undefined value
Null -> represents null i.e. no value at all

non-primitive data types


Object -> represents instance through which we can access members

Array -> represents group of similar values

RegExp -> represents regular expression


JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For example:

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
Comparison Operators
Assignment Operators
Logical Operators

Bitwise Operators
Special Operators
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

Example :

<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
JavaScript Switch

The JavaScript switch statement is used to execute one code from multiple expressions.

It is just like else if statement that we have learned in previous page.

But it is convenient than if..else..if because it can be used with numbers, characters etc.

<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";

document.write(result);

</script>
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 -> used to iterate the properties of an object

Example
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method).

For example: car, pen, bike, chair, glass, keyboard, monitor etc.

JavaScript is an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class based.

Here, we don't create class to get the object. But, we direct create objects.

There are 3 ways to create objects.

1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
JavaScript Object by object literal
The syntax of creating object using object literal is given below:

object={property1:value1, property2:value2, .....propertyN:valueN}

As you can see, property and value is separated by : (colon).

Let’s see the simple example of creating object in JavaScript.

<script>

emp={id:101,name:"Sandeep",salary:30000}

document.write(emp.id+" "+emp.name+" "+emp.salary);

</script>
By creating instance of Object
The syntax of creating object directly is given below:

var objectname=new Object();

Here, new keyword is used to create object.

Let’s see the example of creating object directly.

<script>

var emp=new Object();

emp.id=101;

emp.name="Sandeep";

emp.salary=25000;

document.write(emp.id+" "+emp.name+" "+emp.salary);

</script>
By using an Object constructor
Here, you need to create function with arguments.

Each argument value can be assigned in the current object by using this keyword.

The this keyword refers to the current object.

The example of creating object by object constructor is given below.

<script>

function emp(id,name,salary){

this.id=id;

this.name=name;

this.salary=salary;

e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);

</script>
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.

There are 3 ways to construct array in JavaScript

1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)

1) JavaScript array literal

The syntax of creating array using array literal is given below:

var arrayname=[value1,value2.....valueN];

As you can see, values are contained inside [ ] and separated by , (comma).

Let's see the simple example of creating and using array in JavaScript.

<script> var emp=["Vijay","Ajay","Ravi"];

for (i=0;i<emp.length;i++){

document.write(emp[i] + "<br/>"); } </script>


JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:

var arrayname=new Array();

Here, new keyword is used to create instance of array.

var i;

var emp = new Array();

emp[0] = "Ajay";

emp[1] = "Vijay";

emp[2] = "Rahul";

With Array constructor

var emp=new Array("Ajay","Vijay","shyam")


JavaScript String
The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript

1. By string literal
2. 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 test="Hello world !!";

2) using new Keyword


var test=new String("Hello world !!");
JavaScript Date Object
The JavaScript date object can be used to get year, month and day.

You can display a timer on the webpage by the help of JavaScript date object.

You can use different Date constructors to create date object.

It provides methods to get and set day, month, year, hour, minute and seconds.

Constructor
You can use 4 variant of Date constructor to create date object.

1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)
Date example:
<script>
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month+"/"+year);
</script>

Time:
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
Browser Object Model
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

Window Object
The window object represents a window in browser.

An object of window is created automatically by the browser.

Window is the object of browser, it is not the object of javascript.

The javascript objects are string, array, date etc.


Methods of window object
JavaScript Events
The change in the state of an object is known as an Event.

In html, there are various events which represents that some activity is performed by the user or by the browser.

When javascript code is included in HTML, js react over these events and allow the execution.

This process of reacting over the events is called Event Handling.

Thus, js handles the HTML events via Event Handlers.

For example, when a user clicks over the browser, add js code, which will execute the task to be performed on the event.
Document Object Model
The document object represents the whole html document.

When html document is loaded in the browser, it becomes a document object.

It is the root element that represents the html document.

It has properties and methods. By the help of document object, we can add dynamic content to
our web page.

1. window.document

Is same as

1. document

According to W3C - "The W3C Document Object Model (DOM) is a platform and language-neutral
interface that allows programs and scripts to dynamically access and update the content, structure,
and style of a document."
Properties of document object
Methods of document object
1. <script type="text/javascript">
2. function printvalue(){
3. var name=document.form1.name.value;
4. alert("Welcome: "+name);
5. }
6. </script>
7.
8. <form name="form1">
9. Enter Name:<input type="text" name="name"/>
10. <input type="button" onclick="printvalue()" value="print name"/>
11. </form>
document.getElementById() method
The document.getElementById() method returns the element of specified id.

1. <script type="text/javascript">
2. function getcube(){
3. var number=document.getElementById("number").value;
4. alert(number*number*number);
5. }
6. </script>
7. <form>
8. Enter No:<input type="text" id="number" name="number"/><br/>
9. <input type="button" value="cube" onclick="getcube()"/>
10. </form>
document.getElementsByName() method
1. <script type="text/javascript">
2. function totalelements()
3. {
4. var allgenders=document.getElementsByName("gender");
5. alert("Total Genders:"+allgenders.length);
6. }
7. </script>
8. <form>
9. Male:<input type="radio" name="gender" value="male">
10. Female:<input type="radio" name="gender" value="female">
11. <input type="button" onclick="totalelements()" value="Total Genders">
12. </form>
JavaScript Form Validation
It is important to validate the form submitted by the user because it can have
inappropriate values.

So, validation is must to authenticate user.


JavaScript provides 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.

We can validate name, password, email, date, mobile numbers and more fields.
JavaScript email validation
We can validate the email by the help of JavaScript.

There are many criteria that need to be follow to validate the email id such as:

● email id must contain the @ and . character


● There must be at least one character before and after the @.
● There must be at least two characters after . (dot).
JavaScript Classes
In JavaScript, classes are the special type of functions.

We can define the class just like function declarations and function expressions.

The JavaScript class contains various class members within a body including methods or constructor.

The class is executed in strict mode. So, the code containing the silent error or mistake throws an error.

Class Declarations
A class can be defined by using a class declaration.

A class keyword is used to declare a class with any particular name.

According to JavaScript naming conventions, the name of the class always starts with an uppercase letter.

Example:
Class expressions
Another way to define a class is by using a class expression.

Here, it is not mandatory to assign the name of the class.

So, the class expression can be named or unnamed.

The class expression allows us to fetch the class name.

However, this will not be possible with class declaration.

Unnamed Class Expression

The class can be expressed without assigning any name to it.


Exception Handling in JavaScript
An exception signifies the presence of an abnormal condition which requires special
operable techniques
an exception is the anomalous code that breaks the normal flow of the code.

What is exception handling:

exception handling is a process or method used for handling the abnormal statements in the
code and executing them.

It also enables to handle the flow control of the code/program.

For handling the code, various handlers are used that process the exception and execute the
code.

For example, the Division of a non-zero value with zero will result into infinity always, and it is
an exception.

Thus, with the help of exception handling, it can be executed and handled.
Types of Errors
While coding, there can be three types of errors in the code:

1. Syntax Error: When a user makes a mistake in the pre-defined syntax of a programming
language, a syntax error may appear.
2. Runtime Error: When an error occurs during the execution of the program, such an error
is known as Runtime error. The codes which create runtime errors are known as
Exceptions. Thus, exception handlers are used for handling runtime errors.
3. Logical Error: An error which occurs when there is any logical mistake in the program
that may not produce the desired output, and may terminate abnormally. Such an error
is known as Logical error.
Error Object

When a runtime error occurs, it creates and throws an Error object. Such an object can be used as a base for the
user-defined exceptions too. An error object has two properties:

1. name: This is an object property that sets or returns an error name.


2. message: This property returns an error message in the string form.

Although Error is a generic constructor, there are following standard built-in error types or error constructors
beside it:

1. EvalError: It creates an instance for the error that occurred in the eval(), which is a global function used for
evaluating the js string code.
2. InternalError: It creates an instance when the js engine throws an internal error.
3. RangeError: It creates an instance for the error that occurs when a numeric variable or parameter is out of
its valid range.
4. ReferenceError: It creates an instance for the error that occurs when an invalid reference is de-referenced.
5. SyntaxError: An instance is created for the syntax error that may occur while parsing the eval().
6. TypeError: When a variable is not a valid type, an instance is created for such an error.
7. URIError: An instance is created for the error that occurs when invalid parameters are passed in
Exception Handling Statements
There are following statements that handle if any exception occurs:

● throw statements
● try…catch statements
● try…catch…finally statements.
JavaScript try…catch
A try…catch is a commonly used statement in various programming languages.

Basically, it is used to handle the error-prone part of the code.

It initially tests the code for all possible errors it may contain, then it implements
actions to tackle those errors (if occur).

A good programming approach is to keep the complex code within the try…catch
statements.
try{} statement: Here, the code which needs possible error testing is kept within the try
block.

In case any error occur, it passes to the catch{} block for taking suitable actions and handle
the error.

Otherwise, it executes the code written within.

catch{} statement: This block handles the error of the code by executing the set of
statements written within the block.

This block contains either the user-defined exception handler or the built-in handler.

This block executes only when any error-prone code needs to be handled in the try block.

Otherwise, the catch block is skipped.


1. try{
2. expression; } //code to be written.
3. catch(error){
4. expression; } // code for handling the error.
try…catch…finally statements
Finally is an optional block of statements which is executed after the execution of try and
catch statements.

Finally block does not hold for the exception to be thrown.

Any exception is thrown or not, finally block code, if present, will definitely execute.

You might also like