1 / 48

JAVASCRIPT

JAVASCRIPT. Session 3. Overview. Introduction, Data Types, Operators and Statements JavaScript Objects, Functions The Browser, The DOM, Dynamic pages, Debugging JavaScript and Custom Object creation, Storage XML - JSON, Introduction to Ajax. The Browser.

ecraft
Télécharger la présentation

JAVASCRIPT

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JAVASCRIPT Session 3

  2. Overview • Introduction, Data Types, Operators and Statements • JavaScript Objects, Functions • The Browser, The DOM, Dynamic pages, Debugging • JavaScript and Custom Object creation, Storage • XML - JSON, Introduction to Ajax

  3. The Browser • Browser Object Model (BOM) – A term sometimes applied to the DOM specifically referring to the browser context. ‘BOM’ is not an “official” standard. • The BOM is a set of several common web objects inherited from the browser context that are accessible to JavaScript • We have seen a couple of these objects: • window • document

  4. BOM Hierarchy

  5. Inside a ‘window’ object <html> <head> <title>DOM Example</title> </head> <body> <div id="main_content"> <p>A paragraph of content with <i>some text in italics.</i></p> <p>A second paragraph of content. This paragraph also has an image of a <img src="baseball.jpg"> baseball embedded.</p> </div> </body> </html> Every box in this illustration is called a ‘node’.

  6. window Object • By 'window' we are referring to the part of the browser that surrounds the HTML document • You can use the window object to open new windows (or tabs), close existing windows (or tabs), resize windows, change the status of windows, dealing with frames, working with timers, etc • The window object incudes methods such as alert() and write() (via the 'document' object) that we have used already. • In theory, we should need to write: window.alert() or window.document.write() • However, as the very "top" level (global) object, the ‘window’ reference is implicitly understood and, therefore, typing it turns out to be optional.

  7. Example: Accessing your images via the DOM window.document.images

  8. Accessing Elements <img src=“firetruck.jpg” id=“truck_pic” name=“firetruck” alt=“pic of truck”> <img src=“baseball.jpg” id=“ball_pic” name=“baseball” alt=“pic of baseball”> You can access an element by its 'name' attribute: alert( document.images.firetruck.alt ); //Outputs: ‘pic of truck’ You can access an element using array notation: alert( document.images[0].alt ); //Outputs 'pic of truck' alert( document.images[1].alt ); //Outputs 'pic of ball' You can access an element by its 'id' attribute: alert (document.getElementById(“truck_pic”).alt ); //outputs 'pic of truck'

  9. DOM Example <html> <head> <title>DOM Example</title> <script type="text/javascript"> function domTest(){ var images = document.images; //Recall that ‘window’ is implicit var str="List of Alt Values:\n"; for (var i=0; i<images.length; i++) { str += images[i].alt + "\n"; } alert(str); } //end domTest() </script> </head> <body onload="domTest()"> <p>Some smiley-face balls:</p> <img src="blue_ball.jpg" alt="Pic of blue ball" height="80" width="80"> <img src="green_ball.jpg" alt="Pic of green ball" height="80" width="80"> <img src="red_ball.jpg" alt="Pic of red ball" height="80" width="80"> </body> </html>

  10. Pop-Up (Non-Browser) Windows • alert() • alert(“This is a message”); • confirm() • Returns a boolean: • True – if user clicks ‘OK’ • False – if user clicks ‘Cancel’ • Example: var result = confirm(“Continue ?”); • prompt() • Returns the String entered by the user, if the user clicks ‘OK’ • Returns ‘null’ if the user clicks ‘Cancel’ • var response = prompt(“Your Name ?”, [default] ); Don't forget that even though these methods are part of the 'window' object, the reference to 'window' is "implicit" (i.e. it's presence is assumed). Therefore for clarity, we typically just leave it out.

  11. Opening a new browser window To open a window (or tab) use: window.open(param1, param2, param3); • All 3 parameters are optional • param1 - the URL of the document • param2 - window name (for purposes of referencing if needed) – Note: This is not the <title> of the window • param3 - window options to control the appearance of the window. All desired options are included in one single string, separated by commas. • Not all options are always available. Some are context and window specific. Example: window.open("http://google.com", "", "height=600, width=400, toolbar=no");

  12. window.open("http://google.com", "googWin", "height=600, width=400, toolbar=no"); window.open("http://google.com", "googWin", "height=600, width=400, toolbar=yes");

  13. window.open() - options

  14. window.open() - options

  15. Opening a new browser window var newWindow = window.open("", "winInfo", "height=200, width=400"); newWindow.document.write('The current date is: ' + Date() + '<br>'); newWindow.document.write('<input type="button" value="Greet Me" onclick="alert(\'hi\')">'); • Note how this time, we need to include the reference to the current window object, 'newWindow' in order to ensure that our code applies to the appropriate window • Note the advantage of keeping single and double quotes separate • Note the need to use escape characters in the 'onclick' attribute

  16. BOM Hierarchy

  17. frames Object • The frames object has the following properties: • parent • length • name • The parent (frameset) can access the children frames by their names. The children can access the other child by going throught the parent. • Frames are no longer popular – in fact, their use has fallen out of favor and rarely recommended. • They are discussed here simply for completeness and because it is possible you will encounter them in legacy code.

  18. BOM Hierarchy

  19. location Object alert( window.location.href ); //outputs the current URL

  20. location Object A URL such as: http://learning.javascript.info/ch09-01.htm?a=1 Can be broken down into the following property values of the 'location' object: host/hostname: learningjavascript.info protocol: http: search: ?a=1 href: http://learning.javascript.info/ch09-01.htm?a=1 e.g. alert( window.location.protocol ); //outputs ‘http:’

  21. Timing Events It is possible to time events using JavaScript. There are two function in particular: setTimeout() and setInterval(). setInterval() will execute a function that you name over and over again at specified intervals (e.g. every 3 seconds). Of course, you will then need a way to stop the execution. This is not difficult, but requires some extra code that we will not get into just now. setTimeout() will execute a function once, after a certain time interval has passed. Both of these methods are part of the ‘window’ object, in the same way that alert() is a method of the window object.

  22. //Example: set_timeout_example.htm <html> <head> <title>setTimeout() Example</title> <script type="text/javascript"> function go() { alert('Ready? Click the okay button, then wait 2 seconds to be greeted.'); //After the user closes the alert box above, we wait 2 seconds //and then the greetUser() function is invoked setTimeout("greetUser()",2000); } function greetUser() { alert('Hello!!!'); } </script> </head> <body onload="go()"> </body> </html>

  23. Digression: Anonymous Functions • Consider the setTimeout function: setTimeout(function, milliseconds, [optional parameters]); • Notice how the first argument is itself an entire function. Situations where an argument to a function is itself a function are not uncommon. • Also, it is frequently the case that the function being passed is intended to be used only inside the parameter list. In other words, there are no plans to ever invoke that function elsewhere. For this reason, rather than write a function elsewhere and pass the function's identifier as an argument (e.g. setTimeout("greetUser()", 3000);we instead write the entire function directly inside the parameter list! For example: setTimeout( function doStuff() { alert('hi'); }, 3000); • But wait… since we are not intending to invoke the function at any other time, we do not even need to give the function an identifier: setTimeout( function () { alert('hi'); }, 3000); • When we create a function but dispense with giving the function an identiier, we call it an anonymous function. Anonymous functions are used with some frequency in JavaScript and jQuery.

  24. Back to timers… Now that we understand a little bit about anonymous functions, let’s take another look at our timer functions: Suppose we have a function that prints the current time to a div section called ‘clock’: function printTime() { var now = new Date(); document.getElementById('clock').innerHTML = now.toLocaleTimeString(); } We could create a digital clock effect by printing out the new time every second. Note the use of our anonymous function: setInterval(function() { printTime() }, 1000); and placing this somewhere in an ‘onload’ attribute.

  25. How do we stop it? One issue is that we may want certain repeating events to stop at some point. Perhaps not with the digital watch in this example, but certainly in other cases. To stop setInterval() we use clearInterval() . However – the clearInterval() method requires a reference to the particular instance of setInterval() that we started. For example, it is certainly possible that there may be several different setInterval() functions invoked on the same page. We then run into the problem that if the aforementioned reference to setInterval() was declared inside the method in which it was used, we would not have access to that required reference (since it is out of scope). This brings us to one those relatively rare situations where we need a global variable. Example: ‘timers.htm’

  26. BOM Hierarchy

  27. history Object • This object maintains a history of pages loaded into the browser. • history.back(); //same as clicking the back arrow on your browser • history.forward(); //same as clicking the forward button on your browser • history.go(-3); //same as clicking the back button 3 times • history.go(3); //same as clicking the forward button 3 times • history.go(3); // go forwards • We don’t typically interact with the history object directly. About the only time it may be of use is when you use Ajax page effects, which work outside the normal process of page loading. Therefore, we will not discuss this object any further at this time.

  28. BOM Hierarchy

  29. screen Object Contains information about the display screen, including width and height as well as color and pixel depth. The properties may change from browser to browser. As with the history object, this too is not used all that often.

  30. BOM Hierarchy

  31. navigator Object Allows you to find out information about the client (e.g. browser or other agent) that is accessing your page. Items you can check for / about include: • The type of browser and related information ('userAgent') • The version number ('appVersion') • Whether cookies are enabled ('cookieEnabled') • The OS on which the client is running ('platform') • Which plug-ins are installed ('plugins')

  32. 'navigator' object properties ee Example: history_navigator_properties.htm

  33. BOM Hierarchy

  34. document Object • We have now gone through all of the properties of the 'window' object, albeit somewhat briefly. We will now return to object with which we are already somewhat familiar, the 'document' object. • Of all the objects encapsulated by the 'windows' object, the 'document' object is the one JS programmers interact with most frequently. • The document object provides access to any element on the page, either individually or as a collection (e.g. a specific image, or an array of all of the images). • We've already seen a few properties/methods: getElementById, getElementByTagName and writeln. Other things we can access/do via the 'document' object: • Get the links on a page. • Alter images on the page • Change html contained within a page element

  35. innerHTML Property This property of the document object allows you to directly view and modify the HTML present inside the document. Though deprecated, this property is still available to HTML-5 and is present in a lot of legacy code. However, there are better ways of modifying HTML content (e.g. via node access, via jQuery's html() function, and others). <script> function go() { alert("Check out the text, then click the okay button"); document.getElementById('click').innerHTML = "<h1>Some H1 Text</h1>"; } </script> <div id="click" onclick="go()"> <h2>Click Me</h2> </div>

  36. document Object example Here is a a code example in which we access the 'links' property of the document object. This property retrieves all of the anchor <a> tags as a collection. We will then extract all of the URLs from those <a> elements and output them as an ordered list: var links = ""; for (var i = 0; i < document.links.length; i++) { links = links + "<li>" + document.links[i].href + "</li>"; } document.write("<ol>"); document.write(links); document.write("</ol>"); Examples: document_object_links.htm | dom_images_example.htm

  37. DOM • DOM Level 1 - 1998 • defined the infrastructure, schema, API as a base. • DOM Level 2 - 2000 • increased support for CSS, better element access, namespace support for XML • DOM Level 3 - 2004 • extended support for web services, increased support for XML

  38. Accessing HTML Objects via the DOM • In the DOM world, HTML objects have ‘official’ formal element names. These names typically differ from the HTML tag names with which we are familiar. For example: • <form> HTMLFormElement • <img> HTMLImageElement • <p> HTMLParagraphElement • <div> HTMLDivElement • etc • Most of the DOM properties are “read/write” which means you can not only ‘read’ them, but you can also alter them.

  39. Objects & Properties of HTMLElement • HTML objects inherit various properties and methods from various elements of the “Core DOM”, and the “HTML DOM”. Some of these contributing elements include: • ‘Node’ object • ‘Element’ object • ‘HTMLElement’ object HTMLElement properties: • id = The element identifier • title = Descriptive title for the element’s content • lang = language of the element and its contents • dir = directionality of the text (left=>right, right=>left) • className = Equivalent to the class element

  40. Nodes • The W3C’s specification for the DOM works by describing a web document as a series of “nodes”. • A web page’s DOM is essentially, a ‘tree’ in which there are parents, children, siblings, and so on. • The easiest way to see how all of this plays out is probably by example. We will first open up a document to view the HTML. We will then use a ‘DOM Inspector’ to see the visual representation of the DOM as a collection of nodes. • Most browsers have some form of DOM Inspector built in, or available via plug-ins. We will use Firebug, a plug-in available for Firefox browsers.

  41. Nodes <html> <head> <title>Page as Tree</title> </head> <body> <div id="div1"> <!-- paragraph one --> <p>To better understand the document tree, consider a web page that has a head and body section, a page title, and the body contains a div element that itself contains a header and two paragraphs. One of the paragraphs contains <i>italicized text</i>; the other has an image.</p> <!-- paragraph two --> <p>Second paragraph with image. <br> <img src="washington.jpg" alt="Painting of Washington"/></p> </div> </body> </html>

  42. Firebug's DOM Inspector

  43. Node Properties inherited from 'Node' Every Node object has a series of properties and methods courtesy of a DOM object called 'Node'. These include: • nodeName, nodeValue, nodeType • parentNodes, childNodes • firstChild, lastChild • previousSibling, nextSibling • attributes • ownerDocument • namespaceURI • prefix • localName • Example: node_object_properties.htm

  44. Node Properties inherited from Element' We have just looked at some properties available to nodes courtesy of the object 'Node'. Every node has an additional series of properties and methods courtesy of another DOM object called 'Element'. These include: • getAttribute(name); • setAttribute(name, value); • removeAttribute(name); • getAttributeNode(name); • setAttributeNode(attr); • removeAttributeNode(attr); • hasAttribute(name); Example: node_element_properties.htm

  45. Debugging • Simplest way is just to: alert(someVariable); • Firefox (www.mozilla.com/firefox/ ) - most popular with Ajax developers because of Firebug extension. • http://getFirebug.com

  46. Firebug Features • Inspect and edit HTML • Tweak CSS to perfection • Visualize CSS metrics • Monitor network activity • Debug and profile JavaScript • Includes breakpoints, step-throughs, etc • Quickly find errors • Explore the DOM • Execute JavaScript on the fly • Logging for JavaScript

  47. Firebug's DOM Inspector

  48. End of Session 3 • Next Session: • JavaScript and Custom Object creation, Storage

More Related