Javascript 11
Javascript 11
Simplicity : Simple and easy to run. Syntax, rules and regulations mostly same as C , Java Programming
language.
Popularity: JavaScript is a very popular web language because it is used every where on the web.
Interoperability: JavaScript plays nicely with other languages and can be used in a wide range of applications.
Server Load : JavaScript reduce the server load as it executes on the client side. Although we can run java script
also on server with NodeJS.
Browser Compatible: JavaScript supports all modern browsers. It can execute on any browser and produce same
result.
Code Visibility: Code is always visible to everyone , anyone can view JavaScript code.
Stop Render: One error in JavaScript code can stop whole website to render.
Debugging Support : Not fruitful debugging support. Hence difficult for the developer to detect
the matter .
There are many advantages link with this like faster The primary advantage is it’s ability to highly
response times, a more interactive application. customize, access rights based on user.
It does not provide security for data. It provides more security for data.
HTML, CSS and javascript are used. PHP, Python, Java, Ruby are used.
End user can Turn off it from browser. End user can no turn off it from browser.
A Simple Script
<html>
<head><title>First JavaScript Page</title></head>
<body>
<h1>First JavaScript Page</h1>
<script type="text/javascript">
[Link]("<hr>");
[Link]("Hello World Wide Web");
[Link]("<hr>");
</script>
</body>
</html>
External JavaScript
<html>
<head><title>First JavaScript Program</title></head>
<body>
<script type="text/javascript"
src="your_source_file.js"></script>
</body>
</html> Inside your_source_file.js
[Link]("<hr>");
[Link]("Hello World Wide Web");
[Link]("<hr>");
• Use the src attribute to include JavaScript codes from an external file.
• The scripts inside an HTML document is interpreted in the order they appear in the document.
• Scripts in a function is interpreted when the function is called.
• So where you place the <script> tag matters.
Using innerHTML
To access an HTML element, JavaScript can use the
[Link](id) method.
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = ”Hello World”;
</script>
</body>
</html>
Hiding JavaScript from Incompatible Browsers
<script type="text/javascript">
[Link]("Hello, WWW");
</script>
<noscript>
Your browser does not support JavaScript.
</noscript>
</body>
</html>
Differences between var, let, and const
The scope of a var variable is The scope of a let variable is block The scope of a const variable is block
functional scope. scope. scope.
It can be updated and re-declared into It can be updated but cannot be It cannot be updated or re-declared
the scope. re-declared into the scope. into the scope.
• Post/pre increment/decrement
++, --
• Comparison operators
• ==, !=, >, >=, <, <=
• ===, !== (Strictly equals and strictly not equals)
• i.e., Type and value of operand must match / must not match
Logical Operators
• ! – Logical NOT
• || – Logical OR
• OP1 || OP2
Assignment operators
=, +=, -=, *=, /=, %=
Bitwise operators
&, |, ^, >>, <<, >>>
Conditional Statements
•“if” statement
•“if … else” statement
•"? :" ternary conditional statement
•“switch” statement
• All except "for/in" loop statements have the same syntax as those found
in C and Java.
“for/in” statement
for (var variable in object)
{
statements;
}
var arrayname=[value1,value2.....valueN];
[Link]
Array Examples
<script>
var Car = new Array(3);
Car[0] = "Ford"; Access Array
Car[1] = "Toyota";
Car[2] = "Honda"; Elements
var Car2 = new Array("Ford", "Toyota", "Honda");
[Link]("Yamaha");
[Link](Car2); // output : Ford,Toyota,Honda,Yamaha
[Link]();
[Link](Car2); // output : Ford,Toyota,Honda
Code
<html>
<head>
<title>Alert Box</title>
</head>
<body>
<script>
alert("Hello World");
</script>
</body>
</html>
Confirm Box
• A confirm box is used if you want the user to accept something.
• When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed, If the user clicks "OK", the box returns true. If the user clicks "Cancel",
the box returns false.
• Example :
Code
<script>
var a = confirm(“Are you sure??");
if(a==true) {
alert(“Record Deleted”);
}
else {
alert(“Record Not Deleted”);
}
</script>
Prompt Box
• A prompt box is used if you want the user to input a value.
• When a prompt box pops up, user have to click either "OK" or "Cancel" to proceed,
If the user clicks "OK" the box returns the input value, If the user clicks "Cancel"
the box returns null.
• Example:
Code
<script>
var a = prompt(“Enter Name");
alert(“User Entered ” + a);
</script>
Functions
• A JavaScript function is a block of code designed to perform a particular task.
• A JavaScript function is executed when "something" invokes it.
• A JavaScript function is defined with the function keyword, followed by a name,
followed by parentheses ().
• The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
• The code to be executed, by the function, is placed inside curly brackets.
• Example :
Code
function myFunction(p1, p2) {
return p1 * p2;
}
Functions (Cont.)
• When JavaScript reaches a return statement, the function will stop executing.
• If the function was invoked from a statement, JavaScript will "return" to execute
the code after the invoking statement.
• The code inside the function will execute when "something" invokes (calls) the
function:
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
Functions (Return Values)
// A function can return value of any type using the keyword "return".
// The same function can possibly return values of different types
function foo (p1)
{
if (typeof(p1) == "number")
return 0;// Return a number
else
if (typeof(p1) == "string")
return "zero"; // Return a string
foo(1); // returns 0
foo("abc"); // returns "zero"
foo(); // returns undefined
Variable Arguments
// "arguments" is a local variable (an array) available in every function
// You can either access the arguments through parameters
or through the "arguments" array.
[Link](a);
function sum ()
{
var s = 0;
for(var i = 0; i < [Link]; i++)
s += arguments[i];
return s;
}
Here,
myFunction - is the name of the function
arg1, arg2, ...argN - are the function arguments
statement(s) - is the function body
Example 2: Arrow Function with Multiple Argument
Example 1: Arrow Function with No Argument
let sum = (a, b) => {
let result = a + b; let greet = () => {
return result; [Link]('Hello');
} }
let result1 = sum(5,7); greet(); // Hello
[Link](result1); // 12
Built-In Functions
• parseInt(s)
• eval(expr)
• isFinite(x) • parseFloat(s)
[Link]
• This example uses the length property of the Javascript’s inbuilt object(String) to find the length of a string:
var message="Hello World!";
var x=[Link];
[Link]()
• This example uses the toUpperCase method of the String object to convert string to upper case:
var message="Hello World!";
var x=[Link]();
JavaScript’s inbuilt Objects
• JavaScript comes with some inbuilt objects which are,
• String
• Date
• Array
• Boolean
• Math
• RegExp
etc….
Strings
• The JavaScript string is an object that represents a sequence of characters.
• A string in a JavaScript is wrapped with single or double quotes
• There are 2 ways to create string in JavaScript
(1)By string literal : The string literal is created using double quotes.
var stringname="string value";
• Strings can be joined together with the + operator, which is called concatenation.
For Example,
mystring = “My name is ” + “Sandip”;
Access String Characters JavaScript Strings are immutable
You can access the characters in a string in two In JavaScript, strings are immutable.
ways. That means the characters of a string cannot
be changed.
•One way is to treat strings as an array.
For example,
For example,
var a = 'hello'; let a = 'hello';
[Link](a[1]); // "e“ a[0] = 'H';
[Link](a); // "hello"
•Another way is to use the method charAt().
For example,
var a = 'hello';
[Link]([Link](1)); // "e"
Methods Description String Object (Some useful methods)
charAt() It provides the char value present at the
specified index. slice() It is used to fetch the part of the given
concat() It provides a combination of two or more string. It allows us to assign positive as
strings. well negative index.
indexOf() It provides the position of a char value toLowerCase() It converts the given string into
present in the given string. lowercase letter.
lastIndexOf() It provides the position of a char value toLocaleLowerCase() It converts the given string into
present in the given string by searching a lowercase letter on the basis of host?s
character from the last position. current locale.
search() It searches a specified regular expression toUpperCase() It converts the given string into
in a given string and returns its position if uppercase letter.
a match occurs. toLocaleUpperCase() It converts the given string into
match() It searches a specified regular expression uppercase letter on the basis of host?s
in a given string and returns that regular current locale.
expression if a match occurs. toString() It provides a string representing the
replace() It replaces a given string with the specified particular object.
replacement. valueOf() It provides the primitive value of string
substr() It is used to fetch the part of the given object.
string on the basis of the specified starting split() It splits a string into substring array,
position and length. then returns that newly created array.
substring() It is used to fetch the part of the given trim() It trims the white space from the left
string on the basis of the specified index. and right side of the string.
Math Object in JavaScript
• The Math object allows you to perform mathematical tasks.
• The Math object includes several mathematical constants and methods.
• Math object has some properties which are,
Properties Description
E Returns Euler's number(approx.2.718)
LN2 Returns the natural logarithm of 2 (approx.0.693)
LN10 Returns the natural logarithm of 10 (approx.2.302)
LOG2E Returns the base‐2 logarithm of E (approx.1.442)
LOG10E Returns the base‐10 logarithm of E (approx.0.434)
PI Returns PI(approx.3.14)
SQRT1_2 Returns square root of ½
SQRT2 Returns square root of 2
Math Methods
Method Description Method Description
abs(x) Returns the absolute value of x exp(x) Returns the value of Ex
sin(x) Returns the sine of x (x is in radians) ceil(x) Returns x, rounded upwards to the nearest
cos(x) Returns the cosine of x (x is in radians) integer
tan(x) Returns the tan of x (x is in radians) floor(x) Returns x, rounded downwards to the
nearest integer
acos(x) Returns the arccosine of x, in radians
log(x) Returns the natural logarithm(base E) of x
asin(x) Returns the arcsine of x, in radians
round(x) Rounds x to the nearest integer
atan(x) Returns the arctangent of x as a numeric
value pow(x,y) Returns the value of x to the power of y
atan2(x) Returns arctangent of x max(x,y,z,...,n) Returns the number with the highest value
random() Returns random floating number between 0 sqrt(x) Returns the square root of x
to 1
Math Methods
<script>
var a = [Link](2,3);
[Link](a); // 8
[Link]([Link](2.7)); // 3
[Link]([Link](2.7)); // 2
[Link]([Link](2.7)); // 3
</script>
Date Object
❑The Date object works with dates and times.
❑Date objects are created with new Date().
There are different ways of instantiating (creating) a date:
new Date() new Date() creates a new date object with the current date and time:
;
[Link] = “Sandip";
[Link] = “Patel";
[Link] = ()=>{
alert("Welcome " + [Link] + " " + [Link])
}
</script>
Creating objects using Literal Notation
<script>
var person = {firstName: “Sandip", lastName: “Patel",
sayHi : function()
{
alert("Hi! " + [Link] + " " + [Link]);
}
}
</script>
DOM - Introduction
• The Document Object Model is the standard way to accessing documents.
• DOM allows scripts to dynamically access and update the content, structure, and style of a
document.
• Using JavaScript, you can create, modify and remove elements in the page dynamically.
• When a web page is loaded, the browser will consider all the tags/elements of page as an
object and creates a Document Object Model of the page.
• The HTML DOM model is constructed as a tree of Objects.
• With the DOM, JavaScript can access and change all the elements of an HTML document.
• The nodes in a document make up the page’s DOM tree, which describes the relationships
among elements
• Nodes are related to each other through child-parent relationships
• A node may have multiple children, but only one parent
• The document node in a DOM tree is called the root node.
43
HTML element
head element
title element
body element
h1 element
p element
p element
ul element
li element
li element
li element
44
The HTML DOM Tree of
Objects
With the object model, JavaScript gets all the power it needs to
create dynamic HTML:
domain Returns the domain name of the server that loaded the document
forms Returns a collection of all the forms in the document
images Returns a collection of all the images in the document
links Returns a collection of all the links in the document (CSSs)
referrer Returns the URL of the document that loaded the current document
title Sets or returns the title of the document
URL Returns the full URL of the document
Document Object Methods
Method Description
write() Writes HTML expressions or JavaScript code to a
document
writeln() Same as write(), but adds a newline character after
each statement
open() Opens an output stream to collect the output from
[Link]() or [Link]()
close() Closes the output stream previously opened with
[Link]()
getElementById() Accesses element with a specified id
getElementsByName() Accesses all elements with a specified name
getElementsByTagName() Accesses all elements with a specified tag name
setTimeout(), Set a time period for calling a function once; or
clearTimeout() cancel it.
getElementById()
• When we suppose to get the reference of the element from HTML in JavaScript using id
specified in the HTML we can use this method.
• Example :
HTML
<html>
<body>
<input type=“text” id=“myText”>
</body>
</html>
JavaScript
<script>
function myFunction()
{
var txt = [Link](“myText”);
alert([Link]);
}
</script>
getElementsByName()
• When we suppose to get the reference of the elements from HTML in JavaScript using name
specified in the HTML we can use this method.
• It will return the array of elements with the provided name.
• Example :
JavaScript
<script>
HTML function myFunction()
<html> {
<body> a=[Link](“myText”)[0];
<input type=“text” alert([Link]);
name=“myText”> }
</body> </script>
</html>
getElementsByTagName()
• When we suppose to get the reference of the elements from HTML in JavaScript using name of
the tag specified in the HTML we can use this method.
• It will return the array of elements with the provided tag name.
• Example :
JavaScript
<script>
HTML function myFunction() {
<html> a=[Link](“input”);
<body> alert(a[0].value);
<input type=“text” name=“uname”> alert(a[1].value);
<input type=“text” name=“pword”> }
</body> </script>
</html>
Forms using DOM
• We can access the elements of form in DOM quite easily using the name/id of the
form.
• Example : JS
function f()
{
var a = [Link][“myForm”];
HTML var u = [Link];
<html> var p = [Link];
<body> if(u==“admin” && p==“123”)
<form name=“myForm”> {
<input type=“text” name=“uname”> alert(“valid”);
<input type=“text” name=“pword”> }
<input type=“button” onClick=“f()”> else
</form> {
</body> alert(“Invalid”);
</html> }
}
Validation
• Validation is the process of checking data against a standard or requirement.
• Form validation normally used to occur at the server, after client entered
necessary data and then pressed the Submit button.
• If the data entered by a client was incorrect or was simply missing, the server
would have to send all the data back to the client and request that the form be
resubmitted with correct information.
• This was really a lengthy process which used to put a lot of burden on the server.
• JavaScript provides a way to validate form's data on the client's computer before
sending it to the web server.
Validation (Cont.)
Form validation generally performs two functions.
1. Basic Validation
• Emptiness
• Confirm Password
• Length Validation etc……
2. Data Format Validation
Secondly, the data that is entered must be checked for correct form and value.
• Email Validation
• Mobile Number Validation
• Enrollment Number Validation etc….
Validation using RegExp
• A regular expression is an object that describes a pattern of characters.
• Regular expressions are used to perform on text.
• A regular expression can be a single character, or a more complicated pattern.
• The test() method is a RegExp expression [Link] searches a string for a pattern, and returns
true or false, depending on the result.
• example:
var pattern = "^[\\w]"; // will allow only words in the string
var regex = new RegExp(pattern);
If([Link](testString))
{
//Valid
}
else
{
//Invalid
}
RegExp (Cont.) (Metacharacters)
• To find word characters in the string we can use \w
• We can also use [a-zA-Z0-9_] for the same
• To find non-word characters in the string we can use \W
• to find digit characters in the string we can use \d
• We can also use [0-9] for the same
• To find non-digit characters in the string we can use \D
• We can use \n for new line and \t for tab
Email Validation Using RegExp
JavaScript
<script>
function checkMail()
{
var a = [Link]("myText").value;
var pattern ="^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$”;
var regex = new RegExp(pattern);
if([Link](a))
{
alert("Valid");
}
else
{
alert("Invalid");
}
}
</script>
if (name == "") {
Form Validation - [Link]("Please Enter Your Name");
return false;
Example
<script> }
function validate() { else if (email == "" || ) {
var form1 = [Link]("Please enter a valid e-mail address.");
[Link]("RegForm"); return false;
var name = [Link]; }
var email = [Link]; else if (password == "") {
var phone = [Link]; alert("Please enter your password");
var what = [Link]; return false;
var password = [Link]; }
var else if([Link] <6){
regEmail=/^\w+([\.-]?\w+)*@\w+([\.-] alert("Password should be atleast 6 character long");
?\w+)*(\.\w{2,3})+$/g; return false;
var regPhone=/^\d{10}$/; }
else if (phone == "" || ) {
alert("Please enter valid phone number.");
return false;
}
else if ([Link] == -1) {
alert("Please enter your course.");
return false;
}
}
</script>
<tr>
<form name="RegForm" method="post" id="RegForm" onsubmit="return
<td>Mobile:</td>
validate()" > <td><input type="text" size="40"
<table> name="Telephone" /> <br></td>
<tr> </tr>
<td colspan="2"><h1 style="text-align: <tr>
center;">REGISTRATION FORM</h1></td> <td>Select Your Course : </td>
<td></td> <td><select type="text"name="Subject">
<option>[Link]</option>
</tr>
<option>[Link]</option>
<tr> <option>BCA</option>
<td>Name :</td> <option>MCA</option>
<td><input type="text" size="40" </select> <br></td>
name="Name" /> <br /></td> </tr> <br/> <br/>
</tr> <tr>
<tr> <td>Comments:</td>
<td>E-mail Address:</td> <td><textarea cols="40" name="Comment">
</textarea> <br></td>
<td><input type="text" size="40"
</tr>
name="EMail" /><br></td> <tr>
</tr> <td></td>
<tr> <td><input type="submit" value="Submit"
<td>Password:</td> name="Submit" /> <input type="reset"
<td><input type="text" size="40" value="Reset" name="Reset" /> <br></td>
name="Password" /><br></td> </tr>
</tr> </table>
</form>
Event Handling in Java Script
dblclick ondblclick The event occurs when the user double-clicks on an element
mousedown onmousedown The event occurs when a user presses a mouse button over an
element
mousemove onmousemove The event occurs when a user moves the mouse pointer over an
element
mouseover onmouseover The event occurs when a user mouse over an element
mouseout onmouseout The event occurs when a user moves the mouse pointer out of an
element
mouseup onmouseup The event occurs when a user releases a mouse button over an
element
Keyboard Events
.html
<body>
Select Product : <select name="" id="product">
<option value="45000">AC</option>
<option value="22000">TV</option>
<option value="15000">Refrigerator</option>
<option value="70000">Laptop</option> </select>
<br><br>
Net Prize : <input type="text" id="prize"> <br><br>
Quantity : <input type="text" id="quantity">
<br><br>
Total Amount :<input type="text" id="amount">
</body>
[Link]("change",()=>{
[Link] = [Link];
});
[Link]("focus",()=>{
[Link]=[Link] * [Link];
});
</script>
mouseover and mouseout events
<body>
<img src="img/[Link]" alt="" id="bulb">
</body> [Link]
<script>
var a = [Link]("bulb");
[Link]("mouseover",()=>{
[Link]= "img/[Link]";
});
[Link]("mouseout",()=>{
[Link]
[Link]= "img/[Link]";
});
</script>
Keypress events
<body>
<p>Press any key to display Current Date :</p>
<input type="text" id="key">
<script>
var key = [Link]("key");
[Link]("keypress",()=>{
var a = new Date();
alert(a)
});
</script>
</body>
<body>
<input type="text" id="rows" placeholder="Enter Rows"> <br>
<input type="text" id="cols" placeholder="Enter Cols"> <br>
<input type="button" value="Generate Table" id="btn1">
</body>
<script>
var rows = [Link]("rows");
var cols = [Link]("cols");
var btn1 = [Link]("btn1");
[Link]("click",()=>{
[Link]("<table border='2' width='50%'>");
for(let i=0; i<[Link]; i++)
{
[Link]("<tr>")
for(j=0; j<[Link]; j++)
{
[Link]("<td>" + "[" +i+"]" + "["+j+"]" + "</td>");
}
[Link]("</tr>");
}
[Link]("</table>");
}); Click event
</script>
setTimeout() method setInterval() Method
❑The setInterval() method repeats a given function at
❑The setTimeout() method executes a function, after
every given time-interval.
waiting a specified number of milliseconds.
Syntax:
Syntax:
setInterval(function, milliseconds);
setTimeout(function, milliseconds);
Example : callme function will call after every 2 seconds.
Example : callme function will call after 2 seconds So here welcome in ASOIT will be continuously display
at
<script>
2 seconds time interval
setTimeout(callme,2000); <script>
function callme() { setInterval(callme,2000);
alert('Welcome in ASOIT'); function callme() {
} alert('Welcome in ASOIT');
</script> }
</script>
clearTimeout() method clearnterval() Method
❑The clearInterval() method clears a timer set with
❑The clearTimeout() function in javascript clears the
the setInterval() method.
timeout which has been set by setTimeout()function
❑To clear an interval, use the id returned from
❑To clear Timeout, use the id returned from
setInterval():
setTimeout()
Example :
Example :
t = setInterval(callme, 3000);
t = setTimeout(callme, 3000);
clearInterval(t);
clearTimeout(t);
setInterval function – Example
Change the background color of page at specific time interval. Background color will be changed after every
seconds
<body id="mybody">
</body>
<script>
var colors = ["red","green","blue","pink","black","orange"];
var mybody = [Link]("mybody");
var i=0;
setInterval(()=>{
[Link] = colors[i];
++i;
if(i==[Link])
{
i=0;
}
},1000)
</script>
Callbacks in Javascript (Function as arguments)
❑In JavaScript, you can also pass a function as an argument to a function.
❑This function that is passed as an argument inside of another function is called a callback function.
❑A callback is a function which is called when a task is completed, thus helps in preventing any kind of blocking and a
callback function allows other code to run in the meantime.
❑Generally Callback function is used in Asynchronous communication
❑In the above program, there are two functions.
function greet(name, callback) {
❑While calling the greet() function, two arguments (a
[Link]('Hi' + ' ' + name);
string value and a function) are passed.
callback();
❑The callMe() function is a callback function.
}
function callMe() {
[Link]('I am callback function'); ❑If you create a function to load an external resource
} (like a script or a file), you cannot use the content
before it is fully loaded. This is the perfect time to
greet('Peter', callMe); use a callback.
❑Ex: Function reading a file
Output :
Callbacks Function Example : Asynchronous communication
<script>
// program that shows the delay in execution
function greet() {
[Link]('Hello world');
}
function sayName(name) {
[Link]('Hello' + ' ' + name);
}
❑As you know, the setTimeout() method executes a block of code after the specified time.
❑Here, the greet() function is called after 2000 milliseconds (2 seconds).
❑During this wait, the sayName(‘ASOIT'); is executed. That is why Hello ASOIT is printed before Hello world.
❑The above code is executed asnchronously (the second function; sayName() does not wait for the first
function; greet() to complete).
JSON
❑JSON stands for JavaScript Object Notation.
❑It has been extended from the JavaScript scripting language.
❑The filename extension is .json.
❑JSON Internet Media type is application/json.
❑The JSON format is syntactically similar to the code for creating JavaScript ❑JavaScript has a built in function
objects. for converting JSON strings into
JavaScript objects:
❑Because of this, a JavaScript program can easily convert JSON data into
JavaScript objects. [Link]()
❑Since the format is text only, JSON data can easily be sent between
computers, and used by any programming language. JavaScript also has a built in
function for converting an object
❑You can receive pure text from a server and use it as a JavaScript object. into a JSON string:
❑You can send a JavaScript object to a server in pure text format.
❑You can work with data as JavaScript objects, with no complicated parsing [Link]()
and translations.
Uses of JSON
❑It is used while writing JavaScript based applications that includes browser
extensions and websites.
❑JSON format is used for transmitting structured data over network connection.
❑It is primarily used to transmit data between a server and web applications.
❑Web services and APIs use JSON format to provide public data.
❑It can be used with modern programming languages.
❑It is a lightweight text-based interchange format.
❑JSON is language independent.
JSON Syntax Rules
<script>
var myJSON = '{"name":"John", "age":30, "cars":["Ford", "BMW", "Fiat"]}';
var myObj = [Link](myJSON);
[Link]("demo").innerHTML = [Link][0];
</script>
</body>