Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 1 Client Side Scripting Latest

Download as pdf or txt
Download as pdf or txt
You are on page 1of 62

Unit 1 :

Client Side Scripting


JavaScript

Prepared by: Laxman Kharel


JavaScript
➢ Brendan Eich, the father of JavaScript,
➢ JavaScript was designed to add interactivity to HTML page.
➢ JavaScript is a lightweight, cross-platform and interpreted scripting language.
➢ A JavaScript is usually embedded directly into HTML page.
➢ JavaScript is an interpreted language(means that scripts execute without preliminary compilation)
➢ Everyone can use JavaScript without purchasing a license.
➢ JavaScript is an object-based programming language that supports polymorphism, encapsulation, and
inheritance as well.
What can a JavaScript Do?
➢ It gives HTML designer a programming tool,
➢ It can put dynamic text into an html page.
➢ It can react to events
➢ It can read and write Html elements
➢ It can be used to validate date, to create cookies etc.
Client-Side Scripting language Vs Server-side Scripting language
BASIS SERVER-SIDE SCRIPTING CLIENT-SIDE SCRIPTING

Basic Works in the back end which could not be visible at the client Works at the front end and script are visible
end. among the users.
Processing Requires server interaction. Does not need interaction with the server.
Languages PHP, ASP.net, Ruby on Rails, ColdFusion, Python, HTML, CSS, JavaScript, etc.
Affect Could effectively customize the web pages and provide Can reduce the load to the server.
dynamic websites.
Security Relatively secure. Insecure

➢ Client-side scripting is performed to generate a code that can run on the client end (browser) without needing
the server side processing. Basically, these types of scripts are placed inside an HTML document. The effective
client-side scripting can significantly reduce the server load. It is designed to run as a scripting language utilizing
a web browser as a host program. For example, when a user makes a request via browser for a webpage to the
server, it just sent the HTML and CSS as plain text, and the browser interprets and renders the web content in the
client end.
Client-Side Scripting language Vs Server-side Scripting language

➢ Server-side scripting is a technique of programming for producing the code which can run software on
the server side, in simple words any scripting or programming that can run on the web server is known as
server-side scripting, The server-side involves three parts: server, database, API’s and back-end web
software developed by the server-side scripting language. When a browser sends a request to the server
for a webpage consisting of server-side scripting, the web server processes the script prior to serving the
page to the browser. Here the processing of a script could include extracting information from a database,
making simple calculations, or choosing the appropriate content that is to be displayed in the client end.
The script is being processed and the output is sent to the browser. The web server abstracts the scripts
from the end user until serving the content, which makes the data and source code more secure.
Client-Side Scripting language
➢Advantages:
➢ More interactive since it responds immediately to the user action.
➢ Quick Execution because they don't require a trip to the server.
➢ improve the user experience for the user whose browser support script.
➢ An alternative option is available for the user whose browser didn't support script.
➢ Reusable and obtainable from many resources.
➢ Disadvantages:
➢ It is not supported by all browsers. if no alternative is given for the script than the user might get an error.
➢ Need more testing. because of the different browser and its version support script differently.
➢ If the Script is not available through other resources than more development time and effort required.
➢ Developers have more control over the look and behavior of their Web widgets; however, usability issues can arise if a
Web widget seems like a standard control but behaves different way or vice-versa.
Uses of JavaScript
➢ Adding Interactivity to the website:
➢ Developing mobile application:
➢ Create web browser-based games
➢ Back end web development:
➢ Client-side Validation:
➢ Event Handling:
➢ Building web servers and developing server applications:
➢ Some other uses:
➢Dynamic drop-down menus.
➢ Build forms that respond to user input without accessing a server.
➢ Change the appearance of HTML documents and dynamically write HTML into separate windows.
➢ Open and close new windows or frames.
➢ Build small but complete client side programs.
➢ Displaying popup windows and dialog boxes(like alert dialog box, confirm dialog box and prompt dialog box).
➢ Displaying date, clocks etc.
Formatting and Coding Convention
❑ Naming and declaration rules for variables and functions.
❑ Rules for the use of white space, indentation, and comments.
❑ Programming practices and principles
Coding conventions secure quality:
❑ Improves code readability
❑ Make code maintenance easier
❖ Mainly we use camelCase for identifier names (variables and functions) eg: firstName, doExit()
❖ Always put spaces around operators ( = + - * / ), and after commas: eg: var x = y + z;
❖ Always use 2 spaces for indentation of code blocks:
eg: function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
} }
❖ Always end a simple statement with a semicolon. (It’s a rule actually like in Java)
❖ Global variables written in UPPERCASE (We don't, but it's quite common)
❖ Constants (like PI) written in UPPERCASE
JavaScript Files, Comments

❑ The JavaScript files are saves in .js file extension.


