Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
83 views

Java Script

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

Java Script

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

Web Technologies(22ITC17)

UNIT – II

JavaScript (JS)
JavaScript

JavaScript

(often shortened to JS)

lightweight,

interpreted,

object-oriented language.
JavaScript
➢ JavaScript, which was originally developed at Netscape by Brendan Eich,
was initially named Mocha but soon after was renamed LiveScript.

➢ In late 1995 LiveScript became a joint venture of Netscape and Sun


Microsystems, and its name again was changed, this time to JavaScript.

➢ A language standard for JavaScript was developed in the late 1990s by


the European Computer Manufacturers Association (ECMA) as ECMA-
262.

➢ The ECMA-262 standard is now in version 12.


JavaScript
➢ Java and JavaScript are unrelated.

➢ Java script is divided into three parts

1. core: includes operators, primitive types, expression, statements and sub


programs.

2. Client – side java script: collection of objects that support control of a


browser and interaction with users. Ex HTML document become interactive
with the user inputs such as mouse clicks and keyboard use using javascript

3. Server- side java script: collection of objects used on web server. Ex


supports communication between web server and data base management
system.
Why JavaScript?

➢JavaScript is one of the 3 languages all web developers must learn:

1. HTML to define the content of web pages.

2. CSS to specify the layout of web pages.

3. JavaScript to program the behavior of web pages.


Why JavaScript?
JavaScript is:

