Js 2
Js 2
Object
By using arrays we can store a group of individual objects and it is not
possible to store key-value pairs.
If we want to represent a group of key-value pairs then we should go for
Objects.
Array: A group of individual objects []
Object: A group of key-value pairs {}
JavaScript objects store information in the form of key-value pairs.
nums["fno"]=100 nums.fno=100
nums["sno"]=200 nums.sno=200
class ClassName
constructor() { ... }
}
Object Oriented Programming (OOP) in JS
// Defining class using es6
class Vehicle
{
constructor(name, maker, engine)
{
this.name = name;
this.maker = maker;
this.engine = engine;
}
getDetails()
{
return (`The name of the bike is ${this.name}.`)
}
}
// Making object with the help of the constructor
let bike1 = new Vehicle(A', 'Suzuki', '1340cc');
let bike2 = new Vehicle(B', 'Kawasaki', '998cc');
console.log(bike1.name);
console.log(bike2.maker);
console.log(bike1.getDetails());
Object Oriented Programming (OOP) in JS
Encapsulation:The process of wrapping properties and functions within a single unit is known as encapsulation.
class person
{
constructor(name,id)
{
this.name = name;
this.id = id;
}
add_Address(add)
{
this.add = add;
}
getDetails()
{
console.log(`Name is ${this.name},Address is: ${this.add}`);
}
}
Unlike most of the OOP languages where classes inherit classes, JavaScript
Objects inherit Objects i.e. certain features (property and methods) of one object
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)
The pattern is: any five letter string starting with a and ending with s.
https://regex101.com/
Create a RegEx
Using a regular expression literal:
const regularExp = /abc/;
Using the RegExp() constructor function:
const reguarExp = new RegExp('abc');
JavaScript Regular Expressions
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
if (position >= 0)
else
output:
Executes a search for a match in a string and returns an array of information. It returns
exec()
null on a mismatch.
match() Returns an array containing all the matches. It returns null on a mismatch.
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.
[] - Square brackets -Square brackets specify a set of characters you wish to match.
^ - Caret-The caret symbol ^ is used to check if a string starts with a certain character.
$ - Dollar-The dollar symbol $ is used to check if a string ends with a certain character.
* - Star-The star symbol * matches zero or more occurrences of the pattern left to it.
+ - Plus-The plus symbol + matches one or more occurrences of the pattern left to it.
? - Question Mark -The question mark symbol ? matches zero or one occurrence.
23
Event Driven Programs
• Programs that can capture and respond to events are called
‘event-driven programs’
24
JavaScript Handling of Events
• Events handlers are placed in the BODY part of a Web page
as attributes in HTML tags
25
26
JavaScript that goes between the <SCRIPT>, </SCRIPT> tags:
function checkForm() {
if ( document.sendEmail.sender.value.length < 1) {
window.alert( “Empty From field! Please correct” );
}
}
onMouseOver=“checkForm( )”
27
Usage Guideline
• For very short scripts, “all code in the tag” works well
28
29
JavaScript that goes between the <SCRIPT>, </SCRIPT> tags:
function vuWindow() {
window.open(“http://www.vu.edu.pk/”) ;
}
onClick=“vuWindow()”
30
A Few of Favorite Event Handlers
onClick
onDblClick
onMouseOver
onMouseDown
onFocus
onBlur
onReset
onSubmit
onLoad
onUnload
31
onFocus & onBlur
• onFocus executes the specified JavaScript code when a
window receives focus or when a form element receives
input focus
32
33
JavaScript that goes between the <SCRIPT>, </SCRIPT> tags:
function checkAge( ) {
if( parseInt( document.form1.age.value ) < 12 ) {
window.alert( "Stop! You are younger than 12" ) ;
}
}
36
http://www.vu.edu.pk/
onUnloadDemo.htm
37
<HTML>
<HEAD>
<TITLE>onUnload Demo</TITLE>
<SCRIPT>
function annoyUser( ) {
currentUrl = window.location ;
window.alert( "You can't leave this page" ) ;
window.location = currentUrl ;
}
</SCRIPT></HEAD>
<BODY onUnload="annoyUser( )">
This page uses the onUnload event handler …
</BODY></HTML>
38
<HTML>
<HEAD>
<TITLE>onUnload Demo</TITLE>
<SCRIPT>
function annoyUser( ) {
currentUrl = window.location ;
window.alert( "You can't leave this page" ) ;
window.location = currentUrl ;
}
</SCRIPT></HEAD>
<BODY onUnload="annoyUser( )">
This page uses the onUnload event handler …
</BODY></HTML>
39
More Uses for onLoad/onUnload?
• onLoad can be used to open multiple Windows when a
particular document is opened
• onUnload can be used to say “Thank you for the visit” when
a user is leaving a Web page
40
A Note on Syntax (2)
• At times, you may wish to use event handlers in JavaScript
code enclosed in <SCRIPT>, </SCRIPT> tags
41
A misleading statement from Lecture 18
• I stated:
JavaScript is case sensitive. Only the first of the following
will result in the desired function – the rest will generate
errors or other undesirable events:
• onMouseClick – OnMouseClick
• onmouseclick – ONMOUSECLICK
42
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>
JavaScript Functions and Events
Mouse events
Keyboard events
Form events
Window/Document events
JS Mouse events
Event Performed Event Handler Description
mouseover onmouseover When the cursor of the mouse comes over the element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the browser unloads it
resize onresize When the visitor resizes the window of the browser
load onload When the browser finishes the loading of the page
JavaScript Events and Objects
Event Object
onLoad Body
onUnload Body
onMouseOver Link, Button
onMouseOut Link, Button
onSubmit Form
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
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