❑ Comments
▪ Single line comment
▪ Single line comments start with //.
▪ Any text between // and the end of the line will be ignored by JavaScript(will not be executed)
▪ Multi-Line comments
▪ Multi line comments starts with /* and ends with */ .
▪ Any text between /* and */ will be ignored by JavaScript
Embedding JavaScript In HTML
❑ The JavaScript code can be inserted in HTML file by using the HTML <script> tag. When an HTML document is loaded
with the <script> tag in the web browser, the browser processes the content enclosed inside the script tag as JavaScript
code.
❑ The tags used to begin and end a script are the <Script> and </Script> tags.
<script type=“text/javascript”> The language “Javascript” command is there so the browser can tell the code that
follows is in JavaScript. You can also omit the type attribute from you <script> tag.
❑ JavaScript is written in the same way as HTML in a text editor. Js implementation is quite similar to CSS; you can link to
outside files(with the file extension .js), or write block of code right into you HTML documents with the <script> tag.
❑ Embedded script
<script type=“text/javascript”>
document.write(“<i>Welcome to JavaScript language</i>”);
</script>
❑ External Script
To import script from external JS files we save the code in the text file with the .js extension without the script tags.
We then link to the document in the page’s <head>, with
Embedding JavaScript In HTML
<script type=“text/Javascript” src=“external.js”></script>

We should always include in the head so that the browser is ready to execute scripts when the user calls for them . If a
user clicked a button that called for a script that the browser wasn’t aware of yet, you’d get an error. Having them in the
head means they’re always ready before they’re needed.
A Simple Script
<script type=“text/javascript”>
document.write(“<h1> Title</h1>”);
document.write(“<p align=‘right’>Body</p>”);
</script>
We start by taking control of the document object, and uses its write method to output some text to the document. The
text inside the double quotes is called a String, and this String will be added to the page. To use an object’s methods or
properties, we write the object’s name, a dot, and then the method/property name. Each line of script ends with a
semicolon.
Note that when quoting attributes values, we have to use single quotes, as if we used double quotes , as if you used double
quotes the write method would think the string was over prematurely, and you’d get an error.
Noscript
To find whether the browser supports JavaScript or not, use the <noscript> tag. The HTML <noscript> tag is used to
handle the browsers, which do recognize <script> tag but do not support scripting. This tag is used to display an alternate text
message.
Eg:-
<!DOCTYPE html>
<html>
<head>
<title>HTML noscript Tag</title>
</head>

