0% found this document useful (0 votes)
42 views28 pages

Lec6 Web Programming

JavaScript objects allow for the organization of data and functions. There are built-in JavaScript objects like Window, Document, Location, History, Navigator, and Screen that provide useful information and functionality. JavaScript objects contain properties to store data and methods to perform actions. Objects are created using constructors and the new keyword. Properties are accessed via dot notation and methods are called on objects. The global Math and String objects provide methods for mathematical and string operations respectively.

Uploaded by

Menna Saed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
42 views28 pages

Lec6 Web Programming

JavaScript objects allow for the organization of data and functions. There are built-in JavaScript objects like Window, Document, Location, History, Navigator, and Screen that provide useful information and functionality. JavaScript objects contain properties to store data and methods to perform actions. Objects are created using constructors and the new keyword. Properties are accessed via dot notation and methods are called on objects. The global Math and String objects provide methods for mathematical and string operations respectively.

Uploaded by

Menna Saed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 28

Web Programming

Dr Walid M. Aly

Lecture 6
Java Script Objects
1
Web Programming 20:56 lec6 Dr Walid M. Aly
Java Script Object Orientation
• Java script has some very useful built-in JavaScript objects.
• We used till now 2 objects window & document
• JavaScript objects are collections of properties and
methods , which are like the members of classes in Java
• objects are created with constructor.
• Properties are the values associated with an object.
– Example a property that store the number of characters in a
String
• Methods are the actions that can be performed on
objects.
– Example a methods that change a String to upper case

2
http://www.w3schools.com/jsref/default.asp
Web Programming 20:56 lec6 Dr Walid M. Aly
Java Script Objects
Object Description
Window object The window object represents an open window in a browser.
Navigator object The navigator object contains information about the browser.
Screen object The screen object contains information about the visitor's screen.
History object The history object contains the URLs visited by the user
Location object The location object contains information about the current URL

Object Description
Array object used to store multiple values in a single variable.
Boolean object used to convert a non-Boolean value to a Boolean value
Date object used to work with dates and times.
Math object allows you to perform mathematical tasks
Number object The Number object is an object wrapper for primitive
numeric values
String object used to manipulate a stored piece of text.
RegExp object describes a pattern of characters.
Global used with all the built-in JavaScript objects. 3
Web Programming 20:56 lec6 Dr Walid M. Aly
Java Script Object Orientation...
• Objects are created using constructors and the new keyword
– today=new Date();
– String objects are created directly
• txt=“ Hello World”;
• Properties are accessed by objectName.property
– var txt="Hello World!";
document.write(txt.length);
– Methods are called by objectName.method name
• var day=today.getDay()
• var str="Hello world!";
document.write(str.toUpperCase());

4
Web Programming 20:56 lec6 Dr Walid M. Aly
JS Global
The JavaScript global properties and functions can be used with all the
built-in JavaScript objects.

• JavaScript Global Properties


Infinity , NaN, and undefined
JavaScript Global Functions
isNaN() : Determines whether a value is an illegal number
parseFloat()Parses a string and returns a floating point number
parseInt() Parses a string and returns an integer
eval():evaluate an expression

globalDemo.html

5
Web Programming 20:56 lec6
http://www.w3schools.com/jsref/jsref_obj_global.asp Dr Walid M. Aly
Example : using a global function :parseFloat

function Adder() {
var input1=window.prompt( "Enter First Number:");
var input2=window.prompt( "Enter Second Number:");
var num1=parseFloat(input1);
var num2=parseFloat(input2);
var result=num1+num2;
window.alert("Sum="+result);
}

simpleCalculater.html

6
Web Programming 20:56 lec6 Dr Walid M. Aly
JavaScript window Object
•The window object model the browser window
•We already used the method alert, confirm and prompt of this object
•The window objects has a property location and a method setTimeout

location the Location object for the window


The location object model the current URL.

•setTimeout(code,millisec)
• Calls a function or evaluates an expression after a specified number of milliseconds
• The ID value returned by setTimeout() is used as the parameter for the clearTimeout()
method

