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

Unit III JAVA SCRIPT

Java script notes for beginners to learn it quickly

Uploaded by

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

Unit III JAVA SCRIPT

Java script notes for beginners to learn it quickly

Uploaded by

Jitendra Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

JAVA SCRIPT

Meenakshi Patel
What You Can Do with JavaScript

● You can modify the content of a web page by adding or removing


elements.
● You can change the style and position of the elements on a web page.
● You can monitor events like mouse click, hover, etc. and react to it.
● You can perform and control transitions and animations.
● You can create alert pop-ups to display info or warning messages to
the user.
● You can perform operations based on user inputs and display the
results.
● You can validate user inputs before submitting it to the server.
Adding JavaScript to Your Web Pages

● Embedding the JavaScript code between a pair of <script> and </script>


tag.
● Creating an external JavaScript file with the .js extension and then load it
within the page through the src attribute of the <script> tag.
● Placing the JavaScript code directly inside an HTML tag using the special tag
attributes such as onclick, onmouseover, onkeypress, onload, etc.
Embedding the JavaScript Code

JavaScript code directly within your web pages by placing it between the <script> and
</script> tags.

The <script> tag indicates the browser that the contained statements are to be interpreted as
executable script and not HTML.

<!DOCTYPE html> <script>


<html lang="en"> var greet = "Hello
<head> World!";
<meta charset="UTF-8"> document.write(greet);
<title>Embedding // Prints: Hello World!
JavaScript</title> </script>
</head> </body>
<body> </html>
Calling an External JavaScript File
<script src="js/hello.js"></script>

// A function to display a <!DOCTYPE html>


message <html lang="en">
function sayHello() { <head>
alert("Hello World!"); <meta charset="UTF-8">
} <title>Including External
JavaScript File</title>
// Call function on click of </head>
the button <body>
document.getElementById("myBtn <button type="button"
").onclick = sayHello; id="myBtn">Click Me</button>
<script
src="js/hello.js"></script>
</body>
</html>
Placing the JavaScript Code Inline
HTML tag using the special tag attributes such as onclick, onmouseover, onkeypress,
onload, etc.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Inlining JavaScript</title>

</head>

<body>

<button onclick="alert('Hello World!')">Click Me</button>

</body>

</html>
Difference Between Client-side and Server-side Scripting

Client-side scripting languages such as JavaScript, VBScript, etc. are interpreted and executed by
the web browser,

while server-side scripting languages such as PHP, ASP, Java, Python, Ruby, etc. runs on the web
server and the output sent back to the web browser in HTML format.
JavaScript Syntax
var x = 5;

var y = 10;

var sum = x + y;

document.write(sum); // Prints variable value


Case Sensitivity in JavaScript
● JavaScript is case-sensitive.
● This means that variables, language keywords, function names, and other identifiers
must always be typed with a consistent capitalization of letters.
● For example, the variable myVar must be typed myVar not MyVar or myvar.
● Similarly, the method name getElementById() must be typed with the exact case not
as getElementByID().

var myVar = "Hello World!" ;

console.log(myVar);

console.log(MyVar);

console.log(myvar);
JavaScript Comments

// This is my first JavaScript program

document.write("Hello World!");

/* This is my first program

in JavaScript */

document.write("Hello World!");
JavaScript Variables
Variables are used to store data, like string of text, numbers, etc.

The data or value stored in the variables can be set, updated, and retrieved whenever needed.

var varName = value;

var name = "Peter Parker";

var age = 21;

var isMarried = false;

// Declaring Variable

var userName;

// Assigning value

userName = "Clark Kent";


Declaring Multiple Variables at Once
// Declaring multiple Variables

var name = "Peter Parker", age = 21, isMarried = false;

/* Longer declarations can be written to span

multiple lines to improve the readability */

var name = "Peter Parker",

age = 21,

isMarried = false;
The let and const Keywords
The const keyword works exactly the same as let, except that variables declared using const keyword cannot
be reassigned later in the code.

// Declaring variables

let name = "Harry Potter";

let age = 11;

let isStudent = true;

// Declaring constant

const PI = 3.14;

console.log(PI); // 3.14

// Trying to reassign

PI = 10; // error
Unlike var, which declare function-scoped variables,

both let and const keywords declare variables, scoped at block-level ({}).

Block scoping means that a new scope is created between a pair of curly brackets {}.
Naming Conventions for JavaScript Variables
● A variable name must start with a letter, underscore (_), or dollar sign ($).
● A variable name cannot start with a number.
● A variable name can only contain alpha-numeric characters (A-z, 0-9) and underscores.
● A variable name cannot contain spaces.
● A variable name cannot be a JavaScript keyword or a JavaScript reserved word.
JavaScript Reserved Keywords

Reserved Keywords in ECMAScript 5

Reserved Keywords in ECMAScript 5


Reserved Keywords in ECMAScript 6 (ES6)
Future Reserved Keywords in Older Standards
JavaScript Global Variable

A JavaScript global variable is declared outside the function or declared with window object. It can be accessed from any
function.

1. <script>
2. var value=50;//global variable
3. function a(){
4. alert(value);
5. }
6. function b(){
7. alert(value);
8. }
9. </script>
Declaring JavaScript global variable within function

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

1. window.value=90;

Now it can be declared inside any function and can be accessed from any function. For example:

1. function m(){
2. window.value=100;//declaring global variable by window object
3. }
4. function n(){
5. alert(window.value);//accessing global variable from other function
6. }
Internals of global variable in JavaScript

When you declare a variable outside the function, it is added in the window object internally. You can access it through
window object also. For example:

1. var value=50;
2. function a(){
3. alert(window.value);//accessing global variable
4. }
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.
Creating Objects in JavaScript

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)
4.
1) JavaScript Object by object literal

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