<body>
<script>
<!--
document.write(“<h1 style=‘color: magenta’>Welcome to JavaScript!</h1>")
-->
</script>

<noscript>
Your browser does not support JavaScript!
</noscript>
</body>
</html>
Basic Display Function in JS
document.write() : This is used to display given text on a webpage in JS.
<script>
document.write(“Welcome to JavaScript”);
</script>

console.log(): This function in JavaScript which is used to print any kind of variables defined before in it or to just print any
message that needs to be displayed to the user
<script>
console.log(“Welcome to JavaScript”);
</script>
Variables in JS
❑ Variables are containers for storing data values.
❑ JS variable is loosely typed language means a variable can store any type of value.
❑ Var keyword is used to declare variable. Eg: var name=“Ram”; var age=25;
❑ Variable scope in JS.
❑ Global Scope: variable declared outside of any function is global variables. It can be accessed & modified from any functions.
❑ Local Scope: Variables declared inside of any function is local variables. It can’t be accessed & modified outside functions
declaration.
❑ Eg:
<script type="text/javascript">
var fname="Java";
function name(){
var lname="Script“;
document.write(fname+lname);
}
document.write(fname+"<br>"); // we can't insert lname;
fname="ram";
lname="peter";//can't edit.
name();
</script>
Variables in JS
Var Let Const
var == function scope let == block scope const == block scope like let but immutable
Function scope means it occurs within a Block scope means it occurs within a Like let, const also uses block scope. But
function code block. const creates a constant, an immutable
Function scope is within the function. Block scope is within curly brackets. variable whose value cannot be changed.
<script type="text/javascript">
var fname;
var fname="mohan";
let age=30;
//let age=50; we can't use let to declare same variable
fname="Java"; //or var fname="java";
const name="Sohan"; //
/* const name;
name="sohan"; we can't do this */
{
var y=5; let x=6;
x=7;//we can modify value of let variable
document.write(x+"<br>");
}
document.write(y+" "+name+" "+age+" "+fname);
document.write(x);// let is block level variable
</script>
Operations
Variables:
• A variable is a location in the computer’s memory where a value can be stored for use by a script.
• All variable have a name and a value.
• Before 2015, using the var keyword was the only way to declare a JavaScript variable.
• The 2015 version of JavaScript (ES6 - ECMAScript 2015) allows the use of the const keyword to define a variable that cannot
be reassigned, and the let keyword to define a variable with restricted scope.
example : var price1 = 5; var price2 = 6; var total = price1 + price2;
Operators Operator Description Operator Example Same As
+ Addition = x=y x=y
- Subtraction += x += y x=x+y
Arithmetic * Multiplication -= x -= y x=x-y Assignment
Operator Operator
** Exponentiation Math.pow(x,y) *= x *= y x=x*y
/ Division /= x /= y x=x/y
% Modulus (Division Remainder) %= x %= y x=x%y
++ Increment **= x **= y x = x ** y
-- Decrement = x=y x=y
Operations
Operators
+ operator can be used to concatenate String. Eg: var a=“5”; var b=“Script”; var c=a+b;

Operator Description Operator Description


Comparison == equal to Logical
&& logical and
Operator Operator
=== equal value and equal type || logical or
!= not equal ! logical not
!== not equal value or not equal
type
> greater than Note:
< less than • Type means data type
• Var license=(age>18) ? ”ready for license”: ”underage”;
>= greater than or equal to
<= less than or equal to
? ternary operator
Control Structure
❑ The JavaScript control statement also known as Control Statement or Flow Control statements are statements which
decide the execution flow of the program
❑ Typically the program execution begins from the first line to the last line of that Js code. However in between this the flow
of the execution can be branched(based on some condition ) or re-iterated(loop) base on some criteria. This is the
functionality that is provided by the Control Structure in JS.
Control Structures
WAP to find day of a week using Switch case
<script type="text/javascript">

var day=1;
switch(day)
{
case 1:
document.write("<h1 style='color:blue'>Sunday</h1>");
break;
case 2:
document.write("<h1 style='color:green'>Monday");
break;
case 3:
document.write("<h1 style='color:yellow'>Tuesday");
break;
case 4:
document.write("<h1 style='color:magenta'>Wednesday");
break;
case 5: case 7:
document.write("<h1 style='color:black'>Thursday"); document.write("<h1 style='color:green'>Saturday");
break; break;
case 6: default:
document.write("<h1 style='color:purple'>Friday"); document.write("<h1 style='color:red'>InValid Input");
break; }
</script>.
Control Structures
WAP to find day of a week using Switch case
<html>
<head>
<title>doWhileExercise</title>
</head>
<body bgcolor="green">
<script type="text/javascript">
var i=12;
do{
document.write("<p style='font-size:"+i+"'>This is testing ");
i=i+3;
}while(i<30);
</script>
</body>
</html>
Labeled Statement
• Break: Jumps out of the loop/break the loop
• Continue: breaks one iteration of the loop and continue with the execution of loop.
• Label: javascript label statements are used to prefix a label to an identifier. A label can be used with break and continue
statement to control the flow more precisely. A label is simply an identifier followed by a colon (:) that is applied to a
statement or a block of code.
<script>
var i, j;
loop1:
for (i = 0; i < 3; i++) { //The first for statement is labeled "loop1"
loop2:
for (j = 0; j < 3; j++) { //The second for statement is labeled "loop2"
if (i === 1 && j === 1) {
continue loop1;
}
console.log('i = ' + i + ', j = ' + j);
}
} Output using
</script> Output using Loop 1
Loop 2
Array
❑ Array JavaScript Array is like a data type that is used to store one or more than one value of a similar type together.
❑ In simple, An array is a collection of variables of the same type.
❑ An array in javascript is an Array object. We use new operator to create an array and to specify the number of elements
in an array.
❑ Declaring and Allocating arrays :
var c; //declares a variable that will hold the array.
c=new Array(12); //allocates the array
The preceding statements can also be performed in single steps,
var c=new Array(12);
❑ Array using literal notation:
var earray = [ ]; // empty array
var fruits = ["mango","apple","orange","guava"]; // Array having elements
❑ Using new key word
let arr = new Array(); // empty array
let arr = new Array(10); // array of 10 elements size
let arr = new Array("Java","C","C++"); // array with 3 values
Foreach loop
❑ To loop over an array, we can also use the Array function forEach which is defined in its prototype definition.
Array Method:
var arr=new Array(“ram”, ”Shyam”, “hari”, “Geeta”);
• delete() : delete arr[index] ;
• Push() : arr.push(“Laxman”);
• Pop() : arr.pop();
• Sort() : arr.sort();
• Reverse() : arr.reverse();
• Shift() : insert item at first
• Unshift() : arr.unshift(“Peter”); delete item from first
• Concat() : arr1.concat(arr2);
Foreach loop
❑ To loop over an array, we can also use the Array function forEach which is defined in its prototype definition.
<script type="text/javascript">
var a=5;//no scope let a1=6;// within Scope
var sub=["java","Php","JavaScript"];
document.writeln("<h2 style='color:Magenta'>First Stage<h2>");
sub.forEach(function(value, index){
document.write("<h3 style='color:Yellow'>"+index+":"+value+"<br>");
});
document.write("<h2 style='color:Magenta'>Second Stage<h1>");
sub.push("Python");// used to insert item at last
sub.unshift("DataStructure"); //used to insert item at first
sub.forEach(function(value, index){
document.write("<h3 style='color:Yellow'>"+index+":"+value+"<br>");
});
document.write("<h2 style='color:Magenta'>Third Stage<h1>");
sub.pop(1); //used to remove item
sub.forEach(loop);
function loop(value, index){
document.write("<h3 style='color:Yellow'>"+index+":"+value+"<br>");
};
document.write("<br>"+sub.reverse());
document.write(sub.indexOf("JavaScript"));
</script>
for-of loop & for-in loop
▪ for/in - loops through the properties of an object
▪ for/of - loops through the values of an iterable object
▪ Difference with example :

<script type="text/javascript">
var mobile=['samsung','iphone','huwaei','MI'];
var y;
document.write("<h1>For Of Loop Start</h1>");
for(y of mobile){
document.write("<h2 style='color:orange'>"+y+"<br>");
}
document.write("<h1>For In Loop Start</h1>");
for(var x in mobile){
document.write("<h2 style='color:orange'>"+x+"<br>");
}
</script>
Defining and Invoking functions
❑ Function are subprogram which are used to compute a value or perform a task.
❑ It is a set of statements that are used to perform a specific task, like adding two numbers, finding the square of a
number, or any user-defined task.
❑ Functions can be parameterized and non-parameterized which means they may or may not take any input.
❑ There are two types of function in JavaScript
➢ Library or Built-in function. Eg: write(), alert(), prompt(), parseInt()
➢ User defined function:
❑ Function is defined by using the function keyword followed by the function name and parentheses ( ), to hold
params(inputs) if any. A function can have zero or more parameters separated by commas.
❑ The function body is enclosed within curly braces just after the function declaration part(function name and params), and
at the end of the function body, we can have a return statement to return some output, if we want.
function function_name(parameter-1, parameter-2,...parameter-n) {
// function body }
❑ Calling a user defined function:
After creating a function, we can call it anywhere in our script. The syntax for calling a function is
function_name(val-1, val-2, ..., val-n);
Defining and Invoking functions
❑ Return statement: A function may have return statement i.e., function may return value depending on the requirement.

WAP to implement simple function WAP to implement simple function with return type
<script type="text/javascript">
<script type="text/javascript">
function add(a,b){
function add(a,b){
var c=a+b;
var c=a+b;
return c;
document.writeln("The total is:"+c);
}
}
var r1=add("romeo", "Juliet");
add("romeo", "Juliet");
document.write(r1);
document.write("<br>");
document.write("<br>");
add(2,3);
var r2=add(2,3);
</script>
document.write(r2);
</script>
Defining and Invoking functions
❑ Functions can also be defined with a built-in JavaScript function constructor called Function().

WAP to implement function using constructor We actually don't have to use the function constructor.

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

var funct = new Function("a", "b", "return a * b"); var funct = Function("a", "b”, “return a*b”);
var x = funct(5, 6); var x = funct(5, 6);

document.write(x); document.write(x);

</script> </script>
Build in Objects, Date Objects
❑ An object as a collection of properties that are defined as a key-value pair, where the key is the generic name of the
object feature which can be assigned a value.
❑ In JavaScript, an object is a standalone entity where the properties of the object define the characteristics of the object.
❑ For example, if we consider a mobile phone as an object then its properties are its color, screen size, brand name,
operating system, RAM, Memory, etc. All these properties define the characteristics of a mobile phone.
❑ The property of an object is a key: value pair, where key refers to a variable, and value refers to any type of value
associated with the key. The value can be of any type like a number, string, or even an array, or another object.
❑ Build in Object:
➢ Math Object: abs(x), ceil(x), cos(x), floor(x), log(x), min(x, y), pow( x, y), round(x), sqrt(x)
➢ String Object: we will see in detail:
➢ Date Object:
➢ User defined Object
➢ Boolean Object
➢ Number Object
Build in Objects, Date Objects
❑ Wap to show program on userdefined object
<script type="text/javascript">
//let mobile =new object(),
let mobile={
name:'iphone', //first property has key: name & value:iphone
brand:'Apple',
model:'iphone XS-max',
price:150000
};
mobile.color="Black"; //adding new property to mobile
mobile['screen']="6.5in";
document.write("<h1 style='color:magenta'>"+mobile.name+"</h1>"); //access using property name.value
document.write("<h1 style='color:yellow'>"+mobile['brand']+"</h1>");
document.write("<h1>"+mobile['color']+"</h1>");
document.write("<h1 style='color:#aabbcc'>"+mobile['screen']+"</h1>");
delete mobile.brand; //remove property
mobile.model="Iphone XI-Max Pro"; //update the value of model
for(key in mobile){ //transversing object
document.write("<h1 style='color:#ddeeff'>"+mobile[key]+"<br>");
}
Strings
❑ String is simply a groups of characters, a word, sentence or URL for example .
❑ String are always delimited by quotes, either single or double. Usually you can single quotes around single character and
double quotes around anything longer. Eg: var a=“Welcome to the”; var b = “java Script”;
❑ To concatenate, or joint two strings, we use a plus sign. Eg: document.write(a+’ ‘+b);
❑ String has many methods and properties.
Methods Function
concat() It provides a combination of two or more strings.

indexOf() It provides the position of a char value present in the given string.

lastIndexOf() It provides the position of a char value present in the given string by searching a character from the last position.

search() It searches a specified regular expression in a given string and returns its position if a match occurs.

charAt() It provides the char value present at the specified index.

substr() It is used to fetch the part of the given string on the basis of the specified starting position and length.

substring() It is used to fetch the part of the given string on the basis of the specified index.

slice() It is used to fetch the part of the given string. It allows us to assign positive as well negative index.

trim() It trims the white space from the left and right side of the string.

toUpperCase() It converts the given string into uppercase letter.


String
WAP to show different methods of String
<script type="text/javascript">
var str1="Welcome to the";
var str2="JavaScript the world!";
var str=str1.concat(str2);
document.write(str);
document.write("<p>"+str.length);
document.write("<p>"+str.search("to")); //give index
document.write("<p>"+str.indexOf("the"));
document.write("<p>"+str.lastIndexOf("the")+"</p>");
document.write("<p style='color:yellow'>"+str.charAt(6)+"</P>");
var c=5+2;
var cstr=c.toString();
document.write(typeof("<p>"+cstr));
document.write("<p>"+cstr+7);
document.write("<p>"+str.toUpperCase());
document.write("<p>"+str.substr(2,6)); //(start,length)
document.write("<p>"+str.substring(2,6)); //(start,end-1)
document.write("<p>"+str.slice(2,6)); //(start,end)
</script>
Date Objects
❑ Date object provides method for date and time manipulation.
❑ These can be performed based on the computer’s local time zone or based on World Time standards’: GMT
❑ The Date object use browser's date timezone by default and display date in the text format.
❑ Date objects are created with the new Date() constructor. Date objects created by programmers are static. They don’t
contain a ticking clock.
❑ Days of week & months of the year are enumerated beginning with zero.
0 – Sunday 1 – Monday & so on
0 – January 1 - February & so on
Syntax :-
new Date(); :- creates a new date object with the current date and time.
new Date(milliseconds); :- It creates a new date Object as January 1,1970, 00:00:00 Universal Time UTC
new Date(year, month, day, hours, minutes, seconds, milliseconds); It creates object with the date specified by the integer
values for the year, month, day, hours, minutes, second, milliseconds. We can omit some of the arguments.
new Date(dateString); :- new Date(dateString) creates a new date object from a date string
Date Objects
Methods of date Objects:
➢ Date: Return today’s date and time
➢ toDateString(): Returns the "date" portion of the Date as a human-readable string.
➢ getDate(): returns the day of the month from 1 – 31. Today date
➢ getFullYear(): returns the year (4 digits for 4-digit years) of the specified date
➢ getMonth(): returns the month (0–11) in the specified date
➢ getDay(): returns the day of the week from 0 – 6
➢ getHours(): returns the hours that that range from 0 to 23.
➢ getMinutes()-(0-59) getSeconds()-(0-59), getMilliseconds() (0-999),
➢ toLocaleString(): returns a string representation of the date and time in a form specific to the computer’s locale. for
example : September 13, 2007,at 3:42:22 PM is represented as 09/13/07 15:47:22 in US and 13/09/07 15:47:22 in Europe.
➢ toUTCString() : returns a string representation of the date and time in the form: 15 Sep 2007 15:47:22 UTC
➢ ValueOf() : The time in number of milliseconds since midnight, January 1, 1970. ( same as getTime.)
➢ getTimezoneOffset() : returns the difference in minutes between the current time on the local computer & UTC
Date
WAP to show different methods of Date
<script type="text/javascript">
var d1=new Date();
document.write("<h1 style='color:yellow'>"+d1+"</h1>");
var d2=new Date(5600000000);
document.write("<h1 style='color:magenta'>"+d2+"</h1>");
var d3=new Date(2017,7,5,6,55,55);//(year, month, day, hours, minutes, seconds, milliseconds)
document.write("<h1 style='color:aabbcc'>"+d3+"</h1>");
var d4=new Date("November 24, 1990,12:12:12");
document.write("<h1 style='color:yellow'>"+d4+"</h1>");
document.write("<h1 style='color:aabbcc'>"+d1.toDateString()+"</h1>")
document.write("<h1 style='color:yellow'>"+d1.toTimeString()+"</h1>")
document.write("<h1 style='color:aabbcc'>"+d1.getDay()+"</h1>")
document.write("<h1 style='color:yellow'>"+d1.getMonth()+"</h1>")
document.write("<h1 style='color:aabbcc'>"+d1.getFullYear()+"</h1>")
document.write("<h1 style='color:yellow'>"+d1.getDate()+"</h1>")
document.write("<h1 style='color:aabbcc'>"+d1.getHours()+d1.getMinutes()+"</h1>")
document.write("<h1 style='color:yellow'>"+d1.getSeconds()+d1.getMilliseconds()+"</h1>");
</script>
Date
WAP to show different methods of Date
<script>
var current=new Date();
document.write("<p>toLocaleString: "+ current.toLocaleString()+"</p>"); //The toLocaleString()
method converts a Date object to a string, using locale settings
document.write("<p>toString: "+ current.toString()+"</p>");
document.write("<p>toUTCString: "+ current.toUTCString()+"</p>");
document.write("<p>valueOf: "+ current.valueOf()+"</p>"); //The valueOf() method returns the
primitive value of a Date object. The primitive value is returned as the number of millisecond since midnight
January 1, 1970 UTC.
document.write("<p>getTimezoneOffset: "+ current.getTimezoneOffset()+"</p>");//returns the
time difference between UTC time and local time, in minutes.
var anotherDate=new Date();
anotherDate.setDate(26);
anotherDate.setMonth(11);
anotherDate.setFullYear(2011);
anotherDate.setHours(23);
anotherDate.setMinutes(59);
anotherDate.setSeconds(59);
document.write(anotherDate);
</script>
Interacting with Browser, Windows & Frames
❑ The BOM(Browser Object Model) is used to interact with the browser.
❑ The default object of browser is window.
❑ Windows: The window object represents a window in browser. An object of window is created automatically by the
browser, but window is not the object of javascript.
❑ Methods of Windows Object.

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.

open() opens the new window.

close() closes the current window.

performs action after specified time like calling function, evaluating expressions etc.
setTimeout()
It performs its task after the given milliseconds.
Interacting with Browser, Windows & Frames – Windows & frames
<script type="text/javascript">
function myFunction(){ <body bgcolor="green">
var x=prompt("Enter value of x:"); <button onclick="myFunction()">Pro_Alert</button>
var y=prompt("Enter value of y:"); <button onclick="myFunction1()">Con_SetTout</button>
if(x>y) <button onclick="myFunction2()">Open</button>
alert("x is greater:"); <button onclick="myFunction3()">close</button>
else </body>
alert("y is greater:");
}
function myFunction1(){
var click=confirm("Would you like to submit");
setTimeout( function() {
if(click==true)
alert("you have submitted");
else
alert("not submitted");
}, 2000);
}
function myFunction2(){
open("date.html","myWindow","width=400, height=600");
}
function myFunction3(){
close();
}
</script>
</head>
Interacting with Browser, Windows & Frames -History
❑ The JavaScript history object represents an array of URLs visited by the user. By using this object, you can load previous,
forward or any page.
❑ Property of JavaScript history object :
• length: It returns the length of the history URLs visited by user in that session.
❑ Methods: forward(), back(), go()
<script type="text/javascript">
function backFunction() {
window.history.back(); //history.back();
}
function forwardFunction() {
window.history.forward();
}
function forward2Function() {
window.history.go(2);
}
</script>
</head>
<body bgcolor="green">
<button onclick="backFunction()">Back</button>
<button onclick="forwardFunction()">Forward</button>
<button onclick="forward2Function()">Forward2</button>
</body>
Interacting with Browser, Windows & Frames -Navigator
❑ The JavaScript navigator object is used for browser detection. It can be used to get browser information such as appName,
appCodeName, userAgent etc.
<script type="text/javascript">
document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);
document.writeln("<br/>navigator.appName: "+navigator.appName);
document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);
document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);
document.writeln("<br/>navigator.language: "+navigator.language);
document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);
document.writeln("<br/>navigator.platform: "+navigator.platform);
document.writeln("<br/>navigator.onLine: "+navigator.onLine);
if(navigator.cookieEnabled==true){
alert("cookies enabled");
}
else{
alert("Cookies disabled");
}
</script>
Interacting with Browser, Windows & Frames -Screen
❑ The JavaScript screen object holds information of browser screen. It can be used to display screen width, height,
colorDepth, pixelDepth etc..
<script>
document.writeln("<br/>screen.width: "+screen.width);
document.writeln("<br/>screen.height: "+screen.height);
document.writeln("<br/>screen.availWidth: "+screen.availWidth);
document.writeln("<br/>screen.availHeight: "+screen.availHeight);
document.writeln("<br/>screen.colorDepth: "+screen.colorDepth);
document.writeln("<br/>screen.pixelDepth: "+screen.pixelDepth);

