HTML-Java Script Basics
HTML-Java Script Basics
<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).
<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.
<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),
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>
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
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:
<script type="text/javascript">
</script>
The text/javascript is the content type that provides information to the browser about the data.
<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>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
</form>
</body>
</html>
Advantages of External JavaScript
There will be following benefits if a user creates an external javascript:
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.
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.
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>
/* abc
Defg */
</script>
JavaScript Variable
A JavaScript variable is simply a name of storage location.
There are some rules while declaring a JavaScript variable (also known as identifiers).
A variable i.e. declared outside the function or declared with window object is known as global variable.
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.
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.
It can hold any type of values such as numbers, strings etc. For example:
var sum=10+20;
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.
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.
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.
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.
Here, we don't create class to get the object. But, we direct 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:
<script>
emp={id:101,name:"Sandeep",salary:30000}
</script>
By creating instance of Object
The syntax of creating object directly is given below:
<script>
emp.id=101;
emp.name="Sandeep";
emp.salary=25000;
</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.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
</script>
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
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.
for (i=0;i<emp.length;i++){
var i;
emp[0] = "Ajay";
emp[1] = "Vijay";
emp[2] = "Rahul";
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:
You can display a timer on the webpage by the help of JavaScript 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.
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.
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.
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.
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:
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.
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.
exception handling is a process or method used for handling the abnormal statements in the
code and executing them.
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:
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.
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.
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.
Any exception is thrown or not, finally block code, if present, will definitely execute.