Parameter Description
function Required. The function that will be executed
milliseconds Required. The number of milliseconds to wait before executing the code
Return Value: A Number, representing the ID value of the timer that is set. Use this value
with the clearTimeout() method to cancel the timer
7
Web Programming 20:56 lec6 Dr Walid M. Aly
Example : Redirection using Window Object
<head>
<script type="text/javascript">
function delayer(){
window.location = "http://www.maktoob.com"
}
</script>
</head>
<body onLoad="window.setTimeout('delayer()', 5000)">
<h2>Prepare to be redirected!</h2>
<p>This page is a time delay redirect, please update your bookmarks to our new
location!</p>
</body>
RedirectDemo.html
Example: Using a button as a link to execute redirection

function go(){
a= window.confirm("Are you sure you want to exit");
if (a) RedirectDemo2
window.location="http://www.maktoob.com";
}
8
<input type="button" value="Yahoo."
Web Programming 20:56 lec6
onclick="go()"> Dr Walid M. Aly
JavaScript Math Object
The Math object allows you to perform mathematical tasks.
Math Object Methods
Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y,x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithm (base E) of x
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() Return a random number between 0 (inclusive) and 1 (exclusive)
round(x) Rounds x to the 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

var x=Math.PI;
var y=Math.sqrt(16);
document.write(Math.round(4.7));
document.write(Math.random());
9
Web Programming 20:56 lec6 Dr Walid M. Aly
Example : Random link using Math Object

<body>

<script type="text/javascript">
var r=Math.random();
if (r>0.5)
{
document.write("<a href='http://www.w3schools.com'>Learn Web evelopment!</a>");
}
else
{
document.write("<a href='http://www.wikipedia.org/'>Visit Wikipedia!</a>");
}
</script>

</body>

RandomLink.html