</script>
❑ Location Object : The window.location object can be used to get the current page address
(URL) and to redirect the browser to a new page.
window.location.href : returns the href (URL) of the current page
window.location.hostname : returns the domain name of the web host
window.location.pathname : returns the path and filename of the current page
window.location.protocol : returns the web protocol used (http: or https:)
window.location.assign(): loads a new document
window.location.reload(): reload document
Document Object Model
❑ The Document Object Model or DOM is tree of nodes/elements created by the browser when a webpage is loaded.
❑ Its like a tree of elements also called nodes, which are used to represent every single element on the page.
❑ JavaScript Document object is an object that provides access to all HTML elements of a document.
❑ The document object stores the elements of an HTML document, such as HTML, HEAD, BODY, and other HTML tags as
objects.
❑ A document object is the child object of the window object
❑ What can we do using DOM?
➢ JS help us to change all elements, attributes, CSS styles in the page.
➢ Attach event listeners to elements (click, keypress, submit).
➢ JS helps us to add new HTML elements and attributes.
➢ JS helps us to remove existing HTML elements and attributes.
Document Object Model
HTML DOM tree of Objects

Element Node
Attribute Node
Text Node
Document Object Model
<html>
<head>
<meta charset="utf-8">
<title>DOM Tree Demos</title>
</head>
<body bgcolor="green">
<h1>An HTML 5</h1>
<p> This page contains some basic
HTML5 elements</p>
<p>Here's an unordered list:</p>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</body>
</html>