➢ Lightweight programming language that runs on web browser (client-


side.

➢ Embedded into html code.

➢ Executed by all browsers.

➢ Easy to learn.

➢ Interpreted not compiled.


Uses of JavaScript
➢ JavaScript is a very powerful client-side scripting language.
➢ Javascript enhance the interaction between user and web page.
➢ You can make your webpage more lively and interactive, with the help of
JavaScript. JavaScript is also being used widely in game development
and Mobile application development.
➢ Java script is used to whether the values provided in the form are sensible or not.
So saves server time and internet time.
➢ Java script is used to access and modify the CSS properties and content of any
element of a displayed XHTML document.
➢ Makes static documents to dynamic documents.
JavaScript
Advantages

➢ Less server interaction

➢ Immediate feedback to the visitors

Limitations

➢ Not suitable for network applications

➢ No multithreading and multiprocessor capabilities


JavaScript Vs. JScript

➢ JavaScript: It is a scripting language whose trademark is Oracle

Corporation.

➢ JScript: It is also a scripting language but owned by Microsoft.

➢ JavaScript: One need to handle multiple browser compatibility by

writing code

➢ JScript: It’s only support Microsoft Internet Explorer.


How to use JavaScript
➢ Java script is embedded into a HTML using <script> tag

➢ <script>tag can be written in <head> or <body> tags of XHTML.


<html>
<head> <title> A sample Javascript Structure </title>
<script type = “text/Javascript” src=“test.js”>
//Javascript code goes here……
</script>
</head>
<body>
<script type = “text/javascript”>
//javascript code goes here……
</script>
</body>
</html>
How to use JavaScript
Example-1: Example-2:

<html> <html>

<body>
<body>
<script>
<scrip t>
document.write("<h1>This is a heading</h1>");
document.write("Hello World!")
document.write("<p>This is a paragraph</p>");
</script>
</script>
</body> </body>
</html> </html>
JavaScript Comments
Single-line Comment
<script>
// It is single line comment
document.write("Hello Javascript");
</script>
Multi-line Comment
<script>
/* It is multi line comment. It will not be displayed */
document.write("Javascript multiline comment");
</script>
JavaScript Data Types
➢ The data type is a basic type of data that can be used in a program.

➢ In JavaScript, there is no need to specify the type of variable because it is


dynamically used by JavaScript Engine.
JavaScript Variables
➢ Variables are used to store values

➢ The values may change during the script

➢ You may use var or let to declare a variable

Ex: Varvariablename= value;

• Varfirstname= “Sriram”;

• Varnumber=99;
JavaScript Variables
➢ Rules for variable names

• They must begin with a letter

• Variable names can also begin with $ and _ (but we will not use it)

• Variable names are case sensitive (y and Y are different variables);


JavaScript Data Types
Data Types Description Example

String Represents Textual Data 'hello', "hello world!" etc

An Integer or a Floating-Point
Number 3, 3.234, 3e-2 etc.
Number

Boolean True or False true and false

A Data type whose variable is


undefined let a;
not initialized

null Denotes a Null Value let a = null;

Object Key-Value Pairs of Data let student = { };


JavaScript Data Types

let length = 16; // Number

let lastName = "Johnson"; // String

let x = {firstName:"John", lastName:"Doe"}; // Object

const dataChecked = true; //Boolean

let name; //undefined

const number = null; //null

let person = { firstName: 'John', lastName: 'Doe' }; // Object


JavaScript Data Types
➢ JavaScript evaluates expressions from left to right.

➢ Different sequences can produce different results.

let x = 16 + "Volvo"; 16Volvo

let x = 16 + 4 + "Volvo"; 20Volvo

let x = "Volvo" + 16 + 4; Volvo164

const number1 = 3/0; +Infinity

const number2 = -3/0; -Infinity


JavaScript Data Types
To find the type of a variable, you can use the typeof operator.
JavaScript Type Conversion
➢ In programming, type conversion is the process of converting data of one type
to another. For example: converting String data to Number.

➢ There are two types of type conversion in JavaScript.

➢ Implicit Conversion - automatic type conversion.

➢ Explicit Conversion - manual type conversion.


JavaScript Type Conversion
➢ JavaScript automatically converts one data type to another (to the right
type). This is known as implicit conversion.

Implicit Conversion to String


Implicit Conversion to Number
Non-numeric String Results to NaN
Implicit Boolean Conversion to Number
Null Conversion to Number
Undefined used with Number, Boolean or Null
JavaScript Explicit Conversion
Convert to String/Boolean Explicitly
JavaScript Type Conversion Table
Screen output and keyboard input

➢Java script is interpreted by the browser when browser finds <script>tag in body of HTML document.

➢Java script models HTML document with the Document object.

➢Document object has a method write which is used to create script output.

➢Parameter to write can include any HTML tags and content.

➢Window object that models the browser window.

➢Window object includes three methods that create dialog boxes


Screen output and keyboard input

➢Three types of dialog boxes are

1. Alert box

2. Prompt box

3. Confirm box
Screen output and keyboard input

➢Alert box: Alert box is generally used to give warnings to user.


Screen output and keyboard input

➢Prompt box:
Screen output and keyboard input

➢Confirm box:
JavaScript Display Possibilities

➢Writing into an HTML element, using innerHTML.

➢Writing into the HTML output using document.write().

➢Writing into an alert box, using window.alert().

➢Writing into the browser console, using console.log().


JavaScript Display Possibilities
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
JavaScript Display Possibilities
<!DOCTYPE html>
<html>
<body>

<h2>My First Web Page</h2>


<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>
JavaScript Display Possibilities
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
JavaScript Display Possibilities
<!DOCTYPE html>
<html>
<body>

<script>
console.log(5 + 6);
</script>

</body>
</html>
External JavaScript
➢If you have the same javascript written in different HTML files, you may want to
• Write the script in a separate file
• Give it the extension .js and
• Point to it in the src attribute of the <script> tag
Note: .js file can not contain <script> tag
External JavaScript
➢External Javascript-places script in external file
Methods of window 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
setTimeout()
etc.
JavaScript Object
➢Everything in javascript is an object- a String, a Number, an Array, a Date....

➢Even Booleans, Numbers, Strings can be objects (if defined with the new keyword)

➢JavaScript variables can also contain many values. Objects are variables too. But objects can

contain many values.

➢Object values are written as name : value pairs (name and value separated by a colon).

➢A JavaScript object is a collection of named values.

➢It is a common practice to declare objects with the const keyword.


JavaScript Object
➢This code assigns a simple value to a variable named car:

var car = "Fiat";

➢Objects are variables too. But objects can contain many values.

➢JavaScript objects are containers for named values called properties or methods.

var car = {type:"Fiat", model:"500", color:"white"};

var person = {firstName:"John", lastName:"Doe", age:50}


JavaScript Object
➢Javascript object is a data , with properties and methods.

➢The named values, in JavaScript objects, are called properties.

➢An object method is an object property containing a function definition.

➢Properties are values associated with objects.

➢Methods are actions that objects can perform.

➢Example:- car

Car properties- name, model,weight, color

Car methods- drive(), start(), brake().


JavaScript Object
i. Direct assignment of values

Example:

Var person={name: “john”, age:”20”, height:”6f”};//object literal

(Or)

const person = {};

person.firstName = "John";

person.lastName = "Doe";

person.age = 50;

person.eyeColor = "blue";
JavaScript Object

ii. new operator is used to create instance of an object

Example:

var person=new Object();

// add properties to an object person

person.name=“ John”;

person.age=“20”;

person.height=“6f”;
JavaScript Object
iii. new operator is used by the constructor method

Example:
<script>

function emp(id,name,salary){

this.id=id;

this.name=name;

this.salary=salary;

e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);

</script>
JavaScript Object method
• Methods are actions that can be performed on objects.

• Methods are stored in properties as function definition.

• this keyword:

✓ In JavaScript, the this keyword refers to an object.

✓ Which object depends on how this is being invoked (used or called).

✓ The this keyword refers to different objects depending on how it is used:

✓ In an object method, this refers to the object.

✓ Alone, this refers to the global object.

✓ In an event, this refers to the element that received the event.


JavaScript Object method

• You access an object method with the following syntax:

objectName.methodName()

• If you access a method without the () parentheses, it will return the

function definition:

name = person.fullName;
JavaScript Object method
<script>

// Create an object:

const person = {

firstName: "John",

lastName : "Doe",

id : 5566,

fullName : function() {

return this.firstName + " " + this.lastName;

};

// Display data from the object:

document.getElementById("demo").innerHTML = person.fullName();

</script>
Math object in JavaScript

➢The Math object allows you to perform mathematical tasks.

➢Math is not a constructor. All properties and methods of Math are static

and can be called by using Math as an object without creating it.


• Var x = Math.PI; // Returns PI

• Var y = Math.sqrt(16); // Returns the square root of 16


Math object in JavaScript
Math object in JavaScript
<!DOCTYPE html>

<html>

<body>

<p id="demo">Click the button to display Euler's number.</p> output-2.718281828459045


<button onclick="myFunction()">Try it</button>

<script>

function myFunction()

document.getElementById("demo").innerHTML=Math.E;

</script>

</body>

</html>
Math object in JavaScript
Method Description
abs(x) Returns the absolute value of x
x
exp(x) Returns the value of E
max(x, y, z, ..., n) Returns the number with the highest value
min(x, y, z, ..., n) Returns the number with the lowest value
pow(x, y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Returns the value of x rounded to its nearest
integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle
The Number object
➢Number objects are created with new Number().
var num = new Number(value);
The Number object
Date object
➢ Displays current date and time of a system.
➢ Date object created with new operator
var today= new Date();

<!DOCTYPE html>
<html>
<body>
<script>
var d=new Date(); Output
document.write(d);
</script>
</body>
</html>
Date object
JavaScript Operators
Arithmetic Operators
Assignment Operators
Logical Operators
Comparision Operators
String Operator
Conditional Operator
Conditional Statement
Conditional Statement
<html>

<head>

<title> if conditional statement </title>

<script language = "javascript">

var stdmarks;

stdmarks = prompt("enter student marks" ,"stdmarks");

if(stdmarks>=60)

document.write("passed");

</script>

</head>

</html>
If…else Statement
If…else Statement
<html>

<head>

<title>

if else conditional statement

</title>

<script language = "javascript">

var stdmarks;

stdmarks = prompt("enter student marks" ,"stdmarks");

if(stdmarks>=60)

document.write("passed");

else

document.write("failed");

</script>

</head>

</html>
If…else if… else Statement
If…else if… else Statement
<html>

<head>

<title>

elseif conditional statement

</title>

<script language = "javascript">

var stdmarks;

stdmarks = prompt("enter student marks" ,"stdmarks");

if(stdmarks>=90)

document.writeln("GRADE A");

elseif(stdmarks>=80)

document.writeln("GRADE B");

elseif(stdmarks>=70)

document.writeln("GRADE C");

elseif(stdmarks>=60)

document.writeln("GRADE D");

else

document.writeln("failed grade");

</script>

</head>

</html>
Switch Case
<html>

<head>

<title>

switch statement

</title>

<script language = "javascript">

var choice,n;

choice = prompt("enter ur choice[1-4]" ,"choice");

n=parseInt(choice);

switch(n) {

case 1: document.writeln("GRADE A");

break;

case 2: document.writeln("GRADE B");

break;

case 3: document.writeln("GRADE C");

break;

case 4: document.writeln("GRADE D");

break;

default: document.writeln("FAILED");

}</script></head></html>
Control Statements/Loops in JS
For Loop in JS
while Loop in JS
while Loop in JS
Do..while Loop in JS
Do..while Loop in JS
<html>

<head>

<title>

do-while loop

</title>

<script language = "javascript">

var i=0;

do

document.writeln("the number is :" +i);

document.writeln("<br>");

i++;

}while(i<=5);

</script>

</head>

</html>
Break and continue in JS
Break and continue in JS
Break and continue in JS
JavaScript Arrays
➢An array is a special variable, which can hold more than one value at a time.
➢JavaScript arrays are used to store multiple values in a single variable.
Creating an Array
var array_name = [item1, item2, ...];
var array_name = new Array(“item1”, ”item2”, ”item3");
var cars = ["Saab", "Volvo", "BMW"];
var cars = new Array("Saab", "Volvo", "BMW");
Array indexes start with 0.
➢[0] is the first element. [1] is the second element.
JavaScript Arrays
Access an Array
You can refer to a particular element in an array by referring to the name of the array and
the index number. The index number starts at 0.
var myArray = new Array(3);
myArray[0]=“red”;
myArray[1]=“yellow”;
myArray[2]=“green”;

Modify Values in an Array


myArray[0]="Opel";
Array length
• If myArray is an array, its length is given by myArray.length
myArray.length=10;
Arrays
Arrays
Array Concatenation:
<body>
<p>concatinate two arrays</p>
<script>
var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = hege.concat(stale);
document.write(children);
</script>
</body>
Array.pop() :removes and returns the last element of the array, and decrements
the array’s length
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits.pop() + "<br />");
document.write(fruits + "<br />");
document.write(fruits.pop() + "<br />");
document.write(fruits);
Arrays
Array sort:
<!DOCTYPE html>
<html>
<body>
<p>concatinate two arrays</p>
<script>
var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = hege.concat(stale);
document.write(children+"<br/>");
children.sort();
document.write(children);
</script>
</body>
</html>
JavaScript Functions and Events
➢A JavaScript function is a block of JavaScript code, that can be

executed when "called" for.

➢For example, a function can be called when an event occurs, like when the

user clicks a button.

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


JavaScript Functions and Events

➢A function is written as a code block (inside curly { } braces), preceded

by the function keyword:

function functionname()
{
some code to be executed
}
JavaScript Functions and Events
<html>

<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function which returns the result:</p>

<p id="demo"></p>

<script>

function myFunction(p1, p2) {

return p1 * p2;

document.getElementById("demo").innerHTML = myFunction(4, 3);

</script>

</body>

</html>
JavaScript Functions and Events
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
Example on java script for adding numbers
<html>
<head>
<script type="text/javascript">
function add()
{
var a=document.getElementById("t1").value;
var b=document.getElementById("t2").value;
var c=parseInt(a)+parseInt(b);
document.getElementById("res").value=c;
}
</script>
</head>
<body>
<form>
num1:<input type="text" id="t1"/><br/><br/>
num2:<input type="text" id="t2"/><br/><br/>
result:<input type="text" id="res"/><br/><br/>
<input type="button" value="add" onclick="add()"/>
</form>
</body>
</html>
Create objects using functions
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.display=display_inf;
}
P1= new person(“james”, “Bond”,”007”,”brown”);
function display_inf()
{
document.write(“person firstname:”, this.firstname,”<br/>”);
document.write(“person lastname:”, this.lastname,”<br/>”);
}
// call above method display_inf()
P1.display_inf();
Let keyword
• A variable declared with var is defined throughout the program. One of
the issues with using the var keyword was redeclaring a variable inside
a block will also redeclare the variable outside the block.
• var and let are both used for variable declaration in javascript but the
difference between them is that var is function scoped and let is block
scoped.
• let is block-scoped
• let doesn't allow to redeclare Variables
• Redeclaring a variable with var in a different scope or block changes
the value of the outer variable too.
• When a variable declared with var is used in a loop, the value of that
variable changes.
JavaScript Scope
• Scope determines the accessibility (visibility) of variables.
• JavaScript has 3 types of scope:
✓ Block scope
✓ Function scope
✓ Global scope
• Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
• ES6 introduced two important new JavaScript keywords: let and const.
These two keywords provide Block Scope in JavaScript.
• Automatically Global
• If you assign a value to a variable that has not been declared, it will
automatically become a GLOBAL variable.
• Global variables defined with the var keyword belong to the window object
• Global variables defined with the let keyword do not belong to the window
object
Hoisting
• Hoisting is JavaScript's default behavior of moving all declarations to
the top of the current scope (to the top of the current script or the
current function).
• In JavaScript, a variable can be declared after it has been used.
• JavaScript only hoists declarations, not initializations.
<body>
<p id="demo"></p>

<script>
var x = 5; // Initialize x

elem = document.getElementById("demo"); // Find an element


elem.innerHTML = "x is " + x + " and y is " + y; // Display x and y

var y = 7; // Initialize y
</script>

</body>
Differences between var and let keywords

SN var let

1. The var keyword was introduced with The let keyword was added in ES6 (ES 2015)
JavaScript. version of JavaScript.

2. It has global scope. It is limited to block scope.

3. It can be declared globally and can be It can be declared globally but cannot be
accessed globally. accessed globally.
Differences between var and let keywords
SN var let

4. Variable declared with var keyword can be re-declared Variable declared with let keyword can be updated but
and updated in the same scope. not re-declared.
Example: Example:
function varGreeter() function varGreeter()
{ {
var a = 10; let a = 10;
var a = 20; //a is replaced let a = 20; //SyntaxError:
console.log(a); //Identifier 'a' has already been declared
} console.log(a);
varGreeter(); }
varGreeter();

5. It is hoisted. It is not hoisted.


Example: Example:
{ {
console.log(c); // undefined. console.log(b); // ReferenceError:
//Due to hoisting //b is not defined
var c = 2; let b = 3;
} }
JavaScript Use Strict
• With strict mode, you can not, for example, use undeclared variables.

• Strict mode is declared by adding "use strict"; to the beginning of a script or a function.

• Declared at the beginning of a script, it has global scope (all code in the script will execute in strict mode)

• Declared inside a function, it has local scope (only the code inside the function is in strict mode):

• Strict mode makes it easier to write "secure" JavaScript.

• Strict mode changes previously accepted "bad syntax" into real errors.


Events
• Javascript detect certain events performed on the browser and provide computation reactions when
event occurred.
• These computations are called event driven programming.
• Event is generate when user clicks on any html element with which javascript should react.
• Event handler is a script that is implicitly executed in response to the appearance of event.
• Examples of html events
• When u click mouse
• Press a key
• When page loaded
• When image loaded
• Input text changed
• When form submitted.
Events
• The change in the state of an object is known as an Event.

• Events are signals fired inside the browser window that notify of changes in the browser or operating

system environment.

• Programmers can create event handler code that will run when an event fires, allowing web pages to

respond appropriately to change.

• The process of reacting over the events is called Event Handling. The JS handles the HTML events

via Event Handlers.


Events

Event Handler

Onevent property addEventListener()

• JavaScript objects that fire events have a corresponding "onevent" properties (named by prefixing "on" to the name of

the event). These properties are called to run associated handler code when the event is fired, and may also be called

directly by your own code.

• The most flexible way to set an event handler on an element is to use the EventTarget.addEventListener method. This

approach allows multiple listeners to be assigned to an element, and for listeners to be removed if needed
JavaScript Functions and Events

➢Mouse events

➢Keyboard events

➢Form events

➢Window/Document events
JS Mouse events
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.


JS Keyboard/Form events
Event Performed Event Handler Description

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

Event Performed Event Handler Description

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form element

When the user modifies or changes the value of a form


change onchange
element
JS Window/Document Events
Event Performed Event Handler Description

load onload When the browser finishes the loading of the page

When the visitor leaves the current webpage, the browser


unload onunload
unloads it

resize onresize When the visitor resizes the window of the browser
JavaScript Events and Objects

Event Object
onLoad Body
onUnload Body
onMouseOver Link, Button
onMouseOut Link, Button
onSubmit Form
Button, Checkbox, Submit, Reset,
onClick
Link
JavaScript Click Event
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
document.write(“CBIT");
}
//-->
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>
JavaScript Mouse Event
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert(“CBIT");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
JavaScript 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=" CBIT";
}
//-->
</script>
</body>
</html>
JavaScript Keydown Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>
JavaScript Load Event
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>
JavaScript Strings
➢JavaScript strings are for storing and manipulating text.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p id="demo"></p>
<script>
let text = "John Doe"; // String written inside quotes
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
JavaScript Strings
Method Description

charAt(index) returns the character at the specified index

concat() joins two or more strings

replace() replaces a string with another string

split() converts the string to an array of strings

substr(start, length) returns a part of a string


substring(start,end) returns a part of a string
slice(start, end) returns a part of a string

toLowerCase() returns the passed string in lower case

toUpperCase() returns the passed string in upper case

trim() removes whitespace from the strings

includes() searches for a string and returns a boolean value

search() searches for a string and returns a position of a match


JavaScript Strings
const text1 = 'hello';
const text2 = 'world';
const text3 = ' JavaScript ';

console.log(text1.concat(' ', text2)); // "hello world"


console.log(text1.toUpperCase()); // HELLO
console.log(text3.trim()); // JavaScript
console.log(text1.split()); // ["hello"]
console.log(text1.slice(1, 3)); // "el"
console.log(text3.search("Script")); //9
console.log(text1.charAt("2")); //l
console.log(text1.substr(0,3)); //hel
console.log(text1.substring(0,4)); //hell
JS Date and Time
➢In JavaScript, date and time are represented by the Date object.

➢The Date object provides the date and time information and also provides
various methods.
Creating Date Objects
new Date()
new Date(milliseconds)
new Date(Date string)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
JS Date and Time
const timeNow = new Date();
console.log(timeNow); // shows current date and time
const time1 = new Date(0);
console.log(time1); // Thu Jan 01 1970 05:30:00
const time2 = new Date(100000000000)
console.log(time2); // Sat Mar 03 1973 15:16:40

const date1 = new Date("2020-07-01");


console.log(date1); // Wed Jul 01 2020 05:45:00 GMT+0545
const date2 = new Date("2020-07-01T12:00:00Z");
console.log(date2); // Wed Jul 01 2020 17:45:00 GMT+0545
const time3 = new Date(2020, 1, 20, 4, 12, 11, 0);
console.log(time3); // Thu Feb 20 2020 04:12:11
Object Oriented Programming (OOP) in JS

var College=[“CBIT",“MGIT",“VCE",“VNRVJIET"]; var college={ name:‘CBIT', year: 1979, Dept:‘IT' };


Object Oriented Programming (OOP) in JS
//Defining object
let person =
{
first_name:'CBIT',
last_name: 'MGIT',
//method
getFunction ()
{
return (`The name of the person is${person.first_name} ${person.last_name}`)
},
//object within object
phone_number :
{
mobile:'12345',
landline:'6789'
}
}
console.log(person.getFunction());
console.log(person.phone_number.landline);
Document Object Model (DOM)
➢ DOM acts as interface between JavaScript and HTML, CSS.

➢ Browser will construct DOM.

➢ All HTML tags will be stored as JavaScript objects.

t
Document Object Model (DOM)
https://software.hixie.ch/utilities/js/live-dom-viewer/
Document Object Model (DOM)
To display Document to the console:
Just type on JavaScript console: document
Then we will get total HTML Page/Document.
To Display DOM Objects on the Console:
console.dir(document)
Observe that Root element of DOM is document.
DOM Attributes:
1) document.URL :This is original URL of the website.
2) document.body :It returns everything inside body.
3) document.head :It returns head of the page.
4) document.links :It returns list of all links of the page.
Document Object Model (DOM)
How to grab HTML Elements from the DOM?
1) document.getElementById()
Returns element with the specified id.
2) document.getElementsByClassName()
Returns list of all elements belongs to the specified class.
3) document.getElementsByTagName()
Returns list of all elements with the specified tag.
4) document.querySelector()
Returns the first object matching CSS style selector.
5) document.querySelectorAll()
Returns all objects Matches the CSS Style Selector.
JavaScript Regular Expressions
➢ In JavaScript, a Regular Expression (RegEx) is an object that describes a
sequence of characters used for defining a search pattern.
/^a...s$/