1. 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.

1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </script>
2) By creating instance of Object

The syntax of creating object directly is given below:

1. var objectname=new Object();

Here, new keyword is used to create object.

Let’s see the example of creating object directly.

1. <script>
2. var emp=new Object();
3. emp.id=101;
4. emp.name="Ravi Malik";
5. emp.salary=50000;
6. document.write(emp.id+" "+emp.name+" "+emp.salary);
7. </script>
3) 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.

1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6. }
7. e=new emp(103,"Vimal Jaiswal",30000);
8.
9. document.write(e.id+" "+e.name+" "+e.salary);
10. </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:

1. 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.

1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br/>");
5. }
6. </script>
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:

1. var arrayname=new Array();

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

Let's see the example of creating array directly.

1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7.
8. for (i=0;i<emp.length;i++){
9. document.write(emp[i] + "<br>");
10. }
11. </script>
3) JavaScript array constructor (new keyword)

Here, you need to create instance of array by passing arguments in constructor so that we don't have to provide value
explicitly.

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

1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br>");
5. }
6. </script>
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:

1. var stringname="string value";

Let's see the simple example of creating string literal.

1. <script>
2. var str="This is string literal";
3. document.write(str);
4. </script>
2) By string object (using new keyword)

The syntax of creating string object using new keyword is given below:

1. var stringname=new String("string literal");

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

Let's see the example of creating string in JavaScript by new keyword.

1. <script>
2. var stringname=new String("hello javascript string");
3. document.write(stringname);
4. </script>
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.

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)
JavaScript Date Example

1. Current Date and Time: <span id="txt"></span>


2. <script>
3. var today=new Date();
4. document.getElementById('txt').innerHTML=today;
5. </script>
1. <script>
2. var date=new Date();
3. var day=date.getDate();
4. var month=date.getMonth()+1;
5. var year=date.getFullYear();
6. document.write("<br>Date is: "+day+"/"+month+"/"+year);
7. </script>
JavaScript Current Time Example

1. Current Time: <span id="txt"></span>


2. <script>
3. var today=new Date();
4. var h=today.getHours();
5. var m=today.getMinutes();
6. var s=today.getSeconds();
7. document.getElementById('txt').innerHTML=h+":"+m+":"+s;
8. </script>
JavaScript Digital Clock Example

1. Current Time: <span id="txt"></span> 1. document.getElementById('txt').innerHTML


2. <script> =h+":"+m+":"+s;
3. window.onload=function(){getTime();} 2. setTimeout(function(){getTime()},1000);
4. function getTime(){ 3. }
5. var today=new Date(); 4. //setInterval("getTime()",1000);//another
6. var h=today.getHours(); way
7. var m=today.getMinutes(); 5. function checkTime(i){
8. var s=today.getSeconds(); 6. if (i<10){
9. // add a zero in front of numbers<10 7. i="0" + i;
10. m=checkTime(m); 8. }
11. s=checkTime(s); 9. return i;
10. }
11. </script>
JavaScript Math

Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given number.

1. Square Root of 17 is: <span id="p1"></span>


2. <script>
3. document.getElementById('p1').innerHTML=Math.sqrt(17);
4. </script>
JavaScript Number Methods
JavaScript Number isFinite() method example

1. <script>
2. var x=0;
3. var y=1;
4. var z=-1;
5. document.writeln(Number.isFinite(x));
6. document.writeln(Number.isFinite(y));
7. document.writeln(Number.isFinite(z));
8. </script>
Browser Object Model

The Browser Object Model (BOM) is used to interact with the browser.

