Javascript Objects By: Jalpesh Vasa
• Objects are composed of attributes. If an attribute contains a function, it is considered to be a method of the object otherwise, the attribute is considered a property. • Object Properties: – Object properties can be any of the three primitive data types, or any of the abstract data types, such as another object. – objectName.objectProperty = propertyValue; – var str = document.title; • Object Methods: – The methods are functions that let the object do something or let something be done to it. There is little difference between a function and a method, except that a function is a standalone unit of statements and a method is attached to an object and can be referenced by the this keyword – Following is a simple example to show how to use write() method of document object to write any content on the document: – document.write("This is test"); • The new Operator: – The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method. – var books = new Array("C++", "Perl", "Java"); – var day = new Date("August 15, 1947"); 11-Apr-19 2
• Example: point = new Object(); point.x=17; point.y=22; alert(point.x+' : '+point.y) // Would alert: 17 : 22 • Example: <script type="text/javascript"> var book = new Object(); // Create the object book.subject = "Perl"; // Assign properties to the object book.author = "Mohit"; </script> </head> <body> <script type="text/javascript"> document.write("Book name is : " + book.subject + "<br>"); document.write("Book author is : " + book.author + "<br>"); </script> // would print Book name is: perl Book author: Mohit 11-Apr-19 3
• Example: This example demonstrates how to create an object with a User-Defined Function. Here this keyword is used to refer to the object that has been passed to a function: <script type="text/javascript"> function book(title, author){ this.title = title; this.author = author; } </script> </head> <body> <script type="text/javascript"> var myBook = new book("Perl", “abcd"); document.write("Book title is : " + myBook.title + "<br>"); document.write("Book author is : " + myBook.author + "<br>"); </script> 11-Apr-19 4
• Example: Here is a simple example to show how to add a function along with an object: <script type="text/javascript"> // Define a function which will work as a method function addPrice(amount){ this.price = amount; } function book(title, author){ this.title = title; this.author = author; this.addPrice = addPrice; // Assign that method as property. } </script> </head> <body> <script type="text/javascript"> var myBook = new book("Perl", "Mohtashim"); myBook.addPrice(100); document.write("Book title is : " + myBook.title + "<br>"); document.write("Book author is : " + myBook.author + "<br>"); document.write("Book price is : " + myBook.price + "<br>"); </script> 11-Apr-19 5
• Example: Here is a simple example to show how to add a function along with an object: <script type="text/javascript"> // Define a function which will work as a method function addPrice(amount){ this.price = amount; } function book(title, author){ this.title = title; this.author = author; this.addPrice = addPrice; // Assign that method as property. } </script> </head> <body> <script type="text/javascript"> var myBook = new book("Perl", "Mohtashim"); myBook.addPrice(100); document.write("Book title is : " + myBook.title + "<br>"); document.write("Book author is : " + myBook.author + "<br>"); document.write("Book price is : " + myBook.price + "<br>"); </script> 11-Apr-19 6
Javascript NUMBER Objects
• JavaScript has only one type of number. • Numbers can be written with, or without decimals. • All JavaScript Numbers are 64-bit • The Number object represents numerical date, either integers or floating-point numbers. • var val = new Number(number); • Number Properties: 11-Apr-19 8
• Number Properties: function showValue() { var smallNumber = (-Number.MAX_VALUE) * 2 if (smallNumber == Number.NEGATIVE_INFINITY) { alert("Value of smallNumber : " + smallNumber ); } } Value of val : -Infinity function showValue() { var bigNumber = Number.MAX_VALUE * 2 if (bigNumber == Number.POSITIVE_INFINITY) { alert("Value of bigNumber : " + bigNumber ); } } Value of val : Infinity 11-Apr-19 9
• Number Properties: function showValue() { var val = Number.MAX_VALUE; alert("Value of Number.MAX_VALUE : " + val ); } Value of Number.MAX_VALUE : 1.7976931348623157 x 10308 function showValue() { var val = Number.MIN_VALUE; alert("Value of Number.MIN_VALUE : " + val ); } Value of Number.MIN_VALUE : 5 x 10-324 11-Apr-19 10
• Number Properties: function showValue() { var dayOfMonth = 50; if (dayOfMonth < 1 || dayOfMonth > 31) { dayOfMonth = Number.NaN alert("Day of Month must be between 1 and 31.") } alert("Value of dayOfMonth : " + dayOfMonth ); } Day of Month must be between 1 and 31. Value of dayOfMonth : NaN 11-Apr-19 11
• Example // The following example creates a Number object, myNum, // then adds a description property to all Number objects. // Then a value is assigned to the myNum object's description property. myNum = new Number(65); Number.prototype.description=null; myNum.description="wind speed" alert('The '+myNum.description+' is: '+myNum); // Would alert: The wind speed is 65 11-Apr-19 12
• Number methods: 11-Apr-19 13
Example: <script type="text/javascript"> var num=77.1234; var val = num.toExponential(); document.write("num.toExponential() is : " + val ); document.write("<br />"); val = num.toExponential(4); document.write("num.toExponential(4) is : " + val ); document.write("<br />"); val = num.toExponential(2); document.write("num.toExponential(2) is : " + val); document.write("<br />"); val = 77.1234.toExponential(); document.write("77.1234.toExponential()is : " + val ); document.write("<br />"); val = 77.1234.toExponential(); document.write("77 .toExponential() is : " + val); </script> num.toExponential() is : 7.71234e+1 num.toExponential(4) is : 7.7123e+1 num.toExponential(2) is : 7.71e+1 77.1234.toExponential()is:7.71234e+1 77 .toExponential() is : 7.71234e+1 11-Apr-19 14
Javascript Date Objects
• The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ) • Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields • Syntax 1 var myDate = new Date() Syntax 2 var myDate = new Date([parameters]) Syntax 3 var myDate = new Date(dateString) Syntax 4 var myDate = new Date("month dd, yyyy") Syntax 5 var myDate = new Date("month dd, yyyy hh:mm:ss") Syntax 6 var myDate = new Date(yy, mm, dd) Syntax 7 var myDate = new Date(yy, mm, dd, hh, mm, ss) Syntax 8 var myDate = new Date("miliseconds") 11-Apr-19 16
• Example 1 : var myDate=new Date(); alert('Right now it is: '+myDate.toLocaleString()); Example 2 : myDate = new Date("October 13, 1966 13:35:00"); weekdays=new Array('Sun','Mon','Tues','Wednes','Thurs','Fri','Satur'); alert('I was born a '+weekdays[myDate.getDay()]+'day.'); Example 3 : // Note: October is month number 9! (Cause January is 0) // The reason for this is that it fits well for Arrays, // cause first item in an Array is item number zero. // Look at this example: myDate = new Date(1966,9,13); months=new Array('Jan','Feb','Mar','Apr','May','June', 'July','Aug','Sep','Oct','Nov','Dec'); alert('I was born in '+months[myDate.getMonth()]); 11-Apr-19 17
• Example 4 : myDate = new Date(1966,9,13,13,35,0); nowDate = new Date(); milliseconds=nowDate.getTime()-myDate.getTime(); days=Math.floor(milliseconds/(1000*60*60*24)); alert('I have lived for '+days+' days.'); Example 5 : myDate = new Date(1966,9,13,13,35,0); nowDate = new Date(); milliseconds=nowDate.getTime()-myDate.getTime(); hours=Math.floor(milliseconds/(1000*60*60)); alert('I have lived for '+hours+' hours.'); Example 6 : nowDate = new Date(); xmasDate = new Date(nowDate.getYear(),11,24); milliseconds=xmasDate.getTime()-nowDate.getTime(); days=Math.floor(milliseconds/(1000*60*60*24)); alert('There are '+days+' days left till christmas eve.'); 11-Apr-19 18
Javascript Math Objects
• The math object provides you properties and methods for mathematical constants and functions. • Unlike the other global objects, 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. • Syntax 1 Math.property(value) Syntax 2 Math.method(value) • Properties: E Euler's constant and the base of natural logarithms, approximately 2.718. LN2 Natural logarithm of 2, approximately 0.693. LN10 Natural logarithm of 10, approximately 2.302. LOG2E Base 2 logarithm of E, approximately 1.442. LOG10E Base 10 logarithm of E, approximately 0.434. PI Ratio of the circumference of a circle to its diameter, approximately 3.14159. SQRT1_2 Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707. SQRT2 Square root of 2, approximately 1.414. 11-Apr-19 20
• Properties Example: var property_value = Math.LN2 (0.693) var property_value = Math.E (Euler’s Constant – 2.718) var property_value = Math.LN10 (2.302) var property_value = Math.LOG2E (1.442) var property_value = Math.LOG10E (0.434) var property_value = Math.PI (3.141) 11-Apr-19 21
• Methods: abs() Returns the absolute value of a number. acos() Returns the arccosine (in radians) of a number. asin() Returns the arcsine (in radians) of a number. atan() Returns the arctangent (in radians) of a number. atan2() Returns the arctangent of the quotient of its arguments. ceil() Returns the smallest integer greater than or equal to a number. cos() Returns the cosine of a number. exp() Returns EN, where N is the argument, and E is Euler's constant, the base of the natural logarithm. floor() Returns the largest integer less than or equal to a number. log() Returns the natural logarithm (base E) of a number. max() Returns the largest of zero or more numbers. min() Returns the smallest of zero or more numbers. pow() Returns base to the exponent power, that is, base exponent. random() Returns a pseudo-random number between 0 and 1. round() Returns the value of a number rounded to the nearest integer. sin() Returns the sine of a number. sqrt() Returns the square root of a number. tan() Returns the tangent of a number. 11-Apr-19 22
• Methods Example: var value = Math.abs(-1); (1) var value = Math.abs(null); (0) var value = Math.abs(20); (20) var value = Math.abs("string"); (NaN) var value = Math.ceil(45.95); (46) var value = Math.ceil(45.20); (46) var value = Math.ceil(-45.95); (-45) var value = Math.ceil(-45.20); (-45) var value = Math.max(10, 20, -1, 100); (100) var value = Math.max(-1, -3, -40); (-1) var value = Math.max(0, -1); (0) var value = Math.max(100); (100) 11-Apr-19 23
JavaScript RegExp Object
• What is RegExp?  When you search in a text, you can use a pattern to describe what you are searching for.  A simple pattern can be one single character.  Regular expressions are very powerful tools for performing pattern matches.  You can perform complex tasks that once required lengthy procedures with just a few lines of code using regular expressions  A more complicated pattern can consist of more characters, and can be used for parsing, format checking, substitution and more.  Regular expressions are used to perform powerful pattern-matching and "search-and-replace" functions on text.  A regular expression is an object that describes a pattern of characters. 11-Apr-19 25
• Syntax: var pattern = new RegExp(pattern, attributes); or simply var pattern = /pattern/attributes(modifiers); • pattern: A string that specifies the pattern of the regular expression or another regular expression. • attributes: An optional string containing any of the "g", "i", and "m" attributes that specify global, case-insensitive, and multiline matches, respectively. • Modifiers are used to perform case-insensitive and global searches. • The i modifier is used to perform case-insensitive matching. • The g modifier is used to perform a global match (find all matches rather than stopping after the first match). 11-Apr-19 26
• Examples: <script> var str = "Visit Mypage"; var patt1 = /mypage/i; document.write(str.match(patt1)); </script> <script> var str="Is this all there is?"; var patt1=/is/g; document.write(str.match(patt1)); </script> <script> var str="Is this all there is?"; var patt1=/is/gi; document.write(str.match(patt1)); </script> Mypage is,is Is,is,is 11-Apr-19 27
11-Apr-19 28
<script> var str="Hello world!"; //look for "Hello" var patt=/Hello/g; var result=patt.test(str); document.write("Returned value: " + result); //look for “good" patt=/good/g; result=patt.test(str); document.write("<br>Returned value: " + result); </script> Returned value: true Returned value: false <script> var str="Hello world!"; //look for "Hello" var patt=/Hello/g; var result=patt.exec(str); document.write("Returned value: " + result); //look for "W3Schools" patt=/W3Schools/g; result=patt.exec(str); document.write("<br>Returned value: " + result); </script> Returned value: Hello Returned value: null 11-Apr-19 29
11-Apr-19 30
11-Apr-19 31
11-Apr-19 32
<script> var str="Is this all there is?"; var patt1=/[a-h]/g; document.write(str.match(patt1)); </script> h,a,h,e,e <script> var str="Is this all there is?"; var patt1=/[^a-h]/g; document.write(str.match(patt1)); </script> I,s, ,t,i,s, ,l,l, ,t,r, ,i,s,? <script> var str="Give 100%!"; var patt1=/w/g; document.write(str.match(patt1)); </script> G,i,v,e,1,0,0 <script> var str="Give 100%!"; var patt1=/W/g; document.write(str.match(patt1)); </script> ,%,! 11-Apr-19 33
<script language="JavaScript1.2"> function checkpostal() { var re5digit=/^d{5}$/ //regular expression defining a 5 digit number if (document.myform.myinput.value.search(re5digit)==-1) //if match failed alert("Please enter a valid 5 digit number inside form") } </script> <form name="myform"> <input type="text" name="myinput" size=15> <input type="button" onClick="checkpostal()" value="check"> </form> •^ indicates the beginning of the string. Using a ^ metacharacter requires that the match start at the beginning. •d indicates a digit character and the {5} following it means that there must be 5 consecutive digit characters. •$ indicates the end of the string. Using a $ metacharacter requires that the match end at the end of the string. 11-Apr-19 34
var string1="Peter has 8 dollars and Jane has 15" parsestring1=string1.match(/d+/g) //returns the array [8,15] var string2="(304)434-5454" parsestring2=string2.replace(/[()-]/g, "") //Returns "3044345454" (removes "(", ")", and "- ") var string3="1,2, 3, 4, 5" parsestring3=string3.split(/s*,s*/) //Returns the array ["1","2","3","4","5"]11-Apr-19 35
<script type="text/javascript"> function validateEmail(email) { var reg = /^w+([-+.']w+)*@w+([-.]w+)*.w+([-.]w+)*$/ if (reg.test(email)){ return true; } else{ return false; } } </script> /^[a-zA-Z]*$/ 11-Apr-19 36
HTML DOM 11-Apr-19 37
• With the HTML DOM, JavaScript can access all the elements of an HTML document. • What is the Document Object Model?  The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.  It defines the logical structure of documents and the way a document is accessed and manipulated. In the DOM specification, the term "document" is used in the broad sense.  With the Document Object Model, programmers can create and build documents, navigate their structure, and add, modify, or delete elements and content. Anything found in an HTML or XML document can be accessed, changed, deleted, or added using the Document Object Model, with a few exceptions  The Document Object Model (DOM) is the model that describes how all elements in an HTML page, like input fields, images, paragraphs etc., are related to the topmost structure: the document itself. By calling the element by its proper DOM name, we can influence it.11-Apr-19 38
• With a programmable object model, JavaScript gets all the power it needs to create dynamic HTML:  JavaScript can change all the HTML elements in the page  JavaScript can change all the HTML attributes in the page  JavaScript can change all the CSS styles in the page  JavaScript can react to all the events in the page  JavaScript can remove existing HTML elements and attributes  JavaScript can add new HTML elements and attributes  JavaScript can create new HTML events in the page HTML DOM defines: The HTML elements as objects The properties of all HTML elements The methods to access all HTML elements The events for all HTML element 11-Apr-19 39
HTML DOM Methods • HTML DOM methods are actions you can perform (on HTML Elements). • HTML DOM properties are values (of HTML Elements) that you can set or change. • document.getElementById("demo").innerHTML = "Hello World!"; 11-Apr-19 40
HTML DOM Document Object • Adding and Deleting Elements • Adding Events Handlers Method Description document.createElement(element) Create an HTML element document.removeChild(element) Remove an HTML element document.appendChild(element) Add an HTML element document.replaceChild(new, old) Replace an HTML element document.write(text) Write into the HTML output stream Method Description document.getElementById(id).onclick = function(){code} Adding event handler code to an onclick event 11-Apr-19 41
HTML DOM Document Object • Finding HTML Elements • Changing HTML Elements document.getElementById(id) Find an element by element id document.getElementsByTagName(name) Find elements by tag name document.getElementsByClassName(name) Find elements by class name Property Description element.innerHTML = new html content Change the inner HTML of an element element.attribute= new value Change the attribute value of an HTML element element.style.property= new style Change the style of an HTML element Method Description element.setAttribute(attribute, value) Change the attribute value of an HTML element 11-Apr-19 42
HTML DOM Elements • Finding HTML Elements – Often, with JavaScript, you want to manipulate HTML elements. • Finding HTML elements by id • Finding HTML elements by tag name • Finding HTML elements by class name • Finding HTML elements by CSS selectors • Finding HTML elements by HTML object collections • var myElement = document.getElementById("intro"); • var x = document.getElementsByTagName("p"); 11-Apr-19 43
• Nodes  In the Level 1 DOM, each object, whatever it may be exactly, is a Node. So if you do <P>This is a paragraph</P>  you have created two nodes: an element P and a text node with content 'This is a paragraph'. The text node is inside the element, so it is considered a child node of the element. <P> <-- element node | | This is a paragraph <-- text node  <P>This is a <B>paragraph</B></P> <P> | -------------- | | This is a <B> | | paragraph 11-Apr-19 44
11-Apr-19 45
To do so, you have to find the elements first. There are a couple of ways to do this:  Finding HTML elements by id  Finding HTML elements by tag name  Finding HTML elements by class name The following HTML objects (and object collections) are also accessible: document.anchors document.body document.documentElement document.embeds document.forms document.head document.images document.links document.scripts document.title (1) <body> <p id="intro">Hello World!</p> <p>This example demonstrates the <b>getElementById</b> method!</p> <script> x=document.getElementById("intro"); document.write("<p>The text from the intro paragraph: " + x.innerHTML + "</p>"); </script> 11-Apr-19 46
(2) <body> <p>Hello World!</p> <div id="main"> <p>The DOM is very useful.</p> <p>This example demonstrates the <b>getElementsByTagName</b> method</p> </div> <script> var x=document.getElementById("main"); var y=x.getElementsByTagName("p"); document.write('First paragraph inside "main" is ' + y[0].innerHTML); </script> </body> (3) <p id="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML="New text!"; </script> <p>The paragraph above was changed by a script.</p> 11-Apr-19 47
(5) <body> <img id="image" src="smiley.gif" width="160" height="120"> <script> document.getElementById("image").src="landscape.jpg"; </script> <p>The original image was smiley.gif, but the script changed it to landscape.jpg</p> </body> The HTML document above contains an <img> element with id="image" We use the HTML DOM to get the element with id="image" A JavaScript changes the src attribute of that element from "smiley.gif" to "landscape.jpg“ (6) <p id="p1">Hello World!</p> <p id="p2">Hello World!</p> <script> document.getElementById("p2").style.color="blue"; document.getElementById("p2").style.fontFamily="Arial"; document.getElementById("p2").style.fontSize="larger"; </script> <p>The paragraph above was changed by a script.</p> 11-Apr-19 48
(7) <body> <h1 id="id1">My Heading 1</h1> <button type="button" onclick="document.getElementById('id1').style.color='red'"> Click Me!</button> </body> (8) <p>Hello World!</p> <p class="intro">The DOM is very useful.</p> <p class="intro">This example demonstrates the <b>getElementsByClassName</b> method.</p> <p id="demo"></p> <script> var x = document.getElementsByClassName("intro"); document.getElementById("demo").innerHTML = 'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML; </script> 11-Apr-19 49
(9) <body> <form id="frm1" action="/action_page.php"> First name: <input type="text" name="fname" value="Donald"><br> Last name: <input type="text" name="lname" value="Duck"><br><br> <input type="submit" value="Submit"> </form> <p>Click "Try it" to display the value of each element in the form.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var x = document.forms["frm1"]; var text = ""; var i; for (i = 0; i < x.length ;i++) { text += x.elements[i].value + "<br>"; } document.getElementById("demo").innerHTML = text; } </script> </body> 11-Apr-19 50
HTML DOM Events • Reacting to Events • A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element. • To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute: onclick = JS • HTML events: • When a user clicks the mouse • When a web page has loaded • When an image has been loaded • When the mouse moves over an element • When an input field is changed • When an HTML form is submitted • When a user strokes a key11-Apr-19 51
Example (1) <body> <h1 onclick="this.innerHTML = 'Ooops!'">Click on this text!</h1> </body> (2) <body> <h1 onclick="changeText(this)">Click on this text!</h1> <script> function changeText(id) { id.innerHTML = "Ooops!"; } </script> </body> 11-Apr-19 52
Example (3) <body> <p>Click the button to display the date.</p> <button onclick="displayDate()">The time is?</button> <script> function displayDate() { document.getElementById("demo").in nerHTML = Date(); } </script> <p id="demo"></p></body> (4) <body> <p>Click "Try it" to execute the displayDate() function.</p> <button id="myBtn">Try it</button> <p id="demo"></p> <script> document.getElementById("myBtn").o nclick = displayDate; function displayDate() { document.getElementById("demo").in nerHTML = Date(); } </script></body> 11-Apr-19 53
Example <body onload="checkCookies()"> <p id="demo"></p> <script> function checkCookies() { var text = ""; if (navigator.cookieEnabled == true) { text = "Cookies are enabled."; } else { text = "Cookies are not enabled."; } document.getElementById("demo").in nerHTML = text; } </script></body> <script> function myFunction() { var x = document.getElementById("fname"); x.value = x.value.toUpperCase(); } </script> </head> <body> Enter your name: <input type="text" id="fname" onchange="myFunction()"> </body> 11-Apr-19 54
Example <body> <div onmouseover="mOver(this)" onmouseout="mOut(this)" style="background- color:#D94A38;width:120px;height:20 px;padding:40px;"> Mouse Over Me</div> <script> function mOver(obj) { obj.innerHTML = "Thank You" } function mOut(obj) { obj.innerHTML = "Mouse Over Me" } </script></body> <div onmousedown="mDown(this)" onmouseup="mUp(this)" style="background- color:#D94A38;width:90px;height:20px;p adding:40px;"> Click Me</div> <script> function mDown(obj) { obj.style.backgroundColor = "#1ec5e5"; obj.innerHTML = "Release Me"; } function mUp(obj) { obj.style.backgroundColor="#D94A38"; obj.innerHTML="Thank You"; } </script>11-Apr-19 55
Example <form id="myForm" action="#"> First name: <input type="text" name="fname" value="Donald"><br> Last name: <input type="text" name="lname" value="Duck"><br> <input type="submit" value="Submit"> </form> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var x = document.getElementById("myForm").elements[0].value; document.getElementById("demo").innerHTML = x;} </script> 11-Apr-19 56
JavaScript Window Object 11-Apr-19 57
• The window object is supported by all browsers. It represent the browser's window. • All global JavaScript objects, functions, and variables automatically become members of the window object. • Global variables are properties of the window object. • Global functions are methods of the window object. 11-Apr-19 58
Window Screen • The window.screen object can be written without the window prefix. Some properties: • screen.availWidth - available screen width • screen.availHeight - available screen height <script> document.write("Available Width: " + screen.availWidth); </script> The output of the code above will be: Available Width: 1366 11-Apr-19 59
Window Location • The window.location object can be written without the window prefix. Some examples: • location.hostname returns the domain name of the web host • location.pathname returns the path and filename of the current page • location.port returns the port of the web host (80 or 443) • location.protocol returns the web protocol used (http:// or https://) 11-Apr-19 60
The location.assign() method loads a new document. <html> <head> <script> function newDoc() { window.location.assign(“C:Documents and SettingsAdministratorDesktopa1.html") } </script> </head> <body> <input type="button" value="Load new document" onclick="newDoc()"> </body> </html> 11-Apr-19 61
Window History • The window.history object can be written without the window prefix. • To protect the privacy of the users, there are limitations to how JavaScript can access this object. Some methods: • history.back() - same as clicking back in the browser • history.forward() - same as clicking forward in the browser <html> <head> <script> function goBack() { window.history.back() } </script> </head> <body> <input type="button" value="Back" onclick="goBack()“> </body> </html> 11-Apr-19 62
Window Navigator • The window.navigator object contains information about the visitor's browser. <div id="example"></div> <script> txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>"; txt+= "<p>Browser Name: " + navigator.appName + "</p>"; txt+= "<p>Browser Version: " + navigator.appVersion + "</p>"; txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>"; txt+= "<p>Platform: " + navigator.platform + "</p>"; txt+= "<p>User-agent header: " + navigator.userAgent + "</p>"; txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>"; document.getElementById("example").innerHTML=txt; </script> 11-Apr-19 63

3.1 javascript objects_DOM

  • 1.
  • 2.
    • Objects arecomposed of attributes. If an attribute contains a function, it is considered to be a method of the object otherwise, the attribute is considered a property. • Object Properties: – Object properties can be any of the three primitive data types, or any of the abstract data types, such as another object. – objectName.objectProperty = propertyValue; – var str = document.title; • Object Methods: – The methods are functions that let the object do something or let something be done to it. There is little difference between a function and a method, except that a function is a standalone unit of statements and a method is attached to an object and can be referenced by the this keyword – Following is a simple example to show how to use write() method of document object to write any content on the document: – document.write("This is test"); • The new Operator: – The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method. – var books = new Array("C++", "Perl", "Java"); – var day = new Date("August 15, 1947"); 11-Apr-19 2
  • 3.
    • Example: point =new Object(); point.x=17; point.y=22; alert(point.x+' : '+point.y) // Would alert: 17 : 22 • Example: <script type="text/javascript"> var book = new Object(); // Create the object book.subject = "Perl"; // Assign properties to the object book.author = "Mohit"; </script> </head> <body> <script type="text/javascript"> document.write("Book name is : " + book.subject + "<br>"); document.write("Book author is : " + book.author + "<br>"); </script> // would print Book name is: perl Book author: Mohit 11-Apr-19 3
  • 4.
    • Example: This exampledemonstrates how to create an object with a User-Defined Function. Here this keyword is used to refer to the object that has been passed to a function: <script type="text/javascript"> function book(title, author){ this.title = title; this.author = author; } </script> </head> <body> <script type="text/javascript"> var myBook = new book("Perl", “abcd"); document.write("Book title is : " + myBook.title + "<br>"); document.write("Book author is : " + myBook.author + "<br>"); </script> 11-Apr-19 4
  • 5.
    • Example: Here isa simple example to show how to add a function along with an object: <script type="text/javascript"> // Define a function which will work as a method function addPrice(amount){ this.price = amount; } function book(title, author){ this.title = title; this.author = author; this.addPrice = addPrice; // Assign that method as property. } </script> </head> <body> <script type="text/javascript"> var myBook = new book("Perl", "Mohtashim"); myBook.addPrice(100); document.write("Book title is : " + myBook.title + "<br>"); document.write("Book author is : " + myBook.author + "<br>"); document.write("Book price is : " + myBook.price + "<br>"); </script> 11-Apr-19 5
  • 6.
    • Example: Here isa simple example to show how to add a function along with an object: <script type="text/javascript"> // Define a function which will work as a method function addPrice(amount){ this.price = amount; } function book(title, author){ this.title = title; this.author = author; this.addPrice = addPrice; // Assign that method as property. } </script> </head> <body> <script type="text/javascript"> var myBook = new book("Perl", "Mohtashim"); myBook.addPrice(100); document.write("Book title is : " + myBook.title + "<br>"); document.write("Book author is : " + myBook.author + "<br>"); document.write("Book price is : " + myBook.price + "<br>"); </script> 11-Apr-19 6
  • 7.
  • 8.
    • JavaScript hasonly one type of number. • Numbers can be written with, or without decimals. • All JavaScript Numbers are 64-bit • The Number object represents numerical date, either integers or floating-point numbers. • var val = new Number(number); • Number Properties: 11-Apr-19 8
  • 9.
    • Number Properties: functionshowValue() { var smallNumber = (-Number.MAX_VALUE) * 2 if (smallNumber == Number.NEGATIVE_INFINITY) { alert("Value of smallNumber : " + smallNumber ); } } Value of val : -Infinity function showValue() { var bigNumber = Number.MAX_VALUE * 2 if (bigNumber == Number.POSITIVE_INFINITY) { alert("Value of bigNumber : " + bigNumber ); } } Value of val : Infinity 11-Apr-19 9
  • 10.
    • Number Properties: functionshowValue() { var val = Number.MAX_VALUE; alert("Value of Number.MAX_VALUE : " + val ); } Value of Number.MAX_VALUE : 1.7976931348623157 x 10308 function showValue() { var val = Number.MIN_VALUE; alert("Value of Number.MIN_VALUE : " + val ); } Value of Number.MIN_VALUE : 5 x 10-324 11-Apr-19 10
  • 11.
    • Number Properties: functionshowValue() { var dayOfMonth = 50; if (dayOfMonth < 1 || dayOfMonth > 31) { dayOfMonth = Number.NaN alert("Day of Month must be between 1 and 31.") } alert("Value of dayOfMonth : " + dayOfMonth ); } Day of Month must be between 1 and 31. Value of dayOfMonth : NaN 11-Apr-19 11
  • 12.
    • Example // Thefollowing example creates a Number object, myNum, // then adds a description property to all Number objects. // Then a value is assigned to the myNum object's description property. myNum = new Number(65); Number.prototype.description=null; myNum.description="wind speed" alert('The '+myNum.description+' is: '+myNum); // Would alert: The wind speed is 65 11-Apr-19 12
  • 13.
  • 14.
    Example: <script type="text/javascript"> var num=77.1234; varval = num.toExponential(); document.write("num.toExponential() is : " + val ); document.write("<br />"); val = num.toExponential(4); document.write("num.toExponential(4) is : " + val ); document.write("<br />"); val = num.toExponential(2); document.write("num.toExponential(2) is : " + val); document.write("<br />"); val = 77.1234.toExponential(); document.write("77.1234.toExponential()is : " + val ); document.write("<br />"); val = 77.1234.toExponential(); document.write("77 .toExponential() is : " + val); </script> num.toExponential() is : 7.71234e+1 num.toExponential(4) is : 7.7123e+1 num.toExponential(2) is : 7.71e+1 77.1234.toExponential()is:7.71234e+1 77 .toExponential() is : 7.71234e+1 11-Apr-19 14
  • 15.
  • 16.
    • The Dateobject is a datatype built into the JavaScript language. Date objects are created with the new Date( ) • Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields • Syntax 1 var myDate = new Date() Syntax 2 var myDate = new Date([parameters]) Syntax 3 var myDate = new Date(dateString) Syntax 4 var myDate = new Date("month dd, yyyy") Syntax 5 var myDate = new Date("month dd, yyyy hh:mm:ss") Syntax 6 var myDate = new Date(yy, mm, dd) Syntax 7 var myDate = new Date(yy, mm, dd, hh, mm, ss) Syntax 8 var myDate = new Date("miliseconds") 11-Apr-19 16
  • 17.
    • Example 1: var myDate=new Date(); alert('Right now it is: '+myDate.toLocaleString()); Example 2 : myDate = new Date("October 13, 1966 13:35:00"); weekdays=new Array('Sun','Mon','Tues','Wednes','Thurs','Fri','Satur'); alert('I was born a '+weekdays[myDate.getDay()]+'day.'); Example 3 : // Note: October is month number 9! (Cause January is 0) // The reason for this is that it fits well for Arrays, // cause first item in an Array is item number zero. // Look at this example: myDate = new Date(1966,9,13); months=new Array('Jan','Feb','Mar','Apr','May','June', 'July','Aug','Sep','Oct','Nov','Dec'); alert('I was born in '+months[myDate.getMonth()]); 11-Apr-19 17
  • 18.
    • Example 4: myDate = new Date(1966,9,13,13,35,0); nowDate = new Date(); milliseconds=nowDate.getTime()-myDate.getTime(); days=Math.floor(milliseconds/(1000*60*60*24)); alert('I have lived for '+days+' days.'); Example 5 : myDate = new Date(1966,9,13,13,35,0); nowDate = new Date(); milliseconds=nowDate.getTime()-myDate.getTime(); hours=Math.floor(milliseconds/(1000*60*60)); alert('I have lived for '+hours+' hours.'); Example 6 : nowDate = new Date(); xmasDate = new Date(nowDate.getYear(),11,24); milliseconds=xmasDate.getTime()-nowDate.getTime(); days=Math.floor(milliseconds/(1000*60*60*24)); alert('There are '+days+' days left till christmas eve.'); 11-Apr-19 18
  • 19.
  • 20.
    • The mathobject provides you properties and methods for mathematical constants and functions. • Unlike the other global objects, 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. • Syntax 1 Math.property(value) Syntax 2 Math.method(value) • Properties: E Euler's constant and the base of natural logarithms, approximately 2.718. LN2 Natural logarithm of 2, approximately 0.693. LN10 Natural logarithm of 10, approximately 2.302. LOG2E Base 2 logarithm of E, approximately 1.442. LOG10E Base 10 logarithm of E, approximately 0.434. PI Ratio of the circumference of a circle to its diameter, approximately 3.14159. SQRT1_2 Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707. SQRT2 Square root of 2, approximately 1.414. 11-Apr-19 20
  • 21.
    • Properties Example: varproperty_value = Math.LN2 (0.693) var property_value = Math.E (Euler’s Constant – 2.718) var property_value = Math.LN10 (2.302) var property_value = Math.LOG2E (1.442) var property_value = Math.LOG10E (0.434) var property_value = Math.PI (3.141) 11-Apr-19 21
  • 22.
    • Methods: abs() Returnsthe absolute value of a number. acos() Returns the arccosine (in radians) of a number. asin() Returns the arcsine (in radians) of a number. atan() Returns the arctangent (in radians) of a number. atan2() Returns the arctangent of the quotient of its arguments. ceil() Returns the smallest integer greater than or equal to a number. cos() Returns the cosine of a number. exp() Returns EN, where N is the argument, and E is Euler's constant, the base of the natural logarithm. floor() Returns the largest integer less than or equal to a number. log() Returns the natural logarithm (base E) of a number. max() Returns the largest of zero or more numbers. min() Returns the smallest of zero or more numbers. pow() Returns base to the exponent power, that is, base exponent. random() Returns a pseudo-random number between 0 and 1. round() Returns the value of a number rounded to the nearest integer. sin() Returns the sine of a number. sqrt() Returns the square root of a number. tan() Returns the tangent of a number. 11-Apr-19 22
  • 23.
    • Methods Example: varvalue = Math.abs(-1); (1) var value = Math.abs(null); (0) var value = Math.abs(20); (20) var value = Math.abs("string"); (NaN) var value = Math.ceil(45.95); (46) var value = Math.ceil(45.20); (46) var value = Math.ceil(-45.95); (-45) var value = Math.ceil(-45.20); (-45) var value = Math.max(10, 20, -1, 100); (100) var value = Math.max(-1, -3, -40); (-1) var value = Math.max(0, -1); (0) var value = Math.max(100); (100) 11-Apr-19 23
  • 24.
  • 25.
    • What isRegExp?  When you search in a text, you can use a pattern to describe what you are searching for.  A simple pattern can be one single character.  Regular expressions are very powerful tools for performing pattern matches.  You can perform complex tasks that once required lengthy procedures with just a few lines of code using regular expressions  A more complicated pattern can consist of more characters, and can be used for parsing, format checking, substitution and more.  Regular expressions are used to perform powerful pattern-matching and "search-and-replace" functions on text.  A regular expression is an object that describes a pattern of characters. 11-Apr-19 25
  • 26.
    • Syntax: var pattern= new RegExp(pattern, attributes); or simply var pattern = /pattern/attributes(modifiers); • pattern: A string that specifies the pattern of the regular expression or another regular expression. • attributes: An optional string containing any of the "g", "i", and "m" attributes that specify global, case-insensitive, and multiline matches, respectively. • Modifiers are used to perform case-insensitive and global searches. • The i modifier is used to perform case-insensitive matching. • The g modifier is used to perform a global match (find all matches rather than stopping after the first match). 11-Apr-19 26
  • 27.
    • Examples: <script> var str= "Visit Mypage"; var patt1 = /mypage/i; document.write(str.match(patt1)); </script> <script> var str="Is this all there is?"; var patt1=/is/g; document.write(str.match(patt1)); </script> <script> var str="Is this all there is?"; var patt1=/is/gi; document.write(str.match(patt1)); </script> Mypage is,is Is,is,is 11-Apr-19 27
  • 28.
  • 29.
    <script> var str="Hello world!"; //lookfor "Hello" var patt=/Hello/g; var result=patt.test(str); document.write("Returned value: " + result); //look for “good" patt=/good/g; result=patt.test(str); document.write("<br>Returned value: " + result); </script> Returned value: true Returned value: false <script> var str="Hello world!"; //look for "Hello" var patt=/Hello/g; var result=patt.exec(str); document.write("Returned value: " + result); //look for "W3Schools" patt=/W3Schools/g; result=patt.exec(str); document.write("<br>Returned value: " + result); </script> Returned value: Hello Returned value: null 11-Apr-19 29
  • 30.
  • 31.
  • 32.
  • 33.
    <script> var str="Is thisall there is?"; var patt1=/[a-h]/g; document.write(str.match(patt1)); </script> h,a,h,e,e <script> var str="Is this all there is?"; var patt1=/[^a-h]/g; document.write(str.match(patt1)); </script> I,s, ,t,i,s, ,l,l, ,t,r, ,i,s,? <script> var str="Give 100%!"; var patt1=/w/g; document.write(str.match(patt1)); </script> G,i,v,e,1,0,0 <script> var str="Give 100%!"; var patt1=/W/g; document.write(str.match(patt1)); </script> ,%,! 11-Apr-19 33
  • 34.
    <script language="JavaScript1.2"> function checkpostal() { varre5digit=/^d{5}$/ //regular expression defining a 5 digit number if (document.myform.myinput.value.search(re5digit)==-1) //if match failed alert("Please enter a valid 5 digit number inside form") } </script> <form name="myform"> <input type="text" name="myinput" size=15> <input type="button" onClick="checkpostal()" value="check"> </form> •^ indicates the beginning of the string. Using a ^ metacharacter requires that the match start at the beginning. •d indicates a digit character and the {5} following it means that there must be 5 consecutive digit characters. •$ indicates the end of the string. Using a $ metacharacter requires that the match end at the end of the string. 11-Apr-19 34
  • 35.
    var string1="Peter has8 dollars and Jane has 15" parsestring1=string1.match(/d+/g) //returns the array [8,15] var string2="(304)434-5454" parsestring2=string2.replace(/[()-]/g, "") //Returns "3044345454" (removes "(", ")", and "- ") var string3="1,2, 3, 4, 5" parsestring3=string3.split(/s*,s*/) //Returns the array ["1","2","3","4","5"]11-Apr-19 35
  • 36.
    <script type="text/javascript"> function validateEmail(email) { varreg = /^w+([-+.']w+)*@w+([-.]w+)*.w+([-.]w+)*$/ if (reg.test(email)){ return true; } else{ return false; } } </script> /^[a-zA-Z]*$/ 11-Apr-19 36
  • 37.
  • 38.
    • With theHTML DOM, JavaScript can access all the elements of an HTML document. • What is the Document Object Model?  The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.  It defines the logical structure of documents and the way a document is accessed and manipulated. In the DOM specification, the term "document" is used in the broad sense.  With the Document Object Model, programmers can create and build documents, navigate their structure, and add, modify, or delete elements and content. Anything found in an HTML or XML document can be accessed, changed, deleted, or added using the Document Object Model, with a few exceptions  The Document Object Model (DOM) is the model that describes how all elements in an HTML page, like input fields, images, paragraphs etc., are related to the topmost structure: the document itself. By calling the element by its proper DOM name, we can influence it.11-Apr-19 38
  • 39.
    • With aprogrammable object model, JavaScript gets all the power it needs to create dynamic HTML:  JavaScript can change all the HTML elements in the page  JavaScript can change all the HTML attributes in the page  JavaScript can change all the CSS styles in the page  JavaScript can react to all the events in the page  JavaScript can remove existing HTML elements and attributes  JavaScript can add new HTML elements and attributes  JavaScript can create new HTML events in the page HTML DOM defines: The HTML elements as objects The properties of all HTML elements The methods to access all HTML elements The events for all HTML element 11-Apr-19 39
  • 40.
    HTML DOM Methods •HTML DOM methods are actions you can perform (on HTML Elements). • HTML DOM properties are values (of HTML Elements) that you can set or change. • document.getElementById("demo").innerHTML = "Hello World!"; 11-Apr-19 40
  • 41.
    HTML DOM DocumentObject • Adding and Deleting Elements • Adding Events Handlers Method Description document.createElement(element) Create an HTML element document.removeChild(element) Remove an HTML element document.appendChild(element) Add an HTML element document.replaceChild(new, old) Replace an HTML element document.write(text) Write into the HTML output stream Method Description document.getElementById(id).onclick = function(){code} Adding event handler code to an onclick event 11-Apr-19 41
  • 42.
    HTML DOM DocumentObject • Finding HTML Elements • Changing HTML Elements document.getElementById(id) Find an element by element id document.getElementsByTagName(name) Find elements by tag name document.getElementsByClassName(name) Find elements by class name Property Description element.innerHTML = new html content Change the inner HTML of an element element.attribute= new value Change the attribute value of an HTML element element.style.property= new style Change the style of an HTML element Method Description element.setAttribute(attribute, value) Change the attribute value of an HTML element 11-Apr-19 42
  • 43.
    HTML DOM Elements •Finding HTML Elements – Often, with JavaScript, you want to manipulate HTML elements. • Finding HTML elements by id • Finding HTML elements by tag name • Finding HTML elements by class name • Finding HTML elements by CSS selectors • Finding HTML elements by HTML object collections • var myElement = document.getElementById("intro"); • var x = document.getElementsByTagName("p"); 11-Apr-19 43
  • 44.
    • Nodes  Inthe Level 1 DOM, each object, whatever it may be exactly, is a Node. So if you do <P>This is a paragraph</P>  you have created two nodes: an element P and a text node with content 'This is a paragraph'. The text node is inside the element, so it is considered a child node of the element. <P> <-- element node | | This is a paragraph <-- text node  <P>This is a <B>paragraph</B></P> <P> | -------------- | | This is a <B> | | paragraph 11-Apr-19 44
  • 45.
  • 46.
    To do so,you have to find the elements first. There are a couple of ways to do this:  Finding HTML elements by id  Finding HTML elements by tag name  Finding HTML elements by class name The following HTML objects (and object collections) are also accessible: document.anchors document.body document.documentElement document.embeds document.forms document.head document.images document.links document.scripts document.title (1) <body> <p id="intro">Hello World!</p> <p>This example demonstrates the <b>getElementById</b> method!</p> <script> x=document.getElementById("intro"); document.write("<p>The text from the intro paragraph: " + x.innerHTML + "</p>"); </script> 11-Apr-19 46
  • 47.
    (2) <body> <p>Hello World!</p> <div id="main"> <p>TheDOM is very useful.</p> <p>This example demonstrates the <b>getElementsByTagName</b> method</p> </div> <script> var x=document.getElementById("main"); var y=x.getElementsByTagName("p"); document.write('First paragraph inside "main" is ' + y[0].innerHTML); </script> </body> (3) <p id="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML="New text!"; </script> <p>The paragraph above was changed by a script.</p> 11-Apr-19 47
  • 48.
    (5) <body> <img id="image" src="smiley.gif"width="160" height="120"> <script> document.getElementById("image").src="landscape.jpg"; </script> <p>The original image was smiley.gif, but the script changed it to landscape.jpg</p> </body> The HTML document above contains an <img> element with id="image" We use the HTML DOM to get the element with id="image" A JavaScript changes the src attribute of that element from "smiley.gif" to "landscape.jpg“ (6) <p id="p1">Hello World!</p> <p id="p2">Hello World!</p> <script> document.getElementById("p2").style.color="blue"; document.getElementById("p2").style.fontFamily="Arial"; document.getElementById("p2").style.fontSize="larger"; </script> <p>The paragraph above was changed by a script.</p> 11-Apr-19 48
  • 49.
    (7) <body> <h1 id="id1">My Heading1</h1> <button type="button" onclick="document.getElementById('id1').style.color='red'"> Click Me!</button> </body> (8) <p>Hello World!</p> <p class="intro">The DOM is very useful.</p> <p class="intro">This example demonstrates the <b>getElementsByClassName</b> method.</p> <p id="demo"></p> <script> var x = document.getElementsByClassName("intro"); document.getElementById("demo").innerHTML = 'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML; </script> 11-Apr-19 49
  • 50.
    (9) <body> <form id="frm1" action="/action_page.php"> Firstname: <input type="text" name="fname" value="Donald"><br> Last name: <input type="text" name="lname" value="Duck"><br><br> <input type="submit" value="Submit"> </form> <p>Click "Try it" to display the value of each element in the form.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var x = document.forms["frm1"]; var text = ""; var i; for (i = 0; i < x.length ;i++) { text += x.elements[i].value + "<br>"; } document.getElementById("demo").innerHTML = text; } </script> </body> 11-Apr-19 50
  • 51.
    HTML DOM Events •Reacting to Events • A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element. • To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute: onclick = JS • HTML events: • When a user clicks the mouse • When a web page has loaded • When an image has been loaded • When the mouse moves over an element • When an input field is changed • When an HTML form is submitted • When a user strokes a key11-Apr-19 51
  • 52.
    Example (1) <body> <h1 onclick="this.innerHTML ='Ooops!'">Click on this text!</h1> </body> (2) <body> <h1 onclick="changeText(this)">Click on this text!</h1> <script> function changeText(id) { id.innerHTML = "Ooops!"; } </script> </body> 11-Apr-19 52
  • 53.
    Example (3) <body> <p>Click the buttonto display the date.</p> <button onclick="displayDate()">The time is?</button> <script> function displayDate() { document.getElementById("demo").in nerHTML = Date(); } </script> <p id="demo"></p></body> (4) <body> <p>Click "Try it" to execute the displayDate() function.</p> <button id="myBtn">Try it</button> <p id="demo"></p> <script> document.getElementById("myBtn").o nclick = displayDate; function displayDate() { document.getElementById("demo").in nerHTML = Date(); } </script></body> 11-Apr-19 53
  • 54.
    Example <body onload="checkCookies()"> <p id="demo"></p> <script> functioncheckCookies() { var text = ""; if (navigator.cookieEnabled == true) { text = "Cookies are enabled."; } else { text = "Cookies are not enabled."; } document.getElementById("demo").in nerHTML = text; } </script></body> <script> function myFunction() { var x = document.getElementById("fname"); x.value = x.value.toUpperCase(); } </script> </head> <body> Enter your name: <input type="text" id="fname" onchange="myFunction()"> </body> 11-Apr-19 54
  • 55.
    Example <body> <div onmouseover="mOver(this)" onmouseout="mOut(this)" style="background- color:#D94A38;width:120px;height:20 px;padding:40px;"> Mouse OverMe</div> <script> function mOver(obj) { obj.innerHTML = "Thank You" } function mOut(obj) { obj.innerHTML = "Mouse Over Me" } </script></body> <div onmousedown="mDown(this)" onmouseup="mUp(this)" style="background- color:#D94A38;width:90px;height:20px;p adding:40px;"> Click Me</div> <script> function mDown(obj) { obj.style.backgroundColor = "#1ec5e5"; obj.innerHTML = "Release Me"; } function mUp(obj) { obj.style.backgroundColor="#D94A38"; obj.innerHTML="Thank You"; } </script>11-Apr-19 55
  • 56.
    Example <form id="myForm" action="#"> Firstname: <input type="text" name="fname" value="Donald"><br> Last name: <input type="text" name="lname" value="Duck"><br> <input type="submit" value="Submit"> </form> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var x = document.getElementById("myForm").elements[0].value; document.getElementById("demo").innerHTML = x;} </script> 11-Apr-19 56
  • 57.
  • 58.
    • The windowobject is supported by all browsers. It represent the browser's window. • All global JavaScript objects, functions, and variables automatically become members of the window object. • Global variables are properties of the window object. • Global functions are methods of the window object. 11-Apr-19 58
  • 59.
    Window Screen • Thewindow.screen object can be written without the window prefix. Some properties: • screen.availWidth - available screen width • screen.availHeight - available screen height <script> document.write("Available Width: " + screen.availWidth); </script> The output of the code above will be: Available Width: 1366 11-Apr-19 59
  • 60.
    Window Location • Thewindow.location object can be written without the window prefix. Some examples: • location.hostname returns the domain name of the web host • location.pathname returns the path and filename of the current page • location.port returns the port of the web host (80 or 443) • location.protocol returns the web protocol used (http:// or https://) 11-Apr-19 60
  • 61.
    The location.assign() methodloads a new document. <html> <head> <script> function newDoc() { window.location.assign(“C:Documents and SettingsAdministratorDesktopa1.html") } </script> </head> <body> <input type="button" value="Load new document" onclick="newDoc()"> </body> </html> 11-Apr-19 61
  • 62.
    Window History • Thewindow.history object can be written without the window prefix. • To protect the privacy of the users, there are limitations to how JavaScript can access this object. Some methods: • history.back() - same as clicking back in the browser • history.forward() - same as clicking forward in the browser <html> <head> <script> function goBack() { window.history.back() } </script> </head> <body> <input type="button" value="Back" onclick="goBack()“> </body> </html> 11-Apr-19 62
  • 63.
    Window Navigator • Thewindow.navigator object contains information about the visitor's browser. <div id="example"></div> <script> txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>"; txt+= "<p>Browser Name: " + navigator.appName + "</p>"; txt+= "<p>Browser Version: " + navigator.appVersion + "</p>"; txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>"; txt+= "<p>Platform: " + navigator.platform + "</p>"; txt+= "<p>User-agent header: " + navigator.userAgent + "</p>"; txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>"; document.getElementById("example").innerHTML=txt; </script> 11-Apr-19 63