• The html node at the top of the tree is called the root node.
• The head and body node are siblings, since they’re both children of the html node. The head contain meta and title nodes. The body
node contains nodes representing each of the elements in the document’s body element.
• The li nodes are children of the ul node, since they’re nested inside it.
Document Object Model
❑ The Document Object Model or DOM is tree of nodes/elements created by the browser when a webpage is loaded.
❑ The Document Object Model (DOM) is a programming interface for HTML and XML(Extensible markup language)
documents.
❑ DOM is a way to represent the webpage in the structured hierarchical way so that it will become easier for programmers
and users to glide through the document. With DOM, we can easily access and manipulate tags, IDs, classes, Attributes or
Elements using commands or methods provided by Document object.
❑ Methods of Document Object:

getElementById() : select an element by id.

getElementsByName() : select elements by name.

getElementsByTagName() select elements by a tag name.

getElementsByClassName() select elements by one or more class names.

querySelector() select elements by CSS selectors.


Document Object Model
❑ Properties of Dom.

innerHTML: Gets or sets HTML or XML markup contained within the element

Similar to innerHTML except that it focused solely on textual content


InnerText:
contained within the element.

get/setAttribute: To get and set attribute node value

get/setAttributeNode: To get and set attribute node with property and value

Attributes: Returns all the attributes as object


