java
java
------------
Introduction
------------
=> JavaScript is designed for beginners and professionals both. JavaScript is used to create client-side
dynamic pages.
=> 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.
=> 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.
History of JavaScript
----------------------
=> the company merged with Sun Microsystems for adding Java into its Navigator so that it could
compete with Microsoft over the web technologies and platforms. Now, two languages were there:Java
and the scripting language.
=>Further, Netscape decided to give a similar name to the scripting language as Java's. It led to
'Javascript'. Finally, in May 1995, Marc Andreessen coined the first code of Javascript named 'Mocha'.
Later,
=> the marketing team replaced the name with 'LiveScript'. But, due to trademark reasons and certain
other reasons, in December 1995, the language was finally renamed to 'JavaScript'. From then,
JavaScript came into existence.
Application of JavaScript
-------------------------
=> Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and prompt
dialog box),
JavaScript Example
-------------------
<script>
</script>
-------------------------
<html>
<body>
<script type="text/javascript">
alert("Hello Apollo");
</script>
</body>
</html>
-------------------------
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
</form>
</body>
</html>
-------------------------
=> We can create external JavaScript file and embed it in many html page.
=> It provides code reusability 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.
function msg(){
alert("Hello apollo");
<html>
<head>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
</form>
</body>
</html>
----------------------------------
=> It helps in the reusability of code in more than one HTML file.
=> It is time-efficient as web browsers cache the external js files, which further reduces the page loading
time.
JavaScript Comment
------------------
=> 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.
The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.
-------------------------------------
-> It can be used to elaborate the code so that end user can easily understand the 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
comments.
------------------------------
It is represented by double forward slashes (//). It can be used before and after the statement.
Example
----------
<html>
<body>
<script>
document.write("hello javascript");
</script>
-------------------------------
It can be used to add single as well as multi line comments. So, it is more convenient.
It is represented by forward slash with asterisk then asterisk with forward slash. For example:
<html>
/*<body>
<script>
</script>
</body>*/
</html>
</body>
</html>
JavaScript variable
----------------------
There are some rules while declaring a JavaScript variable (also known as identifiers).
=> Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
=> After first letter we can use digits (0 to 9), for example value1.
=> JavaScript variables are case sensitive, for example x and X are different variables.
Example
-------
var x = 10;
var _value="Ajay";
---------------------
=> JavaScript provides different data types to hold different types of values. There are two types of data
types in JavaScript.
----------------------------------
There are five types of primitive data types in JavaScript. They are as follows:
-----------------------------------------
------------------------------------
The non-primitive data types are as follows:
------------------------------------
JavaScript Operators
---------------------
JavaScript operators are symbols that are used to perform operations on operands. For example:
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
Syntex
--------
if(expression){
//content to be evaluated
Syntex
--------
if(expression){
else{
Syntex
--------
if(expression1){
else if(expression2){
else if(expression3){
else{
JavaScript Switch
------------------
=> The JavaScript switch statement is used to execute one code from multiple expressions.
Syntex
--------
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
/////////////////////////////////////////////////////////////////////
JavaScript Loops
-------------------
=> The JavaScript loops are used to iterate the piece of code using for, while, do while It makes the code
compact.
1.for loop
syntex
---------
code to be executed
2.while loop
-------------
syntex
---------
intialization;
while (condition)
{
code to be executed
increment/decrement;
3.do-while loop
---------------
syntex
---------
intialization;
do{
code to be executed
increment/decrement;
}while (condition);
JavaScript Functions
---------------------
=> JavaScript functions are used to perform operations. We can call JavaScript function many times to
reuse the code.
---------------------------------------
2.Less coding: It makes our program compact. We don’t need to write many lines of code each time to
perform a common task.
--------------------------
//code to be executed
}
----------------------------
<html>
<body>
<script>
function msg(){
</script>
</body>
</html>
===============================
=> We can call function by passing arguments. Let’s see the example of function that has one argument.
example
---------
<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
</script>
<form>
</form>
</body>
</html>
===============================
=> We can call function that returns a value and use it in our program. Let’s see the example of
example
---------
<html>
<body>
<script>
function getInfo(){
</script>
<script>
document.write(getInfo());
</script>
</body>
</html>
===========================
=> In JavaScript, the purpose of Function constructor is to create a new Function object. It executes the
code globally.
Syntax
----------
Method Description
apply() - It is used to call a function contains this value and a single array of arguments.
call() - It is used to call a function contains this value and an argument list.
example.
=========
<html>
<body>
<script>
document.writeln(add(2,5));
</script>
</body>
</html>
JavaScript Array
------------------
=> JavaScript array is an object that represents a collection of similar type of elements.
- By array literal
------------------------------
Example
---------
<html>
<body>
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
</script>
</body>
</html>
---------------------------------------------
Example
---------
<html>
<body>
<script>
var i;
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
</script>
</body>
</html>
----------------------------------------------
Example
---------
<html>
<body>
<script>
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
</script>
</body>
</html>
JavaScript String
--------------------
- By string literal
1) By string literal
======================
The string literal is created using double quotes. The syntax of creating string using string
literal is given below:
Example
----------
<html>
<body>
<script>
document.write(str);
</script>
</body>
</html>
=========================================
The syntax of creating string object using new keyword is given below:
Example
-------
<html>
<body>
<script>
document.write(stringname);
</script>
</body>
</html>
===========================
Let's see the list of JavaScript string methods with examples.
Methods Description
charCodeAt() It provides the Unicode value of a character present at the specified index.
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string by searching a
character from the last position.
search() It searches a specified regular expression in a given string and returns its position if a
match occurs.
match() It searches a specified regular expression in a given string and returns that regular
expression if a match occurs.
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.
slice() It is used to fetch the part of the given string. It allows us to assign positive as well
negative index.
toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s current
locale.
toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s current
locale.
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.
-------------------------------------------
The JavaScript String charAt() method returns the character at the given index.
Example
----------
<html>
<body>
<script>
var str="javascript";
document.write(str.charAt(2));
</script>
</body>
</html>
-----------------------------------------
Example
----------
<html>
<body>
<script>
var s3=s1+s2;
document.write(s3);
</script>
</body>
</html>
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 template based not class based. Here, we don't create class to get the object. But, we
direct create objects.
--------------------------------
-----------------------------------------
object={property1:value1,property2:value2.....propertyN:valueN}
Example
----------
<html>
<body>
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
</script>
</body>
</html>
------------------------------------
The syntax of creating object directly is given below:
Example
--------
<html>
<body>
<script>
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
</script>
</body>
</html>
-------------------------------------
=> Here, you need to create function with arguments. Each argument value can be assigned in the
current object by using this keyword.
Example
--------
<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
</script>
</body>
</html>
---------------------------------------
We can define method in JavaScript object. But before defining method, we need to add property in the
function with same name as method.
Example
--------
<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
e.changeSalary(45000);
</body>
</html>
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.
Mouse events:
==============
mouseover onmouseover When the cursor of the mouse comes over the element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
Click Event
-----------
Example
-------
<html>
<body>
<!--
function clickevent()
//-->
</script>
<form>
</form>
</body>
</html>
mouseover Event
----------------
<html>
<body>
<p>The function bigImg() is triggered when the user moves the mouse pointer over the image.</p>
<p>The function normalImg() is triggered when the mouse pointer is moved out of the image.</p>
<script>
function bigImg(x) {
x.style.height = "64px";
x.style.width = "64px";
function normalImg(x) {
x.style.height = "32px";
x.style.width = "32px";
</script>
</body>
</html>
mouseout Event
----------------
<html>
<body>
<script>
function mouseOver() {
document.getElementById("demo").style.color = "red";
function mouseOut() {
document.getElementById("demo").style.color = "black";
</script>
</body>
</html>
<html>
<body>
Click the text! The mouseDown() function is triggered when the mouse button is pressed down over this
paragraph, and sets the color of the text to red. The mouseUp() function is triggered when the mouse
button is released, and sets the color of the text to green.
</p>
<script>
function mouseDown() {
document.getElementById("myP").style.color = "red";
function mouseUp() {
document.getElementById("myP").style.color = "green";
</script
</body>
</html>
-----------------
<html>
<head>
<style>
div {
width: 200px;
height: 100px;
}
</style>
</head>
<body>
<p>Mouse over the rectangle above, and get the coordinates of your mouse pointer.</p>
<p>When the mouse is moved over the div, the p element will display the horizontal and vertical
coordinates of your mouse pointer, whose values are returned from the clientX and clientY properties
on the
MouseEvent object.</p>
<p id="demo"></p>
<script>
function myFunction(e) {
var x = e.clientX;
var y = e.clientY;
document.getElementById("demo").innerHTML = coor;
function clearCoor() {
document.getElementById("demo").innerHTML = "";
</script>
</body>
</html>
JavaScript BOM
---------------
------------------------
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:
window.alert("hello apollo");
is same as:
alert("hello apollo");
Window
------
Diffrent components
1, Document
2, History
3, Screen
4, Navigator
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.
=========================
Method Description
------- ------------
confirm() displays the confirm dialog box containing message with ok and cancel button.
----------------------------------
<html>
<body>
<script type="text/javascript">
function msg(){
alert("I am "+v);
</script>
</body>
</html>
----------------------------------
<html>
<body>
<script type="text/javascript">
function msg(){
if(v==true){
alert("ok");
else{
alert("cancel");
}
}
</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.
window.history
---------------------------------------
---------------------------
//////////////////////////////////////////
<html>
<head>
</head>
<body>
<script>
function previousPage() {
window.history.back();
}S
</script>
</body>
</html>
----------------------------
=> The JavaScript navigator object is used for browser detection. It can be used to get browser
information such as appName, appCodeName, userAgent etc.
window.navigator
-----------------------------------------
There are many properties of navigator object that returns information of the browser.
10 mimeTypes[] returns the array of mime type. It is supported in Netscape and Firefox only.
---------------------------------
<html>
<body>
<script>
document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);
document.writeln("<br/>navigator.appName: "+navigator.appName);
document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);
document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);
document.writeln("<br/>navigator.language: "+navigator.language);
document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);
document.writeln("<br/>navigator.platform: "+navigator.platform);
document.writeln("<br/>navigator.onLine: "+navigator.onLine);
</script>
</body>
</html>
==========================
=> The JavaScript screen object holds information of browser screen. It can be used to display screen
width, height, colorDepth, pixelDepth etc.
window.screen
----------------------------------------
There are many properties of screen object that returns information of the browser.
-- -------- --------------
=============================================
<html>
<body>
<script>
document.writeln("<br/>screen.width: "+screen.width);
document.writeln("<br/>screen.height: "+screen.height);
document.writeln("<br/>screen.availWidth: "+screen.availWidth);
document.writeln("<br/>screen.availHeight: "+screen.availHeight);
document.writeln("<br/>screen.colorDepth: "+screen.colorDepth);
document.writeln("<br/>screen.pixelDepth: "+screen.pixelDepth);
</script>
</body>
</html>
JavaScript DOM
---------------
=>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.
=> 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.
------------------------------
Let's see the properties of document object that can be accessed and modified by the document object.
- text
- textarea
anchor - checkbox
- radio
- reset
link - button
============================
Method Description
------- -----------
writeln("string") writes the given string on the doucment with newline character at the
end.
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName() returns all the elements having the given class name.
In this example, we are going to get the value of input text by user. Here, we are using
document.form1.name.value to get the value of name field.
Here, document is the root element that represents the html document.
-----
-----
value is the property, that returns the value of the input text.
------
Let's see the simple example of document object that prints name with welcome message.
<html>
<head>
</head>
<body>
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
</script>
<form name="form1">
</form>
</body>
</html>
=====================================================
In the previous topic, we have used document.form1.name.value to get the value of the input value.
Instead of this, we can use document.getElementById() method to get value of the input text. But we
need to define id for the input field.
Let's see the simple example of document.getElementById() method that prints cube of the given
number.
<html>
<head>
</head>
<body>
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
</form>
</form>
</body>
</html>
=================================================
=> The document.getElementsByName() method returns all the element of specified name.
document.getElementsByName("name")
Example :
---------
<html>
<head>
</head>
<body>
<script type="text/javascript">
function totalelements()
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
</script>
<form>
Male:<input type="radio" name="gender" value="male">
</form>
</body>
</html>
====================================================
=> The document.getElementsByTagName() method returns all the element of specified tag name.
document.getElementsByTagName("name")
Example :1
---------
<html>
<head>
</head>
<body>
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
</script>
<p>This is a pragraph</p>
</body>
</html>
Example :2
-----------
<html>
<head>
</head>
<body>
<script type="text/javascript">
function counth2(){
var totalh2=document.getElementsByTagName("h2");
function counth3(){
var totalh3=document.getElementsByTagName("h3");
</script>
<h2>This is h2 tag</h2>
<h2>This is h2 tag</h2>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
</body>
</html>
Javascript - innerHTML
========================
=> The innerHTML property can be used to write the dynamic html on the html document.
=> It is used mostly in the web pages to generate the dynamic html such as registration form, comment
form, links etc.
In this example, we are going to create the html form when user clicks on the button.
<html>
<body>
function showcommentform() {
document.getElementById('mylocation').innerHTML=data;
</script>
<form name="myForm">
<div id="mylocation"></div>
</form>
</body>
</html>
--------------------------------------------------
<!DOCTYPE html>
<html>
<head>
<title>First JS</title>
<script>
var flag=true;
function commentform(){
if(flag){
document.getElementById("mylocation").innerHTML=cform;
flag=false;
}else{
document.getElementById("mylocation").innerHTML="";
flag=true;
</script>
</head>
<body>
<div id="mylocation"></div>
</body>
</html>
Javascript - innerText
=========================
=> The innerText property can be used to write the dynamic text on the html document. Here, text will
not be interpreted as html text but a normal text.
=> It is used mostly in the web pages to generate the dynamic content such as writing the validation
message, password strength etc.
=============================
In this example, we are going to display the password strength when releases the key after press.
<html>
<body>
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
else{
msg="poor";
document.getElementById('mylocation').innerText=msg;
</script>
<form name="myForm">
</form>
</body>
</html>
----------------------------
=> 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.
=> Through JavaScript, we can validate name, password, email, date, mobile numbers and more fields.
--------------------------------------
In this example, we are going to validate the name and password. The name can’t be empty and
password can’t be less than 6 characters long.
<html>
<body>
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
return false;
}else if(password.length<6){
return false;
</script>
<body>
</form>
</body>
</html>
-------------------------------------
<html>
<head>
<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;
if(firstpassword==secondpassword){
return true;
else{
return false;
</script>
</head>
<body>
</form>
</body>
</html>
-----------------------------
Let's validate the textfield for numeric value only. Here, we are using isNaN() function.
<html>
<head>
<script>
function validate(){
var num=document.myform.num.value;
if (isNaN(num)){
return false;
}else{
return true;
</script>
</head>
<body>
</form>
</body>
</html>
JavaScript validation with image
----------------------------------
Let’s see an interactive JavaScript form validation example that displays correct and incorrect image if
input is correct or incorrect.
<html>
<body>
<script type="text/javascript">
function validate(){
var name=document.f1.name.value;
var passwordlength=document.f1.password.value.length;
var status=false;
if(name==""){
document.getElementById("namelocation").innerHTML=
status=false;
}else{
status=true;
if(passwordlength<6){
document.getElementById("passwordlocation").innerHTML=
status=false;
}else{
return status;
}
</script>
<table>
</table>
</form>
</body>
</html>
------------------------------
There are many criteria that need to be follow to validate the email id such as:
example
----------
<html>
<body>
<script>
function validateemail()
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
return false;
</script>
<body>
</form>
</body>
</html>
JavaScript Debugging
=====================
=> Sometimes a code may contain certain mistakes. Being a scripting language, JavaScript didn't show
any error message in a browser. But these mistakes can affect the output.
=> The best practice to find out the error is to debug the code. The code can be debugged easily by using
web browsers like Google Chrome, Mozilla Firebox.
==============================
=> Here, we will find out errors using built-in web browser debugger. To perform debugging, we can use
any of the following approaches:
The console.log() method displays the result in the console of the browser. If there is any mistake in the
code, it generates the error message.
Example
--------
<html>
<title>My Debugging</title>
<body>
<script>
x = 10;
y = 15;
z = x + y;
console.log(z);
</script>
</body>
</html>
---------------------------
=> In debugging, generally we set breakpoints to examine each line of code step by step.
=> JavaScript provides debugger keyword to set the breakpoint through the code itself.
=> The debugger stops the execution of the program at the position it is applied.
=> If an exception occurs, the execution will stop again on that particular line.
example
---------
<html>
<body>
<h2>JavaScript Debugger</h2>
<p id="demo"></p>
<p>With the debugger turned on, the code below should stop executing before it executes the third
line.</p>
<script>
let x = 15 * 5;
debugger;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
JavaScript Hoisting
-------------------
=> Hoisting is a mechanism in JavaScript that moves the declaration of variables and functions at the
top. So, in JavaScript we can use variables and functions before declaring them.
=> JavaScript hoisting is applicable only for declaration not initialization. It is required to initialize the
variables and functions before using their values.
Hoisting Example
----------------
<html>
<title>My Hoisting</title>
<body>
<script>
x=10;
document.write(x);
var x;
</script>
</body>
</html>
------------------------------
<html>
<title>My Hoisting</title>
<body>
<script>
document.write(sum(10,20));
function sum(a,b)
return a+b;
</script>
</body>
</html>
-------------------------
=> Being a scripting language, sometimes the JavaScript code displays the correct result even it has
some errors. To overcome this problem we can use the JavaScript strict mode.
=> The JavaScript provides "use strict"; expression to enable the strict mode. If there is any silent error
or mistake in the code, it throws an error.
Console.Log Example
--------------
<html>
<body>
<script>
x=10;
console.log(x);
</script>
</body>
</html>
strict Example
-----------------
<html>
<title>My Strict</title>
<body>
<script>
console.log(sum(10,20));
function sum(a,a)
"use strict";
return a+a;
</script>
</body>
</html>