1. window.alert("hello javatpoint");

is same as:

1. alert("hello javatpoint");
Window Object

The window object represents a window in browser. An object of window is created automatically by the browser.
Methods of window object
Example of alert() in javascript

1. <script type="text/javascript">
2. function msg(){
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>
Example of confirm() in javascript

1. <script type="text/javascript">
2. function msg(){
3. var v= confirm("Are u sure?");
4. if(v==true){
5. alert("ok");
6. }
7. else{
8. alert("cancel");
9. }
10.
11. }
12. </script>
13.
14. <input type="button" value="delete record" onclick="msg()"/>
Example of prompt() in javascript

1. <script type="text/javascript">
2. function msg(){
3. var v= prompt("Who are you?");
4. alert("I am "+v);
5.
6. }
7. </script>
8.
9. <input type="button" value="click" onclick="msg()"/>
Example of open() in javascript

1. <script type="text/javascript">
2. function msg(){
3. open("http://www.google.com");
4. }
5. </script>
6. <input type="button" value="google" onclick="msg()"/>
Example of setTimeout() in javascript

1. <script type="text/javascript">
2. function msg(){
3. setTimeout(
4. function(){
5. alert("Welcome to Javatpoint after 2 seconds")
6. },2000);
7.
8. }
9. </script>
10.
11. <input type="button" value="click" onclick="msg()"/>
JavaScript History Object

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.

1. window.history

Or,

1. history
Example of history object

1. history.back();//for previous page


2. history.forward();//for next page
3. history.go(2);//for next 2nd page
4. history.go(-2);//for previous 2nd page
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.

1. window.navigator

Or,

1. navigator
Property of JavaScript navigator object
Methods of JavaScript navigator object
Example of navigator object

1. <script>
2. document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);
3. document.writeln("<br/>navigator.appName: "+navigator.appName);
4. document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);
5. document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);
6. document.writeln("<br/>navigator.language: "+navigator.language);
7. document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);
8. document.writeln("<br/>navigator.platform: "+navigator.platform);
9. document.writeln("<br/>navigator.onLine: "+navigator.onLine);
10. </script>
JavaScript Screen Object

The JavaScript screen object holds information of browser screen. It can be used to display screen width, height,
colorDepth, pixelDepth etc.

1. window.screen

Or,

1. screen
Property of JavaScript Screen Object
Example of JavaScript Screen Object

1. <script>
2. document.writeln("<br/>screen.width: "+screen.width);
3. document.writeln("<br/>screen.height: "+screen.height);
4. document.writeln("<br/>screen.availWidth: "+screen.availWidth);
5. document.writeln("<br/>screen.availHeight: "+screen.availHeight);
6. document.writeln("<br/>screen.colorDepth: "+screen.colorDepth);
7. document.writeln("<br/>screen.pixelDepth: "+screen.pixelDepth);
8. </script>
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
Properties of document object
Methods of document object
Accessing field value by document object

document.form1.name.value to get the value of name field.

Here, document is the root element that represents the html document.

form1 is the name of the form.

name is the attribute name of the input text.

value is the property, that returns the value of the input text.
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>
Javascript - document.getElementById() method

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>
Javascript - 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.
12. <input type="button" onclick="totalelements()" value="Total Genders">
13. </form>
Javascript - document.getElementsByTagName() method

1. <script type="text/javascript">
2. function countpara(){
3. var totalpara=document.getElementsByTagName("p");
4. alert("total p tags are: "+totalpara.length);
5.
6. }
7. </script>
8. <p>This is a pragraph</p>
9. <p>Here we are going to count total number of paragraphs by getElementByTagName() method.</p>
10. <p>Let's see the simple example</p>
11. <button onclick="countpara()">count paragraph</button>
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.
Example of innerHTML property

1. <script type="text/javascript" >