Document Object Model: Methods of DOM
<script>
function task(){
var name=document.getElementById("fn").value;
var a=parseInt(document.getElementsByName("r1")[0].value);
var b=parseInt(document.getElementsByName("r1")[1].value);
document.getElementsByName("r1")[2].value=a+b;
document.getElementById("lbl1").innerText=name+" "+ "you have to pay"; }
function task1(){
var para=document.getElementsByTagName("p");
for(let i=0;i<para.length;i++){
para[i].style.fontWeight="bold";
para[i].style.color="yellow";
para[i].style.fontSize=36; } }
function task2(){
var hd=document.getElementsByClassName("hding");
for(let i=0;i<hd.length;i++){
hd[i].style.fontWeight="italic";
hd[i].style.color="Pink";
hd[i].style.fontSize=30; }
}
function task3(){
var v=document.querySelector("#d").innerText="So it changed";
}
Document Object Model: methods of DOM
<body bgcolor="green">
<label id="lblfname">FirstName</label>
<input type="text" name="fname" id="fn"><br><br>
<input type="text" name="r1" ><br><br>
<input type="text" name="r1" ><br><br>
<label id="lbl1"></label>
<input type="text" name="r1" ><br><br>
<button id="btn1" name="click1" onclick="task()">Click1</button>
<button id="btn2" name="click2" onclick="task1()">Click2</button>
<button id="btn3" name="click3" onclick="task2()">Click3</button>
<button id="btn4" name="click4" onclick="task3()">Click4</button><br>
<p>This is paragraph one</p>
<p>This is paragraph two</p>
<h1 class="hding">This is heading one</h1>
<h2 class="hding">This is heading two</h2>
<div class="c">nothing</div>
<div class="c">Something</div>
<div id="d">everything</div>
<div id="d">allthing</div>
</body>
Document Object Model: Properties of Dom
<body bgcolor="green">
<div id="header" class="js" style="border:1px solid red" onclick="fun()">Javascript</div>
<div id="menu">
<ul> <li><a href="">Home</a></li>
<li><a href="">Gallery</a></li>
<li><a href="">contact</a></li>
<li><a href="">About</a></li> </ul>
</div>
<script>
var intxt=document.getElementById("menu").innerText;
console.log(intxt);
var inthtm=document.getElementById("menu").innerHTML;
console.log(inthtm);
var a=document.getElementById("header").getAttribute("style");
console.log(a);
var an=document.getElementById("header").getAttributeNode("onclick");
console.log(an);
var att=document.getElementById("header").attributes; //show all attributes of header
console.log(att);
document.getElementById("header").setAttribute("style","border:4px dotted yellow");
document.getElementById("header").removeAttribute("onclick");
console.log(document.getElementById("header").attributes);
</script>
Event Handling
❑ Events are the action that result from activities, such as clicking a link or filling a form, by user.
❑ Event handling is the mechanism that controls the event and decides what should happen if an event occur.
❑ Event handlers are an extra attribute of an object which includes an event’s name and the action taken if the event occurs.
❑ An event handler is also known as an event listener.
Event Performed Event Handler Description

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.

