SlideShare a Scribd company logo
JavaScript
UNIT-V
Javascript
▪ Introduction to JavaScript
▪ JavaScript Language
▪ Declaring Variables
▪ Scope of Variable
▪ Functions
▪ Event handlers
▪ Document Object Model
▪ Form Validation
Introduction to Javascript
▪ Javascript is a dynamic client side scripting language.
▪ JavaScript is an object-based scripting language which is lightweight and cross-
platform.
▪ It is an interpreted programming language.
▪ JavaScript was designed to add interactivity to HTML pages.
▪ It is usually embedded directly into HTML pages.
▪ JavaScript was first known as LiveScript, but Netscape changed its name to
JavaScript.
JavaScript - Syntax
▪ JavaScript can be implemented using JavaScript statements that are
placed within the <script>... </script>.
▪ The <script> tag alerts the browser program to start interpreting all the
text between these tags as a script.
▪ syntax:<script ...> JavaScript code </script>
▪ The script tag takes two important attributes 1.language 2.type
▪ Language − This attribute specifies what scripting language you are using.
Typically, its value will be javascript.
▪ Type − text/javascript is the content type that provides information to
the browser about the data
▪ <script language = "javascript" type = "text/javascript"> JavaScript code </
script>
▪ Let’s create the first JavaScript example.
▪ The function document.write() which writes a string into our HTML document
<html>
<body>
<script language=“javascript” type="text/javascript">
document.write("JavaScript is a simple language for learners");
</script>
</body>
</html>
JavaScript Output
For output, we can use document.write() or an window.alert() (alert box).
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body> </html>
JavaScript Variable
▪ A JavaScript variable is simply a name of storage location.
▪ Variables are declared with the var keyword as follows.
<html>
<body>
<script type="text/javascript">
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
JavaScript Variable Scope
▪ The scope of a variable is the region of your program in which it is defined.
▪ JavaScript variables have only two scopes.
▪ Global Variables − A global variable has global scope which means it can be defined anywhere
in your JavaScript code.
▪ Local Variables − A local variable will be visible only within a function where it is defined.
Function parameters are always local to that function.
▪ JavaScript local variable is declared inside block or function.
▪ It is accessible within the function or block only.
<html> <body>
<script type=“text/javascript”>
function abc() { var x=10;//local variable
}
abc();
</script>
<body> <html>
JavaScript 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.
<html>
<body>
<script type=“text/javascript”>
var data=200;//gloabal variable
function a(){ document.writeln(data); }
function b(){ document.writeln(data); }
a();//calling JavaScript function
b();
</script>
</body>
</html>
Declaring JavaScript global variable within function
To declare JavaScript global variables inside function, you need to use window object.
For example: window.value=90;
<html>
<body>
<script type=“text/javascript”>
function m() { window.value=100;//declaring global variable by window object }
function n() { alert(window.value);//accessing global variable from other function }
m();
n();
</script>
</body>
</html>
When you declare a variable outside the function, it is added in the window object internally. You can access it through
window object also.
var value=50;
function a(){ alert(window.value);//accessing global variable
}
Data Types
▪ Javascript provides 2 primitive types
1. Primitive types 2. non-Primitive types
Primitive types
▪ 1. String 2.Number 3.Boolean 4. Undefined 5.Null
Data Type Description
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 a variable has not been assigned a value, or
not declared at al
Null represents null i.e. no value at all
non-primitive data types
The non-primitive data types are as follows:
Data Type Description
Object represents instance through which we can access
members
Array represents group of similar values
RegExp represents regular expression
Functions
Javascript uses a special keyword called function to define the functions
Unlike other languages no need to specify the return type or parameter types.
<html>
<body>
<script>
function getInfo(){
return "hello java Script";
}
document.write(getInfo());
</script>
</body>
</html>
1. <html>
2. <head>
3. <title>JavaScript simple example</title>
4. </head>
5. <body>
6. <script type="text/javascript">
7. function total(a,b)
8. { result=a+b; return result; }
9. </script>
10. <h1> MY JavaScript PROGRAM </h1>
11. <script type="text/javascript">
12. document.write("<h1>Sum="+total(10,30)+"</h1>");
13. </script>
14. </body>
15. </html>
Parameter Function
<html>
<head>
<title>JavaScript simple example</title>
</head>
<body>
<script type="text/javascript">
function total(a,b)
{ result=a+b; return result; }
</script>
<h1> MY JavaScript PROGRAM </h1>
<script type="text/javascript">
document.write("<h1>Sum="+total(10,30)+"</h1>");
</script>
</body>
</html>
Javascript Objects
▪ A javaScript object is an entity having state (properties represented as data members)
and behavior (method). For example: car, pen, bike, chair, glass, keyboard, monitor etc.
▪ JavaScript is an object-based language.
▪ Everything is an object in JavaScript.
Javascript Objects
▪ The root object in Javascript is Object.
▪ All user-defined objects and built-in objects are descendants of an object called Object.
Standard Objects
▪ Javascript consists several standard objects like
1. Object 2.Arrays 3. String 4.Math 5. Date 6. Boolean 7.Number8.Regular expression
Object
▪ There are 2 ways to create objects.
▪ They are: 1.By array literal
2.By creating instance of object directly (using new keyword)
▪ JavaScript Object by object literal:
The syntax: object={property1:value1,property2:value2.....propertyN:valueN
▪ As you can see, property and value is separated by : (colon).
• Example:
<html> <body>
<script type=“text/javascript”>
emp={id:102,name:"Shyam Kumar",salary:40000
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body> </html>
• By creating instance of Object
syntax: var objectname=new Object(); (Here, new keyword is used to create object)
• Example:
<html> <body>
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body> </html>
Array
JavaScript array is an object that represents a collection of similar type of elements.
There are 2 ways to construct array in JavaScript 1.By array literal 2.By creating instance of Array directly (using new
keyword)
JavaScript array literal
Syntax : var array_name = [item1, item2, ...];
Example: var cars = ["Saab", "Volvo", "BMW"];
<html> <body>
<h2>JavaScript Arrays</h2>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.write(cars);
</script> </body> </html>
JavaScript Array directly (new keyword)
syntax: var arrayname=new Array();
Example: var cars = new Array("Saab", "Volvo", "BMW");
<html> <body> <h2>JavaScript Arrays</h2>
<script>
var cars = new Array("Saab", "Volvo", "BMW");
document.write(cars);
</script> </body> </html>
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)
By string literal
The string literal is created using double quotes.
Syntax:var stringname="string value";
<html> <body> <script type=“text/javascript”>
var str="This is string literal";
document.write(str);
</script> </body> </html>
By string object (using new keyword)
<html> <body>
<script type=“text/javascript”>
var stringname=new String("hello javascript string");
document.write(stringname);
</script> </body> </html>
JavaScript String Methods
concat() It provides a combination of two or more strings.
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.
toString() It provides a string representing the particular object.
Date Object
The Date object is a datatype built into the JavaScript language.
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.
we can create 4 variant of Date constructor to create date object.
Date()
Date(milliseconds)
Date(dateString)
Date(year, month, day, hours, minutes, seconds, milliseconds)
JavaScript Date Methods
getDate(): It returns the integer value between 1 and 31 that represents the day for the specified date on the
basis of local time.
getDay() It returns the integer value between 0 and 6 that represents the day of the week on the basis of
local time.
etHours() It returns the integer value between 0 and 23 that represents the hours on the basis of local time.
getMinutes() It returns the integer value between 0 and 59 that represents the minutes on the basis of local time.
getMonth() It returns the integer value between 0 and 11 that represents the month on the basis of local time.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript new Date()</h2>
<p>Using new Date(), creates a new date object with the current date and time:</p>
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
Window Object
▪ The window object represents a window in browser.
▪ An object of window is created automatically by the browser.
▪ The important methods of window object are as follows:
Method Description
alert() displays the alert box containing
message with ok button.
confirm() displays the confirm dialog box
containing message with ok and
cancel button.
prompt() displays a dialog box to get input
from the user.
Example of alert()
▪ It displays alert dialog box. It has message and ok button.
<script type="text/javascript">
function msg(){
alert("Hello Alert Box");
}
</script>
<input type="button" value="click" onclick="msg()"/>
DOM (Document Object Model)
The HTML DOM is a standard object model and programming interface for HTML.
In other words: The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.
In the DOM, all HTML elements are defined as objects.
HTML DOM methods are actions (methods) you can perform on HTML Elements (like
add or deleting an HTML element).
HTML DOM properties( are values (of HTML Elements) that you can get(set) or
change. (like changing the content of an HTML element).
Methods of document object
We can access and change the contents of document by its methods.
The important methods of document object are as follows:
Method Description
write("string") writes the given string on the doucment.
writeln("string") writes the given string on the doucment with
newline character at the end.
getElementById() returns the element having the given id value.
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.
Example
The following example changes the content (the innerHTML) of the <p> element
with id="demo":
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
The getElementById() Method: The most common way to access an HTML element is
to use the id of the element.
In the example above the getElementById method used id="demo" to find the element.
The innerHTML Property: The easiest way to get the content of an element is by using
the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML elements.
JavaScript - Events
▪ JavaScript's interaction with HTML is handled through events that occur when the user or
the browser manipulates a page.
▪ When the page loads, it is called an event. When the user clicks a button, that click too is
an event.
▪ The other events like pressing any key, closing a window, resizing a window, etc.
▪ Developers can use these events to execute JavaScript coded responses, which cause
buttons to close windows, messages to be displayed to users, data to be validated, and
virtually any other type of response imaginable.
▪ Events are a part of the Document Object Model (DOM) and every HTML element contains
a set of events which can trigger JavaScript Code.
HTML/DOM events for JavaScript
HTML or DOM events are widely used in JavaScript code.
JavaScript code is executed with HTML/DOM events.
Events Description
onclick occurs when element is clicked.
ondblclick occurs when element is double-clicked.
onfocus occurs when an element gets focus such as button, input, textarea etc.
onblur occurs when form looses the focus from an element.
onsubmit occurs when form is submitted.
onmouseover occurs when mouse is moved over an element.
onmouseout occurs when mouse is moved out from an element (after moved over).
onmousedown occurs when mouse button is pressed over an element.
onmouseup occurs when mouse is released from an element (after mouse is pressed).
onload occurs when document, object or frameset is loaded.
onunload occurs when body or frameset is unloaded.
onscroll occurs when document is scrolled.
onresized occurs when document is resized.
onreset occurs when form is reset.
onkeydown occurs when key is being pressed.
onkeypress occurs when user presses the key.
onkeyup occurs when key is released.
Onclick Event
<html>
<head>
<script type=“text/javascript”>
function sayHello() {
alert(“Hello World”) }
</script> </head>
<body>
<p> Click the following button and see result </p>
<form >
<input type=“button” onClick=“sayHello()” value=“Say Hello”/>
</form>
</body>
</html>
onsubmit Event
onsubmit is an event that occurs when you try to submit a form.
You can put your form validation against this event type.
Here we are calling a validate() function before submitting a form data to the webserver.
If validate() function returns true, the form will be submitted, otherwise it will not submit the data.
<html> <body>
<script>
function validate() {
name = document.forms[0].fname.value;
alert(name);
} </script>
<body>
<form onsubmit=“validate()" >
Enter your name: <input id="fname" type="text" >
<input type="submit">
</form> </body>
</html>
onmouseover and onmouseout
▪ These two event types will help you create nice effects with images or even with text as well.
▪ The onmouseover event triggers when you bring your mouse over any element
▪ the onmouseout triggers when you move your mouse out from that element.
<html>
<body>
<h1 onmouseover="style.color='red'" onmouseout="style.color=‘blue'">Mouse over this text</h1>
</body>
</html>
Focus Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
</script>
</body>
</html>
JavaScript Form Validation
▪ It is important to validate the form submitted by the user because it can have inappropriate values. So
validation is must.
▪ The JavaScript provides you the facility the validate the form on the client side so processing will be fast
than server-side validation. So, most of the web developers prefer JavaScript form validation.
▪ Through JavaScript, we can validate name, password, email, date, mobile number etc fields.
Javascript : Regular Expressions
• A regular expression is an object that describes a pattern of characters.
• Regular expressions are used to perform pattern-matching and "search-and-
replace" functions on text.
• Syntax: /pattern/modifiers;
• Example:var patt = /w3schools/I
• /w3schools/i is a regular expression.
• w3schools is a pattern (to be used in a search).
• i is a modifier (modifies the search to be case-insensitive).
▪ String.match() function searches for given pattern or string and it returns
it returns the matched string if it is true
it returns the null if the given string or pattern doesn’t found
Modifiers
Example:
var reg=/^the/i
var s="The King of 9 Planets";
document.write(s.match(reg));
Modifiers: Modifiers are used to perform case-insensitive and global searches
Modifier Description
g Perform a global match (find all matches rather than stopping after the first match)
I Perform case-insensitive matching
M Perform multiline matching
Regular Expressions : Meta Characters
Quantifier Description Example
^x Matches any string with x at the beginning of it Reg=/^the/
s1=“the king”
s2=“king is the”
s1.match(reg); ---- The
s2.match(reg);---- null
X$ Matches any string with x at the end of it Reg=/the$/
s1=“the king”
s2=“king is the”
s1.match(reg); ---- null
s2.match(reg);---- the
[ ] Finds the any character specified in the brackets [abc], [a-z], [0-9],[a-z A-Z]
Metacharacters:Metacharacters are characters with a special meaning:
Expression Description
[abc] Find any character between the brackets
[^abc] Find any character NOT between the brackets
[0-9] Find any character between the brackets (any digit)
[^0-9] Find any character NOT between the brackets (any non-digit)
(x|y) Find any of the alternatives specified
Metacharacter Description
. Find a single character, except newline or line terminator
w Find a word character
W Find a non-word character
d Find a digit
D Find a non-digit character
s Find a whitespace character
S Find a non-whitespace character
Regular Expressions : Quantifiers
Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n{X} Matches any string that contains a sequence of X n's
n{X,Y} Matches any string that contains a sequence of X to Y n's
n{X,} Matches any string that contains a sequence of at least X n's
n$ Matches any string with n at the end of it
^n Matches any string with n at the beginning of it
?=n Matches any string that is followed by a specific string n
?!n Matches any string that is not followed by a specific string n
Important Regular Expressions
▪ Email :
reg=/^([a-z0-9]+)@([a-z0-9]+).([a-z.]{2,6})$/
▪ Date :
reg=/^d{2}[/-]{1}d{2}[/-]{1}d{2,4}$/
▪ Phone :
reg=/^[789]d{9}$/
▪ User Name :
reg=/^[a-ZA-Z0-9_]{6,20}$/
Email : reg=/^([a-z0-9]+)@([a-z0-9]+).([a-z.]{2,6})$/
^x : Matches any string with x at the beginning of it
[ ]: Finds the any character specified in the brackets:- [abc], [a-z], [0-9],[a-z A-Z]
n+ : Matches any string that contains at least one n
. : Find a single character, except newline or line terminator
n{X,Y} : Matches any string that contains a sequence of X to Y n’s
n$ : Matches any string with n at the end of it
1. <html>
2. <head>
3. <title>Untitled Document</title>
4. <script type="text/javascript" >
5. function check()
6. {
7. reg=/^([a-z0-9]+)@([a-z0-9]+).([a-z.]{2,6})$/
8. s=document.getElementById("email").value;
9. if(s.match(reg)==null)
10. alert("please check the email id");
11. else
12. alert("email validation complete");
13. }
Output
Form Validation
Write Java script program to validate username, password,email & phone no
<html>
<head>
<title>Registration</title>
<script>
function uvalid()
{ uname.innerText= "enter the username"; }
function pvalid()
{
var v1=new RegExp("^[w]{6,}$");
var in1=document.f.login.value;
var elements="";
if(!(v1.test(in1)))
{ uname.innerText="username should contain 6 chars"; }
else { uname.innerText=""; }
pass.innerText="enter the password";
}
function evalid()
{
var v2=new RegExp("^[w]{6,}");
var in2=document.f.password.value;
if(!(v2.test(in2)))
pass.innerText="password should conatin atleast 6chars";
else
pass.innerText="";
emai.innerText="enter the email";
}
function phvalid()
{
var v3=new RegExp("^[w]+@[w]+.com$");
var in3=document.f.email.value;
if(!(v3.test(in3)))
emai.innerText="email should be in the form name@domain.com";
else
emai.innerText= "";
ph.innerText="enter the phonenumber";
}
function pnvalid()
{
var v4=new RegExp("^[d]{10}$");
var in4=document.f.phonenum.value;
if(!(v4.test(in4)))
ph.innerText="phone number should contain 10 digits";
else
ph.innerText=" ";
}
</script>
</head>
<body> <center>
<form name="f">
<table align="center">
<caption align="left"> REGISTRATION
<caption>
<tr>
<td>USERNAME :</td>
<td><input type="text" name="login"
onfocus="uvalid()"></td>
<td><p id="uname"> <p></td>
</tr> <tr>
<td>PASSWORD:</td>
<td><input type="password"
name="password"
onfocus="pvalid()"></td>
<td><p id="pass"> </p></td>
</tr> <tr>
<td>E-mail id:</td>
<td><input type="text" name="email"
onfocus="evalid()"></td>
<td><p id="emai"></p></td>
</tr> <tr>
<td>Phone Number:</td>
<td><input type="text"
name="phonenum"
onfocus="phvalid()"
onblur="pnvalid()"></td>
<td><p id="ph"> </p></td>
</tr> <tr>
<td><input type="button"
value="submit"></td>
<td><input type="reset"
value="reset"></td>
</tr> </table>
</form> </body> </html>
Previous Year Questions
How is Client side Java Script different from Server side Java Script? [3] Dec 2018
What is JavaScript? What are the features of JavaScript? [3] Dec2018
Explain the scope of variable. [3] 2018
What is the difference between undefined and not defined in JavaScript? [3 ] 2018
Write about the following with reference to Java Script with an example:
Explain how to write functions in Java Script? [5] Dec 2017
a) Functions b) Form Validation [5+5] May 2017
Explain how to write functions in Java Script? [5] Dec 2017
How parameters are passed to functions in java script? Explain [5] 2019
Explain Document Object Model with suitable examples and code. [5] 2016
Explain the advantages of DOM *? [2] 2016
Explain about object, methods and events in Java Scripts. [5] 2016, May 2019
Define object, Property, Method and Event in java script? Give examples.[5] 2019
What is the date object in java script [2] Dec2017
What is an ‘event’? How are events handled in JavaScript? [3]
Write a short note on Event handlers in JavaScript. [5] 2016
Discuss the event handlers in JavaScript. [5] 2018
Discuss the keyboard events in java script with examples [5] Dec2017
Explain the process of event handling in java script with suitable examples.[5] 2019
Write a java script for sorting the elements of an array using function [5] Dec2017
Write a java script to change text color of HTML elements. [5] May 2019
Write a JavaScript to display whether given number is a prime or not. [7]2018
How does one access cookie in a java script? [3] 2016,[3] 2017, [2]2019
Give a note on this keyword in JavaScript. [2] 2018
How the keyword „new‟ is used to create objects in java script? [3]
What is the functioning of the java script keyword „this‟ and „dot‟ operator? Explain. [5] May 2019
Describe about form validation concept in JavaScript. Explain with an example program. [10] 2018
With an example program, explain form validation concept in JavaScript. [5] Nov2016
Write a java script to validate a form consisting of a hall ticket number as username and mobile number as
password. Also navigate to another web page after validation. [5] May 2019
Give a brief note on built-in objects in javascript with example Dec2020
How does one access cookie in a java script?
Java script can create, read and delete cookies with the document.cookie property
Write a JavaScript to display whether given number is a prime or not. Dec 2019
<html>
<body>
<script type="text/javascript">
var n=window.prompt("enter the number ", 7);
var i, flag = true;
for(i = 2; i <= n - 1; i++)
if (n % i == 0) {
flag = false;
break;
}
// Check and display alert message
if (flag == true)
alert(n + " is prime");
else
alert(n + " is not prime");
</script>
</body> </html>
J
Write a javascript to change text color of html elements? May 2019
<!DOCTYPE html>
<html>
<body>
<h2 id="myH2">This is an example h2</h2>
<p id="myP">This is an example paragraph.</p>
<br>
<script>
document.getElementById("myH2").style.color = "#ff0000";
document.getElementById("myP").style.color = "magenta";
</script>
</body>
</html>

More Related Content

Similar to Javascript

Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoftch samaram
 
Java script
Java scriptJava script
Java script
Jay Patel
 
wp-UNIT_III.pptx
wp-UNIT_III.pptxwp-UNIT_III.pptx
wp-UNIT_III.pptx
GANDHAMKUMAR2
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Marlon Jamera
 
js.pptx
js.pptxjs.pptx
js.pptx
SuhaibKhan62
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
08. session 08 intoduction to javascript
08. session 08   intoduction to javascript08. session 08   intoduction to javascript
08. session 08 intoduction to javascriptPhúc Đỗ
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
Doeun KOCH
 
Client sidescripting javascript
Client sidescripting javascriptClient sidescripting javascript
Client sidescripting javascript
Selvin Josy Bai Somu
 
JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
rashmiisrani1
 
Javascript analysis
Javascript analysisJavascript analysis
Javascript analysis
Uchitha Bandara
 
Java script
Java scriptJava script
Java script
Rajkiran Mummadi
 
Java script
 Java script Java script
Java scriptbosybosy
 
Java script
Java scriptJava script
Java script
Sukrit Gupta
 
Java script
Java scriptJava script
Java script
Shyam Khant
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJamshid Hashimi
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
Priya Goyal
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 

Similar to Javascript (20)

Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
 
Java script
Java scriptJava script
Java script
 
wp-UNIT_III.pptx
wp-UNIT_III.pptxwp-UNIT_III.pptx
wp-UNIT_III.pptx
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
js.pptx
js.pptxjs.pptx
js.pptx
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScript
 
08. session 08 intoduction to javascript
08. session 08   intoduction to javascript08. session 08   intoduction to javascript
08. session 08 intoduction to javascript
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
 
Java script
Java scriptJava script
Java script
 
Client sidescripting javascript
Client sidescripting javascriptClient sidescripting javascript
Client sidescripting javascript
 
JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
 
Javascript analysis
Javascript analysisJavascript analysis
Javascript analysis
 
Java script
Java scriptJava script
Java script
 
Java script
 Java script Java script
Java script
 
Java script
Java scriptJava script
Java script
 
chap04.ppt
chap04.pptchap04.ppt
chap04.ppt
 
Java script
Java scriptJava script
Java script
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 

Recently uploaded

Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 

Recently uploaded (20)

Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 

Javascript

  • 2. Javascript ▪ Introduction to JavaScript ▪ JavaScript Language ▪ Declaring Variables ▪ Scope of Variable ▪ Functions ▪ Event handlers ▪ Document Object Model ▪ Form Validation
  • 3. Introduction to Javascript ▪ Javascript is a dynamic client side scripting language. ▪ JavaScript is an object-based scripting language which is lightweight and cross- platform. ▪ It is an interpreted programming language. ▪ JavaScript was designed to add interactivity to HTML pages. ▪ It is usually embedded directly into HTML pages. ▪ JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript.
  • 4. JavaScript - Syntax ▪ JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script>. ▪ The <script> tag alerts the browser program to start interpreting all the text between these tags as a script. ▪ syntax:<script ...> JavaScript code </script> ▪ The script tag takes two important attributes 1.language 2.type ▪ Language − This attribute specifies what scripting language you are using. Typically, its value will be javascript. ▪ Type − text/javascript is the content type that provides information to the browser about the data ▪ <script language = "javascript" type = "text/javascript"> JavaScript code </ script>
  • 5. ▪ Let’s create the first JavaScript example. ▪ The function document.write() which writes a string into our HTML document <html> <body> <script language=“javascript” type="text/javascript"> document.write("JavaScript is a simple language for learners"); </script> </body> </html>
  • 6. JavaScript Output For output, we can use document.write() or an window.alert() (alert box). <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> document.write(5 + 6); </script> </body> </html> <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> window.alert(5 + 6); </script> </body> </html>
  • 7. JavaScript Variable ▪ A JavaScript variable is simply a name of storage location. ▪ Variables are declared with the var keyword as follows. <html> <body> <script type="text/javascript"> var x = 10; var y = 20; var z=x+y; document.write(z); </script> </body> </html>
  • 8. JavaScript Variable Scope ▪ The scope of a variable is the region of your program in which it is defined. ▪ JavaScript variables have only two scopes. ▪ Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code. ▪ Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function. ▪ JavaScript local variable is declared inside block or function. ▪ It is accessible within the function or block only. <html> <body> <script type=“text/javascript”> function abc() { var x=10;//local variable } abc(); </script> <body> <html>
  • 9. JavaScript 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. <html> <body> <script type=“text/javascript”> var data=200;//gloabal variable function a(){ document.writeln(data); } function b(){ document.writeln(data); } a();//calling JavaScript function b(); </script> </body> </html>
  • 10. Declaring JavaScript global variable within function To declare JavaScript global variables inside function, you need to use window object. For example: window.value=90; <html> <body> <script type=“text/javascript”> function m() { window.value=100;//declaring global variable by window object } function n() { alert(window.value);//accessing global variable from other function } m(); n(); </script> </body> </html> When you declare a variable outside the function, it is added in the window object internally. You can access it through window object also. var value=50; function a(){ alert(window.value);//accessing global variable }
  • 11. Data Types ▪ Javascript provides 2 primitive types 1. Primitive types 2. non-Primitive types Primitive types ▪ 1. String 2.Number 3.Boolean 4. Undefined 5.Null Data Type Description 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 a variable has not been assigned a value, or not declared at al Null represents null i.e. no value at all
  • 12. non-primitive data types The non-primitive data types are as follows: Data Type Description Object represents instance through which we can access members Array represents group of similar values RegExp represents regular expression
  • 13. Functions Javascript uses a special keyword called function to define the functions Unlike other languages no need to specify the return type or parameter types. <html> <body> <script> function getInfo(){ return "hello java Script"; } document.write(getInfo()); </script> </body> </html>
  • 14. 1. <html> 2. <head> 3. <title>JavaScript simple example</title> 4. </head> 5. <body> 6. <script type="text/javascript"> 7. function total(a,b) 8. { result=a+b; return result; } 9. </script> 10. <h1> MY JavaScript PROGRAM </h1> 11. <script type="text/javascript"> 12. document.write("<h1>Sum="+total(10,30)+"</h1>"); 13. </script> 14. </body> 15. </html>
  • 15. Parameter Function <html> <head> <title>JavaScript simple example</title> </head> <body> <script type="text/javascript"> function total(a,b) { result=a+b; return result; } </script> <h1> MY JavaScript PROGRAM </h1> <script type="text/javascript"> document.write("<h1>Sum="+total(10,30)+"</h1>"); </script> </body> </html>
  • 16. Javascript Objects ▪ A javaScript object is an entity having state (properties represented as data members) and behavior (method). For example: car, pen, bike, chair, glass, keyboard, monitor etc. ▪ JavaScript is an object-based language. ▪ Everything is an object in JavaScript.
  • 17. Javascript Objects ▪ The root object in Javascript is Object. ▪ All user-defined objects and built-in objects are descendants of an object called Object. Standard Objects ▪ Javascript consists several standard objects like 1. Object 2.Arrays 3. String 4.Math 5. Date 6. Boolean 7.Number8.Regular expression Object ▪ There are 2 ways to create objects. ▪ They are: 1.By array literal 2.By creating instance of object directly (using new keyword) ▪ JavaScript Object by object literal: The syntax: object={property1:value1,property2:value2.....propertyN:valueN ▪ As you can see, property and value is separated by : (colon).
  • 18. • Example: <html> <body> <script type=“text/javascript”> emp={id:102,name:"Shyam Kumar",salary:40000 document.write(emp.id+" "+emp.name+" "+emp.salary); </script> </body> </html> • By creating instance of Object syntax: var objectname=new Object(); (Here, new keyword is used to create object) • Example: <html> <body> <script> var emp=new Object(); emp.id=101; emp.name="Ravi Malik"; emp.salary=50000; document.write(emp.id+" "+emp.name+" "+emp.salary); </script> </body> </html>
  • 19. Array JavaScript array is an object that represents a collection of similar type of elements. There are 2 ways to construct array in JavaScript 1.By array literal 2.By creating instance of Array directly (using new keyword) JavaScript array literal Syntax : var array_name = [item1, item2, ...]; Example: var cars = ["Saab", "Volvo", "BMW"]; <html> <body> <h2>JavaScript Arrays</h2> <script> var cars = ["Saab", "Volvo", "BMW"]; document.write(cars); </script> </body> </html> JavaScript Array directly (new keyword) syntax: var arrayname=new Array(); Example: var cars = new Array("Saab", "Volvo", "BMW"); <html> <body> <h2>JavaScript Arrays</h2> <script> var cars = new Array("Saab", "Volvo", "BMW"); document.write(cars); </script> </body> </html>
  • 20. 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) By string literal The string literal is created using double quotes. Syntax:var stringname="string value"; <html> <body> <script type=“text/javascript”> var str="This is string literal"; document.write(str); </script> </body> </html> By string object (using new keyword) <html> <body> <script type=“text/javascript”> var stringname=new String("hello javascript string"); document.write(stringname); </script> </body> </html>
  • 21. JavaScript String Methods concat() It provides a combination of two or more strings. 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. toString() It provides a string representing the particular object.
  • 22. Date Object The Date object is a datatype built into the JavaScript language. 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. we can create 4 variant of Date constructor to create date object. Date() Date(milliseconds) Date(dateString) Date(year, month, day, hours, minutes, seconds, milliseconds) JavaScript Date Methods getDate(): It returns the integer value between 1 and 31 that represents the day for the specified date on the basis of local time. getDay() It returns the integer value between 0 and 6 that represents the day of the week on the basis of local time. etHours() It returns the integer value between 0 and 23 that represents the hours on the basis of local time. getMinutes() It returns the integer value between 0 and 59 that represents the minutes on the basis of local time. getMonth() It returns the integer value between 0 and 11 that represents the month on the basis of local time.
  • 23. <!DOCTYPE html> <html> <body> <h2>JavaScript new Date()</h2> <p>Using new Date(), creates a new date object with the current date and time:</p> <p id="demo"></p> <script> const d = new Date(); document.getElementById("demo").innerHTML = d; </script> </body> </html>
  • 24. Window Object ▪ The window object represents a window in browser. ▪ An object of window is created automatically by the browser. ▪ The important methods of window object are as follows: Method Description alert() displays the alert box containing message with ok button. confirm() displays the confirm dialog box containing message with ok and cancel button. prompt() displays a dialog box to get input from the user.
  • 25. Example of alert() ▪ It displays alert dialog box. It has message and ok button. <script type="text/javascript"> function msg(){ alert("Hello Alert Box"); } </script> <input type="button" value="click" onclick="msg()"/>
  • 26. DOM (Document Object Model) The HTML DOM is a standard object model and programming interface for HTML. In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements. In the DOM, all HTML elements are defined as objects. HTML DOM methods are actions (methods) you can perform on HTML Elements (like add or deleting an HTML element). HTML DOM properties( are values (of HTML Elements) that you can get(set) or change. (like changing the content of an HTML element).
  • 27. Methods of document object We can access and change the contents of document by its methods. The important methods of document object are as follows: Method Description write("string") writes the given string on the doucment. writeln("string") writes the given string on the doucment with newline character at the end. getElementById() returns the element having the given id value. 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.
  • 28. Example The following example changes the content (the innerHTML) of the <p> element with id="demo": <html> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Hello World!"; </script> </body> </html> The getElementById() Method: The most common way to access an HTML element is to use the id of the element. In the example above the getElementById method used id="demo" to find the element. The innerHTML Property: The easiest way to get the content of an element is by using the innerHTML property. The innerHTML property is useful for getting or replacing the content of HTML elements.
  • 29. JavaScript - Events ▪ JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page. ▪ When the page loads, it is called an event. When the user clicks a button, that click too is an event. ▪ The other events like pressing any key, closing a window, resizing a window, etc. ▪ Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable. ▪ Events are a part of the Document Object Model (DOM) and every HTML element contains a set of events which can trigger JavaScript Code.
  • 30. HTML/DOM events for JavaScript HTML or DOM events are widely used in JavaScript code. JavaScript code is executed with HTML/DOM events. Events Description onclick occurs when element is clicked. ondblclick occurs when element is double-clicked. onfocus occurs when an element gets focus such as button, input, textarea etc. onblur occurs when form looses the focus from an element. onsubmit occurs when form is submitted. onmouseover occurs when mouse is moved over an element. onmouseout occurs when mouse is moved out from an element (after moved over). onmousedown occurs when mouse button is pressed over an element. onmouseup occurs when mouse is released from an element (after mouse is pressed). onload occurs when document, object or frameset is loaded. onunload occurs when body or frameset is unloaded. onscroll occurs when document is scrolled. onresized occurs when document is resized. onreset occurs when form is reset. onkeydown occurs when key is being pressed. onkeypress occurs when user presses the key. onkeyup occurs when key is released.
  • 31. Onclick Event <html> <head> <script type=“text/javascript”> function sayHello() { alert(“Hello World”) } </script> </head> <body> <p> Click the following button and see result </p> <form > <input type=“button” onClick=“sayHello()” value=“Say Hello”/> </form> </body> </html>
  • 32. onsubmit Event onsubmit is an event that occurs when you try to submit a form. You can put your form validation against this event type. Here we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data. <html> <body> <script> function validate() { name = document.forms[0].fname.value; alert(name); } </script> <body> <form onsubmit=“validate()" > Enter your name: <input id="fname" type="text" > <input type="submit"> </form> </body> </html>
  • 33. onmouseover and onmouseout ▪ These two event types will help you create nice effects with images or even with text as well. ▪ The onmouseover event triggers when you bring your mouse over any element ▪ the onmouseout triggers when you move your mouse out from that element. <html> <body> <h1 onmouseover="style.color='red'" onmouseout="style.color=‘blue'">Mouse over this text</h1> </body> </html>
  • 34. Focus Event <html> <head> Javascript Events</head> <body> <h2> Enter something here</h2> <input type="text" id="input1" onfocus="focusevent()"/> <script> function focusevent() { document.getElementById("input1").style.background=" aqua"; } </script> </body> </html>
  • 35. JavaScript Form Validation ▪ It is important to validate the form submitted by the user because it can have inappropriate values. So validation is must. ▪ The JavaScript provides you the facility the validate the form on the client side so processing will be fast than server-side validation. So, most of the web developers prefer JavaScript form validation. ▪ Through JavaScript, we can validate name, password, email, date, mobile number etc fields.
  • 36. Javascript : Regular Expressions • A regular expression is an object that describes a pattern of characters. • Regular expressions are used to perform pattern-matching and "search-and- replace" functions on text. • Syntax: /pattern/modifiers; • Example:var patt = /w3schools/I • /w3schools/i is a regular expression. • w3schools is a pattern (to be used in a search). • i is a modifier (modifies the search to be case-insensitive). ▪ String.match() function searches for given pattern or string and it returns it returns the matched string if it is true it returns the null if the given string or pattern doesn’t found
  • 37. Modifiers Example: var reg=/^the/i var s="The King of 9 Planets"; document.write(s.match(reg)); Modifiers: Modifiers are used to perform case-insensitive and global searches Modifier Description g Perform a global match (find all matches rather than stopping after the first match) I Perform case-insensitive matching M Perform multiline matching
  • 38. Regular Expressions : Meta Characters Quantifier Description Example ^x Matches any string with x at the beginning of it Reg=/^the/ s1=“the king” s2=“king is the” s1.match(reg); ---- The s2.match(reg);---- null X$ Matches any string with x at the end of it Reg=/the$/ s1=“the king” s2=“king is the” s1.match(reg); ---- null s2.match(reg);---- the [ ] Finds the any character specified in the brackets [abc], [a-z], [0-9],[a-z A-Z] Metacharacters:Metacharacters are characters with a special meaning:
  • 39. Expression Description [abc] Find any character between the brackets [^abc] Find any character NOT between the brackets [0-9] Find any character between the brackets (any digit) [^0-9] Find any character NOT between the brackets (any non-digit) (x|y) Find any of the alternatives specified Metacharacter Description . Find a single character, except newline or line terminator w Find a word character W Find a non-word character d Find a digit D Find a non-digit character s Find a whitespace character S Find a non-whitespace character
  • 40. Regular Expressions : Quantifiers Quantifier Description n+ Matches any string that contains at least one n n* Matches any string that contains zero or more occurrences of n n? Matches any string that contains zero or one occurrences of n n{X} Matches any string that contains a sequence of X n's n{X,Y} Matches any string that contains a sequence of X to Y n's n{X,} Matches any string that contains a sequence of at least X n's n$ Matches any string with n at the end of it ^n Matches any string with n at the beginning of it ?=n Matches any string that is followed by a specific string n ?!n Matches any string that is not followed by a specific string n
  • 41. Important Regular Expressions ▪ Email : reg=/^([a-z0-9]+)@([a-z0-9]+).([a-z.]{2,6})$/ ▪ Date : reg=/^d{2}[/-]{1}d{2}[/-]{1}d{2,4}$/ ▪ Phone : reg=/^[789]d{9}$/ ▪ User Name : reg=/^[a-ZA-Z0-9_]{6,20}$/
  • 42. Email : reg=/^([a-z0-9]+)@([a-z0-9]+).([a-z.]{2,6})$/ ^x : Matches any string with x at the beginning of it [ ]: Finds the any character specified in the brackets:- [abc], [a-z], [0-9],[a-z A-Z] n+ : Matches any string that contains at least one n . : Find a single character, except newline or line terminator n{X,Y} : Matches any string that contains a sequence of X to Y n’s n$ : Matches any string with n at the end of it
  • 43. 1. <html> 2. <head> 3. <title>Untitled Document</title> 4. <script type="text/javascript" > 5. function check() 6. { 7. reg=/^([a-z0-9]+)@([a-z0-9]+).([a-z.]{2,6})$/ 8. s=document.getElementById("email").value; 9. if(s.match(reg)==null) 10. alert("please check the email id"); 11. else 12. alert("email validation complete"); 13. }
  • 45. Form Validation Write Java script program to validate username, password,email & phone no <html> <head> <title>Registration</title> <script> function uvalid() { uname.innerText= "enter the username"; } function pvalid() { var v1=new RegExp("^[w]{6,}$"); var in1=document.f.login.value; var elements=""; if(!(v1.test(in1))) { uname.innerText="username should contain 6 chars"; } else { uname.innerText=""; } pass.innerText="enter the password"; }
  • 46. function evalid() { var v2=new RegExp("^[w]{6,}"); var in2=document.f.password.value; if(!(v2.test(in2))) pass.innerText="password should conatin atleast 6chars"; else pass.innerText=""; emai.innerText="enter the email"; } function phvalid() { var v3=new RegExp("^[w]+@[w]+.com$"); var in3=document.f.email.value; if(!(v3.test(in3))) emai.innerText="email should be in the form name@domain.com"; else emai.innerText= ""; ph.innerText="enter the phonenumber"; }
  • 47. function pnvalid() { var v4=new RegExp("^[d]{10}$"); var in4=document.f.phonenum.value; if(!(v4.test(in4))) ph.innerText="phone number should contain 10 digits"; else ph.innerText=" "; } </script> </head>
  • 48. <body> <center> <form name="f"> <table align="center"> <caption align="left"> REGISTRATION <caption> <tr> <td>USERNAME :</td> <td><input type="text" name="login" onfocus="uvalid()"></td> <td><p id="uname"> <p></td> </tr> <tr> <td>PASSWORD:</td> <td><input type="password" name="password" onfocus="pvalid()"></td> <td><p id="pass"> </p></td> </tr> <tr> <td>E-mail id:</td> <td><input type="text" name="email" onfocus="evalid()"></td> <td><p id="emai"></p></td> </tr> <tr> <td>Phone Number:</td> <td><input type="text" name="phonenum" onfocus="phvalid()" onblur="pnvalid()"></td> <td><p id="ph"> </p></td> </tr> <tr> <td><input type="button" value="submit"></td> <td><input type="reset" value="reset"></td> </tr> </table> </form> </body> </html>
  • 49. Previous Year Questions How is Client side Java Script different from Server side Java Script? [3] Dec 2018 What is JavaScript? What are the features of JavaScript? [3] Dec2018 Explain the scope of variable. [3] 2018 What is the difference between undefined and not defined in JavaScript? [3 ] 2018 Write about the following with reference to Java Script with an example: Explain how to write functions in Java Script? [5] Dec 2017 a) Functions b) Form Validation [5+5] May 2017 Explain how to write functions in Java Script? [5] Dec 2017 How parameters are passed to functions in java script? Explain [5] 2019 Explain Document Object Model with suitable examples and code. [5] 2016 Explain the advantages of DOM *? [2] 2016 Explain about object, methods and events in Java Scripts. [5] 2016, May 2019 Define object, Property, Method and Event in java script? Give examples.[5] 2019 What is the date object in java script [2] Dec2017 What is an ‘event’? How are events handled in JavaScript? [3] Write a short note on Event handlers in JavaScript. [5] 2016 Discuss the event handlers in JavaScript. [5] 2018 Discuss the keyboard events in java script with examples [5] Dec2017 Explain the process of event handling in java script with suitable examples.[5] 2019 Write a java script for sorting the elements of an array using function [5] Dec2017 Write a java script to change text color of HTML elements. [5] May 2019 Write a JavaScript to display whether given number is a prime or not. [7]2018 How does one access cookie in a java script? [3] 2016,[3] 2017, [2]2019 Give a note on this keyword in JavaScript. [2] 2018 How the keyword „new‟ is used to create objects in java script? [3] What is the functioning of the java script keyword „this‟ and „dot‟ operator? Explain. [5] May 2019
  • 50. Describe about form validation concept in JavaScript. Explain with an example program. [10] 2018 With an example program, explain form validation concept in JavaScript. [5] Nov2016 Write a java script to validate a form consisting of a hall ticket number as username and mobile number as password. Also navigate to another web page after validation. [5] May 2019 Give a brief note on built-in objects in javascript with example Dec2020 How does one access cookie in a java script? Java script can create, read and delete cookies with the document.cookie property Write a JavaScript to display whether given number is a prime or not. Dec 2019 <html> <body> <script type="text/javascript"> var n=window.prompt("enter the number ", 7); var i, flag = true; for(i = 2; i <= n - 1; i++) if (n % i == 0) { flag = false; break; } // Check and display alert message if (flag == true) alert(n + " is prime"); else alert(n + " is not prime"); </script> </body> </html> J
  • 51. Write a javascript to change text color of html elements? May 2019 <!DOCTYPE html> <html> <body> <h2 id="myH2">This is an example h2</h2> <p id="myP">This is an example paragraph.</p> <br> <script> document.getElementById("myH2").style.color = "#ff0000"; document.getElementById("myP").style.color = "magenta"; </script> </body> </html>