2. function showcommentform() {
3. var data="Name:<input type='text' name='name'><br>Comment:<br><textarea rows='5' cols='80'></textarea>
4. <br><input type='submit' value='Post Comment'>";
5. document.getElementById('mylocation').innerHTML=data;
6. }
7. </script>
8. <form name="myForm">
9. <input type="button" value="comment" onclick="showcommentform()">
10. <div id="mylocation"></div>
11. </form>
Show/Hide Comment Form Example using innerHTML
1. <!DOCTYPE html> 1. if(flag){
2. <html> 2. document.getElementById("mylocation").innerHTML
3. <head> =cform;
4. <title>First JS</title> 3. flag=false;
5. <script> 4. }else{
6. var flag=true; 5. document.getElementById("mylocation").innerHTML
7. function commentform(){ ="";
8. var cform="<form action='Comment'>Enter 6. flag=true;
Name:<br><input type='text' name='name'/><br/> 7. }
9. Enter Email:<br><input type='email' 8. }
name='email'/><br>Enter Comment:<br/> 9. </script>
10. <textarea rows='5' cols='70'></textarea><br><input 10. </head>
type='submit' value='Post Comment'/></form>"; 11. <body>
12. <button
onclick="commentform()">Comment</button>
13. <div id="mylocation"></div>
14. </body>
15. </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.
Javascript innerText Example
1. <script type="text/javascript" >
2. function validate() {
3. var msg;
4. if(document.myForm.userPass.value.length>5){
5. msg="good";
6. }
7. else{
8. msg="poor";
9. }
10. document.getElementById('mylocation').innerText=msg;
11. }
12.
13. </script>
14. <form name="myForm">
15. <input type="password" value="" name="userPass" onkeyup="validate()">
16. Strength:<span id="mylocation">no strength</span>
17. </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 Form Validation Example
1. <script> 1. </script>
2. function validateform(){ 2. <body>
3. var name=document.myform.name.value; 3. <form name="myform" method="post"
4. var action="abc.jsp" onsubmit="return
password=document.myform.password.val validateform()" >
ue; 4. Name: <input type="text"
5. name="name"><br/>
6. if (name==null || name==""){ 5. Password: <input type="password"
7. alert("Name can't be blank"); name="password"><br/>
8. return false; 6. <input type="submit" value="register">
9. }else if(password.length<6){ 7. </form>
10. alert("Password must be at least 6
characters long.");
11. return false;
12. }
13. }
JavaScript Retype Password Validation
1. <script type="text/javascript"> 1. }
2. function matchpass(){ 2. }
3. var 3. </script>
firstpassword=document.f1.password.value 4.
; 5. <form name="f1" action="register.jsp"
4. var onsubmit="return matchpass()">
secondpassword=document.f1.password2. 6. Password:<input type="password"
value; name="password" /><br/>
5. 7. Re-enter Password:<input type="password"
6. if(firstpassword==secondpassword){ name="password2"/><br/>
7. return true; 8. <input type="submit">
8. } 9. </form>
9. else{
10. alert("password must be same!");
11. return false;
JavaScript Number Validation
1. <script>
2. function validate(){
3. var num=document.myform.num.value;
4. if (isNaN(num)){
5. document.getElementById("numloc").innerHTML="Enter Numeric value only";
6. return false;
7. }else{
8. return true;
9. }
10. }
11. </script>
12. <form name="myform" onsubmit="return validate()" >
13. Number: <input type="text" name="num"><span id="numloc"></span><br/>
14. <input type="submit" value="submit">
15. </form>
JavaScript validation with image
1. <script> 1. status=true;
2. function validate(){ 2. }
3. var name=document.f1.name.value;
4. var 1. if(password.length<6){

password=document.f1.password.value; 2. document.getElementById("passwordloc").i

5. var status=false; nnerHTML=

6. 3. " <img src='unchecked.gif'/> Password

7. if(name.length<1){ must be at least 6 char long";

8. document.getElementById("nameloc").inner 4. status=false;

HTML= 5. }else{

9. " <img src='unchecked.gif'/> Please enter 6. document.getElementById("passwordloc").i

your name"; nnerHTML=" <img src='checked.gif'/>";

10. status=false; 7. }

11. }else{ 8. return status;

12. document.getElementById("nameloc").inner
HTML=" <img src='checked.gif'/>";
1. }
2. </script>
3.
4. <form name="f1" action="#"
onsubmit="return validate()">
5. <table>
6. <tr><td>Enter Name:</td><td><input
type="text" name="name"/>
7. <span id="nameloc"></span></td></tr>
8. <tr><td>Enter Password:</td><td><input
type="password" name="password"/>
9. <span id="passwordloc"></span></td></tr>
10. <tr><td colspan="2"><input type="submit"
value="register"/></td></tr>
11. </table>
12. </form>
JavaScript email validation
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 email validation
1. <script> 1. </script>
2. function validateemail() 2. <body>
3. { 3. <form name="myform" method="post"
4. var x=document.myform.email.value; action="#" onsubmit="return
5. var atposition=x.indexOf("@"); validateemail();">
6. var dotposition=x.lastIndexOf("."); 4. Email: <input type="text"
7. if (atposition<1 || dotposition<atposition+2 || name="email"><br/>
dotposition+2>=x.length){ 5.
8. alert("Please enter a valid e-mail address 6. <input type="submit" value="register">
\n atpostion:"+atposition+"\n 7. </form>
dotposition:"+dotposition);
9. return false;
10. }
11. }

You might also like