Keydown & Keyup onkeydown & onkeyup When the user press and then release the key

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

Scroll onscroll When an element is scrolled around.


Event Handling
❑ To work with events there are two thing we need to do.
❖ Listen for events
❖ React to events .
Reacting to events:-
➢ Listening to event is handled by addEventListener

<body bgcolor="green">
<div>
<label id="lbl">Input Name:</label>
<input type="text" id="txt">
<input type="text" id="txt1"><br><br>
<button id="btn">Click</button>
<button id="btn1">Click1</button>
</div>
Event Handling
<script>
document.getElementById("btn").onmousemove=fun;
function fun(){document.getElementById("txt").style.background="blue"};

document.getElementById("btn1").addEventListener("dblclick",fun1);
function fun1(){ document.getElementById("lbl").style.border="5px solid red"};

document.getElementById("lbl").addEventListener("mousemove",function(){
this.style.background="yellow";
});
document.getElementById("txt1").addEventListener("mouseleave",fun2);
function fun2(){
this.style.background="blue";
};
document.getElementById("txt1").addEventListener("click",function(){
this.removeEventListener("mouseleave",fun2);
});
</script>
</body>
Forms
❑ Forms are used in webpages for the user to enter their required details that further send it to the server for processing. A
form is also known as a web form or HTML form. Examples of form use are prevalent in e-commerce websites, online
banking, online surveys to name a few.
Accessing the Form Elements: CheckBox
function fun1(){
var chkbx=document.getElementsByClassName("abc");
if(chkbx[0].checked==true){
document.getElementById("para").style.color="yellow";
}
else{
document.getElementById("para").style.color="black";
}
if(chkbx[1].checked==true){
document.getElementById("para").style.fontSize="50px"
}
if(chkbx[2].checked==true){
document.getElementById("para").style.fontWeight="bold";
}
}

<p id="para">Javascript is client side scripting </p>


<input type="checkbox" class="abc" onclick="fun1()">Color:Red
<input type="checkbox" class="abc" onclick="fun1()">Font-Size:50px
<input type="checkbox" class="abc" onclick="fun1()">Font-Weight:Bold
Forms
Accessing the Form Elements: Radio Accessing the Form Elements: Select
function fun1(){ function fun1(){
var rd1=document.getElementById("rd1"); var select=document.getElementById("sbox");
var rd2=document.getElementById("rd2"); alert(select.options[select.selectedIndex].
if(rd1.checked) value);
alert(rd1.value+"is checked"); }
else if(rd2.checked)
alert(rd2.value+"is checked"); <form>
else <select id="sbox">
alert("nothing is selected"); <option value="Nepal">Nepal</option>
} <option value="China">China</option>
<option value="India">India</option>
</select>
<button onclick="fun1()">Press Me</button>
</form>