10
Web Programming 20:56 lec6 Dr Walid M. Aly
JavaScript String Object
• The String object is used to manipulate a stored piece
of text.
• String objects are created directly or with new String().
– var txt = new String(“Ahmed");
– var txt = “Ahmed";
• The number of characters in a string is stored in the
length property
var str = “Ahmed”;
var len = str.length;

11
Web Programming 20:56 lec6 Dr Walid M. Aly
String Object Methods
Method Description
charAt() Returns the character at the specified index
indexOf() Returns the position of the first found occurrence of a specified value in a
string or -1
lastIndexOf() Returns the position of the last found occurrence of a specified value in a string
match() Searches for a match between a regular expression and a string, and returns
the matches or null;
replace() Searches for a match between a substring (or regular expression) and a
string, and replaces the matched substring with a new substring
substring() Extracts the characters from a string, between two specified indices or
starting from one index
toLowerCase() Converts a string to lowercase letters
toUpperCase() Converts a string to uppercase letters

<script type="text/javascript">
var str = "Hello World!"; Hello World
document.write(str.indexOf("World") + "<br/>");
document.write(str.indexOf("world") + "<br/>");
document.write(str.match("World") + "<br/>");
document.write(str.match("world") + "<br/>");
document.write(str.replace("World"," AAST") + "<br/>");
</script>

12
Web Programming 20:56 lec6 StringDemo1.html
Dr Walid M. Aly
Return the first and last character of a string:

<script >
var str = "Hello world!";
document.write("First character: " +
Hello World!
str.charAt(0) + "<br />");
document.write("Last character: " + First character: H
str.charAt(str.length-1)); Last character: !
</script>

Extract characters from a string:


<script > Hello World!
var str="Hello world!";
document.write(str.substring(3)+"<br />");
document.write(str.substring(3,7)); lo world!
lo w
</script>

13
Web Programming 20:56 lec6 Dr Walid M. Aly
Split function
The split() method is used to split a string into an array of substrings, and returns the
new array.
How are you doing today?
<script type="text/javascript">
var str="How are you doing today?";
How are you doing today?
document.write(str.split() + "<br />");
How,are,you,doing,today?
document.write(str.split(" ") + "<br />");
H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?
document.write(str.split("") + "<br />");
How,are,you
document.write(str.split(" ",3));
</script>

<script type="text/javascript">
var str="name=Ahmed Aly"; name
values=str.split("="); Ahmed Aly
document.write(values[0]+"<br/>");
document.write(values[1]);
</script>

14
Web Programming 20:56 lec6 Dr Walid M. Aly
String HTML Wrapper Methods
The HTML wrapper methods return the string wrapped inside the appropriate HTML tag.

Method Description
anchor() Creates an anchor
big() Displays a string using a big font
blink() Displays a blinking string
bold() Displays a string in bold
fontcolor() Displays a string using a specified color
fontsize() Displays a string using a specified size from 1 to 7
italics() Displays a string in italic
link() Displays a string as a hyperlink
small() Displays a string using a small font
strike() Displays a string with a strikethrough
sub() Displays a string as subscript text
sup() Displays a string as superscript text

15
Web Programming 20:56 lec6 Dr Walid M. Aly
Example: creating a link using link()

Display the text: "Free Web Building Tutorials!" as a hyperlink:


<script>

var str = "Free Web Building Tutorials!";


document.write(str.link("http://www.w3schools.com"));

</script>

16
Web Programming 20:56 lec6 Dr Walid M. Aly
Example : Using String HTML Wrapper Methods
<script >
var word="Hello";
document.write(word.fontcolor("red"));
document.write("<br/>");
document.write(word.bold());
document.write("<br/>");
document.write(word.italics().strike());
document.write("<br/>");
word=word.fontsize(7);
word=word.fontcolor("green");
document.write(word);
</script>

17
Web Programming 20:56 lec6 Dr Walid M. Aly
Java script Navigator Object
• The Navigator object contains information about the visitor's browser
name, version, and more.
Method Description
javaEnabled() Specifies whether or not the browser has Java
enabled

Property Description
appCodeName Returns the code name of the browser
appName Returns the name of the browser
appVersion Returns the version information of the browser
cookieEnabled Determines whether cookies are enabled in the
browser
platform Returns for which platform the browser is compiled

18
Web Programming 20:56 lec6 Dr Walid M. Aly
Example : Using navigator Object

<script type="text/javascript">
var BrowserName=navigator.appName;
document.write("You are using the Browser :"+ BrowserName +"<br/>");
var BrowserVersion= navigator.appVersion;
document.write("Your Browser Version :"+ BrowserVersion+"<br/>");
if( navigator.cookieEnabled)
document.write("cookies are enabled"+"<br/>");
else
document.write("cookies are not enabled"+"<br/>");
if( navigator.javaEnabled())
document.write("Your Browser support java "+"<br/>");
else
document.write("Your Browser does not support java"+"<br/>");
</script>

NavigatorDemo.html

19
Web Programming 20:56 lec6 Dr Walid M. Aly
JavaScript Date Object
Some examples of creation of a date:
var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)

• Local time methods of Date:


– getDate – returns the day of the month (1-31)
– getMonth – returns the month of the year (0 – 11)
– getDay – returns the day of the week (0 – 6), where Sunday is equivalent to zero
– getFullYear – returns the year
– getHours – returns the hour (0 – 23)
– getMinutes – returns the minutes (0 – 59)
– setDate()-Sets the day of the month (from 1-31)
– setFullYear()-Sets All data year , month ,day
– setHours()-Sets the hour (from 0-23)
– setMinutes()-Set the minutes (from 0-59)
– setSeconds()-Sets the seconds (from 0-59)
When an object of class Date is printed to screen , a description of date is shown
d=new Date(); document.write(d); 20
Web Programming 20:56 lec6 Dr Walid M. Aly
Example : dynamic day greeting
<script >
//If the time is less than 10, you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.

var d = new Date();


var time = d.getHours();

if (time < 10)