➢ The pattern is: any five letter string starting with a and ending with s.
https://regex101.com/
Syntax
A regular expression could be defined like this:
var pattern = /pattern/attributes;
pattern:- specifies a regular expression
Attribute:- specify if a search should be global, case-insensitive, etc.
JavaScript Regular Expressions
Create a RegEx
➢ Using a regular expression literal:
cost regularExp = /abc/;
➢ Using the RegExp() constructor function:
const reguarExp = new RegExp('abc');
https://regex101.com/
JavaScript Regular Expressions
Using String Methods

➢ In JavaScript, regular expressions are often used with the two string methods: search() and

replace().

➢ The search() method uses an expression to search for a match, and returns the position of the match.
1. The search method returns the position in the String object at which the pattern matched.
2. If there is no match, search returns –1.
3. The position of the first character in the string is 0.

➢ The replace() method returns a modified string where the pattern is replaced.
JavaScript Regular Expressions
var str = "Rabbits are furry";

var position = str.search(/bits/g);

if (position >= 0)

document.write("'bits' appears in position", position,"<br />");

else

document.write("'bits' does not appear in str <br />");

output:

'bits' appears in position 3


JavaScript Regular Expressions
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>Replace "Microsoft" with “Google" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft!</p>
<script>
function myFunction()
{
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML = text.replace("Microsoft",“Google");
}
</script>
</body>
</html>
JavaScript Regular Expressions
Method Description

Executes a search for a match in a string and returns an array of information. It returns null
exec()
on a mismatch.

test() Tests for a match in a string and returns true or false.

match() Returns an array containing all the matches. It returns null on a mismatch.

matchAll() Returns an iterator containing all of the matches.

Tests for a match in a string and returns the index of the match. It returns -1 if the search
search()
fails.

Searches for a match in a string and replaces the matched substring with a replacement
replace()
substring.

split() Break a string into an array of substrings.


JavaScript Regular Expressions
const string = 'Find me';
const pattern = /me/;
// search if the pattern is in string variable
const result1 = string.search(pattern);
console.log(result1); // 5
// replace the character with another character
const string1 = 'Find me';
string1.replace(pattern, 'found you'); // Find found you
// splitting strings into array elements
const regex1 = /[\s,]+/;
const result2 = 'Hello world! '.split(regex1);
console.log(result2); // ['Hello', 'world!', '']
// searching the phone number pattern
const regex2 = /(\d{3})\D(\d{3})-(\d{4})/g;
const result3 = regex2.exec('My phone number is: 555 123-4567.');
console.log(result3); // ["555 123-4567", "555", "123", "4567"]
Meta characters
Characters provide special meaning
Quantifiers
Brackets

[abc] Find any characters between


brackets
[^abc] Find any character NOT
between the brackets
[0-9] Find numbers between them
[^0-9] Find any character NOT
between the brackets (any
non-digit)
(x/y) Find any of the alternative
Anchors
• A pattern is tied to a string position with an anchor.
• A pattern can be specified to match only at the beginning of the string by
preceding it with a circumflex (^) anchor.
/^pearl/

• A pattern can be specified to match at the end of a string only by


following the pattern with a dollar sign anchor.
/gold$/
Pattern Modifiers
• Modifiers can be attached to patterns to change how they are used, thereby increasing their
flexibility.
• The modifiers are specified as letters just after the right delimiter of the pattern.
• The i modifier makes the letters in the pattern match either uppercase or lowercase letters in
the string.
• For example, the pattern /Apple/i matches
‘APPLE’, ‘apple’, ‘APPle’, and any other combination of uppercase and lowercase spellings
of the word “apple.”
• The x modifier allows white space to appear in the pattern.
• If the pattern has the g modifier, the returned array has all of the substrings of the string that
matched.
Pattern Modifiers
• \b (boundary), which matches the boundary position between a word

character (\w) and a non-word character (\W), in either order. For

example, the following pattern matches “A tulip is a flower” but not “A

frog isn’t”:

/\bis\b/

• The pattern does not match the second string because the ‘is’ is followed

by another word character (n).


JavaScript Regular Expressions

In this example, matches is set to [4, 3].


JavaScript Regular Expressions
Do a case-insensitive search for
"w3schools" in a string:
<script>
Do a global search for "is":
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
<script>
document.write(str.match(patt1));
</script> var str="Is this all there is?";
var patt1=/is/g;
document.write(str.match(patt1));
Do a global, case-insensitive search for "is":

<script> </script>
output- is,is
var str="Is this all there is?";
var patt1=/is/gi;
document.write(str.match(patt1));

</script>

Output- Is,is,is
JavaScript Regular Expressions
Do a global, case-insensitive search for "is":
<!DOCTYPE html>
<html>
<body> [abc]
<!DOCTYPE html>
<script>
<html>
var str="Is this all there is?"; <body>
var patt1=/is/gi;
<script>
document.write(str.match(patt1)); var str="Is this all there is?";
</script> var patt1=/[a-h]/g;
document.write(str.match(patt1));
</body> </script>
</html>
</body>
Output- Is,is,is
</html>
output- h,a,h,e,e
JavaScript Regular Expressions
<!DOCTYPE html>
<html>
<body>

<script>
var str="Is this all there is?";
var patt1=/[^a-h]/g;
document.write(str.match(patt1));
</script>

</body>
</html>
Output- I,s, ,t,i,s, ,l,l, ,t,r, ,i,s,?
JavaScript Regular Expressions
Email Validation Example
<html>
<head> <body>
<script> <h3>EMAIL VALIDATION </h3>
function myFunction() { ENTER EMAIL :
var x =
document.getElementById("myText").value;
<input type="text" id="myText">
var y=/^[a-z]{1,20}\d{2}\@[a-z]{2,10}\.[a-
z]{3}$/; <button onClick="myFunction()">Try it</button>

if(x.match(y))
alert(" Valid email "); <p id="demo"> </p>

else </body>

alert("In valid email "); </html>

}
</script>
</head>

You might also like