<form onclick="fun1()">
<input id="rd1" name="group1" type="radio" value="male">Male<br>
<input id="rd2" name="group1" type="radio" value="female">Female<br>
<button >Clickme</button>
</form>
COOKIES
❑ A cookie is a piece of data that is stored on your computer to be accessed by your browser.
❑ A cookie contains the information as a string generally in the form of a name-value pair separated by semi-colons.
❑ It maintains the state of a user and remembers the user's information among all the web pages.
❑ Why Cookies?
❑ The communication between a web browser and server happens using a stateless protocol named HTTP. Stateless
protocol treats each request independent. So, the server does not keep the data after sending it to the browser. But
in many situations, the data will be required again. Here come cookies into a picture. With cookies, the web browser
will not have to communicate with the server each time the data is required. Instead, it can be fetched directly from
the computer. whenever a user sends a request to the server, the cookie is added with that request automatically.
Due to the cookie, the server recognizes the users.
❑ Structure of Cookies :
❑ Cookies are created using the cookie property of the Document object.
❑ The format of a cookie is as follows:

name=value; expires=expirationDateGMT; path=URLpath; domain=siteDomain


COOKIES
▪ name=value; : The first section of the cookie defines the name of the cookie and the value assigned to the cookie. Both

the name and value settings can be anything you choose to use. Eg: name=“ram” or any variable. This is the only section of the
cookie that is mandatory.

▪ expires=expirationDateGMT; : The optional expires= section specifies the date on which the cookie should expire. The
JavaScript Date Object can be used to obtain and manipulate dates for this purpose
e.g.: var expirationDate = new Date; expirationDate.setMonth(expirationDate.getMonth()+6)

▪ path=URLpath; : The path= setting allows a URL to be stored in the cookie. By default, cookies are accessible only to web
pages in the same directory as the web page which originally created the cookie. For example, if the cookie was created when the
user loaded http://www.hamronepal.com/home/index.html that cookie will be accessible to any other pages in the /home
directory, but not to pages in /about. Usually, we should set path to the root: path=/ to make the cookie accessible from all
website pages.

▪ domain=siteDomain : It specifies the domain for which the cookie is valid. If not specified this defaults to the host portion of
the current document location. If a domain is specified, sub domains are always included.
eg: document. Cookie =“username=peter; domain=peterson.com”;
person1.peterson.com person2.peterson.com //this two sub domain can access cookie made by domain=peterson.com
eg: document. Cookie =“username=peter; domain=person3.peterson.com”; //peterson.com can’t access cookie made by person3
COOKIES
<script>
function cookfun(){
var ucookval=document.getElementById("uname").value;
//=document.frm.uname.value;
var pcookval=document.getElementById("pass").value;
//=document.frm.pass.value;
//create cookie
document.cookie="Username = "+ucookval+";"+"expires=Thu, 18 Dec 2021 12:00:00 UTC";
document.cookie="Password= "+pcookval+";"+"expires=Thu, 18 Dec 2021 12:00:00 UTC";
}
//retrieve cookie
function cookfun1(){
var cookArr=document.cookie.split(";");
for(var i=0;i<cookArr.length;i++){
var cookVal=cookArr[i].split("=");
if(cookVal[0].trim()=='Username'){
//document.frm.uname.value=cookVal[1];
document.getElementById("uname").value=cookVal[1];
}
COOKIES
else if(cookVal[0].trim()=='Password'){
//document.frm.pass.value=cookVal[1];
document.getElementById("pass").value=cookVal[1];
} }
}
</script>
</head>
<body bgcolor="green">
<form name="frm">
Username: <input type="text" name="uname" id="uname"><br><br>
Password: <input type="text" name="pass" id="pass"><br><br>
<button onclick="cookfun()">SetCookie</button>
<button onclick="cookfun1()">GetCookie</button>
</form>
</body>
Handling Regular Expression
▪ Regular expressions are patterns used to match character combinations in strings.
▪ In JavaScript, regular expressions are also objects.
▪ Some methods of Regular expression:
▪ Exec(): this function will return an array for match or null if there is no matching.
▪ Test(): this function returns true or false
▪ Match() : this function returns an array of result or null
▪ Search() : this function returns index of first match else -1
▪ Replace() : This function returns new replaced string with all replacements( if no flag is given first match will be replaced)
▪ Flags:
▪ g – Global search, don’t return after the first match
▪ i – Case-insensitive search
Handling Regular Expression

<script type="text/javascript">
let reg=/Nepal/gi; //this is regular expression literal
let s="The Nepal is a landlocked country nepal lies in south east Asia";
//exec method - returns an array for match or null if not match
console.log(reg.exec(s));
//test method- returns true or false
console.log(reg.test(s));
//match method - returns an array for match or null
console.log(s.match(reg));
//search method - returns index of first match otherwise -1
console.log(s.search(reg));
//replace method- returns new replaced string
console.log(s.replace(reg,'Nepal with Kalapani & Limpiyadhura'));
</script>
Handling Regular Expression
Meta-Characters:
Metacharacter Description
. Find a single character, except newline or line terminator
\w or [a-zA-Z0-9_] Matches any word Character. A word character is any letter, digit and underscore.
\W Find a non-word character
\d or [0-9] It matches any decimal digit from 0 through 9.
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
\b Find a match at the beginning/end of a word, beginning like this: \bHI, end like this: HI\b
\B Find a match, but not at the beginning/end of a word
\0 Find a NULL character
\n Find a new line character
\t Find a tab character only
[^aeiou] matches a single character outside the given set
(foo|bar|baz) matches any of the alternatives specified
Handling Regular Expression
Quantifiers: They are symbols that have a special meaning in a regular expression.
Symbol 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

You might also like