{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}
</script>
gereeting.html

21
Web Programming 20:56 lec6 Dr Walid M. Aly
Example : dynamic day greeting using a function
…..
<script type = "text/javascript" >
function getGreeting(hour)
{
if (hour<10)
return "Good Morning";
if (hour<17)
return "Good Afternoon";
else
return "Good Evening";
}
</script>
<h1> Hello </h1>
<script type = "text/javascript" >
var today=new Date();
var hour=today.getHours();
var message=getGreeting(hour);
document.write(message);
</script>

gereeting2.html
22
Web Programming 20:57 lec6 Dr Walid M. Aly
JavaScript Array Object
• Array elements can be primitive values or references to other
objects
• the elements of an array need not have the same type.
Create an Array
An array can be defined in three ways.
var myCars=new Array();
myCars[0]=“Matrix ";
myCars[1]="Volvo";
myCars[2]="BMW";

var myCars=new Array(" Matrix ","Volvo","BMW"); // condensed array

var myCars=[" Matrix ","Volvo","BMW"]; // literal array

•If you specify numbers or true/false values inside the array then the variable type will be
Number or Boolean, instead of String.

23
Web Programming 20:57 lec6 Dr Walid M. Aly
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.
document.write(myCars[0]);
alert(mycars[0));

 If you print the array, all elements are printed

• Array Length
– Length is dynamic - the length property stores the length
• length property is writeable
myList.length = 150;
– The length of an array is the highest subscript to which an element has
been assigned, plus 1
myList[122] = “Hello"; // length is 123
– Assigning a value to an element that does not exist creates that element

24
Web Programming 20:57 lec6 Dr Walid M. Aly
Array methods
Method Description
concat() Joins two or more arrays, and returns a copy of the joined
arrays
join(separator) Joins all elements of an array into a string, The elements will
be separated by a specified separator. The default separator is comma (,)
pop() Removes the last element of an array, and returns that
element
push() Adds new elements to the end of an array, and returns the
new length
reverse() Reverses the order of the elements in an array
slice() Selects a part of an array, and returns the new array
sort() Sorts the elements of an array

arrayDemo.html
25
Web Programming 20:57 lec6 Dr Walid M. Aly
Indexing in JavaScript Arrays
• Many programming languages support arrays with named
indexes.
• Arrays with named indexes are called associative arrays (or
hashes).
• JavaScript does not support arrays with named indexes.
• In JavaScript, arrays always use numbered indexes.

26
Web Programming 20:57 lec6 Dr Walid M. Aly
Example :Return the name of the weekday (not just a number)

<script type="text/javascript">

var d=new Date();


var weekday=new Array();
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

document.write("Today is " + weekday[d.getDay()]);

</script> dateDayDemo.html

28
Web Programming 20:57 lec6 Dr Walid M. Aly
JavaScript Number Object
The Number object is an object wrapper for primitive numeric values.
The Number Object has some useful properties
Methods in Number can be called directly y primitive values
var num = new Number(value);
Number Object Properties
Property Description
MAX_VALUE Returns the largest number possible in JavaScript
MIN_VALUE Returns the smallest number possible in JavaScript
NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
POSITIVE_INFINITY Represents infinity (returned on overflow)

Number Object Methods


Method Description
toFixed(x) Formats a number with x numbers of digits after the decimal point by rounding
toPrecision(x) Formats a number to x length by rounding, A decimal point with zeros are
added (if needed), to create the specified length.
var num = 10; var result = num.toFixed(2); // result will equal 10.00
num = 930.9805; result = num.toFixed(3); // result will equal 930.981
num = 500.2349; result = num.toPrecision(4); // result will equal 500.2
num = 5000.2349; result = num.toPrecision(4); // result will equal 5000
num = 555.55; result = num.toPrecision(2); // result will equal 5.6e+2
num = 555.55; result = num.toPrecision(6); // result will equal 555.550
29
Web Programming 20:57 lec6 Dr Walid M. Aly

You might also like