1 / 39

Introduction to Web Site Development

John Hurley Department of Computer Science California State University, Los Angeles. Introduction to Web Site Development. Lecture 8: JavaScript II. Tutoring.

Télécharger la présentation

Introduction to Web Site Development

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. John Hurley Department of Computer Science California State University, Los Angeles Introduction to Web Site Development Lecture 8: JavaScript II

  2. Tutoring • Tutoring for this class, CS122, and CS 201-203, is available for the rest of the term in the CS department office at the following times: • Mondays 11-3 • Wednesdays 10-1 • Thursdays 3-6 • Fridays 10-2

  3. Schedule Weeks 8-9 • I will be out of town for a long Memorial Day weekend • Keenan Knaur will sub in the lab this Weds. He is familiar with the lab assignment. • Next Monday, the 26th, is a holiday • My office hours are cancelled on Tuesday, May 27 • I will be back Weds, May 28. • Due to the timing of this term, with two Monday holidays, Weds the 28th counts as a Monday. Class will meet at 9:50, not at 9

  4. Comments • Comments are ignored by the web browser • There are two types of comments • Single Line • // comment • Multiple Line /* comment comment comment */

  5. Comments Example • Example: • <script type="text/javascript">// this is a comment /* this is a comment as well it spans multiple lines */</script>

  6. JavaScript Functions • A function is a key programming construct. • A statement is the smallest unit of execution in a programming language • A function executes zero or more statements • Functions can be reused

  7. JavaScript Functions • A function in JavaScript is like a function in math • This is how we do it in math • The function definition (math): • f(x) = x2 • Evaluating (calling) a function (math) • f(2) = 4 • f(3) = 9 • f(4) = 16

  8. JavaScript Functions • This is how we do it in JavaScript • The function definition (JavaScript): • function square(input) // x is the argument{return input*input; // multiply x times x} • Evaluating (calling) a function (JavaScript) • var x = square(2); // evaluates to 4 • var y = square(3); // evaluates to 9 • var z = square(4); // evaluates to 16 • If you have a return statement in your function, you may call the function and assign the result to a variable as in the example above

  9. JavaScript Functions • Every JavaScript function declaration has the following syntax: • The function definition (JavaScript): • function name(zero-or-more-comma-separated-parameters){ statement-list}

  10. JavaScript Functions • JavaScript functions can have zero arguments • function hey(){ window.alert("Hey!");return "Said \"Hey!\"";} • JavaScript functions do not have to return anything (they can just do one or more things) • function hey(){ window.alert("Hey!"); window.alert("Hey again!");}

  11. JavaScript Functions • Anytime you have a JavaScript function that doesn’t return something (doesn’t have the return statement), don’t assign it to variable • function hey1(){return 0;}function hey2(){}var x = hey1(); // OK, function hey1 returns 0var y = hey2(); // NOT OK!!!!!!!!! NO RETURN VALUE!!!!!

  12. JavaScript Functions You must call a function for it to run; just defining the function does not make it run: <!DOCTYPE html> <html> <head> <script type="text/javascript"> function hey() { window.alert("Hey!"); return ("Said \"Hey!\""); } </script> </head> <body> <script type = "text/javascript"> document.write(hey()); </script> </body> </html>

  13. Properties • A property is a characteristic or attribute of an object. Properties generally correspond to html element attributes. Many properties have slightly different names than the corresponding css properties. • The background color of a web page documentdocument.bgcolor • The date the web page file was last modifieddocument.lastmodified • The src file of an image object image1.src

  14. Properties <!DOCTYPE html> <html> <head> </head> <body> <script type="text/javascript"> varcolorIn = window.prompt("what is your favorite color?"); changeBG(colorIn); function changeBG(color) { document.bgColor = color; //Change background color } </script> </body> </html>

  15. Object • An object is a thing or entity. • Browser window • Submit button • Web page document

  16. Document Object Model • In programming terms, an Application Programming Interface • A way to manipulate an html document • DOM allows us to use JavaScript to control various aspects of our documents

  17. Document Object Model (DOM) • A portion of the DOM is shown at the left. • Defines every object and element on a web page • Hierarchical structure • Accesses page elements and apply styles to page elements

  18. The Document Object • Every HTML page has a document object associated with it • The document object gives us access to the other HTML objects in our document, plus a few other things • The syntax is: • document.attribute • document.function-name(parameters)

  19. Read/Write Document Attributes • document.title • The title of the HTML document, usually the string that is displayed in the browser’s window caption or tab bar • document.dir • The general direction of text in the document; can be the string "ltr" or "rtl" • document.body • Represents the body of the document; this one will be critical if you continue your study of JS

  20. Read Only Document Attributes • document.URL • A string that contains the full pathname of the currently open HTML document • document.lastModified • A string that contains the date for which the currently open HTML document was last modified

  21. <head> <title>My Document</title> </head> <body> <script type = "text/JavaScript"> window.alert(document.title); document.title = "Godzilla's Lair"; window.alert(document.title); </script> </body>

  22. Document Functions • document.write(str) • A function that allows you append HTML code to your document while it is being loaded • document.getElementById(id) • Retrieves the HTML object associated with the given HTML id attribute; this is one of the most important functions in the HTML DOM • document.getElementsByTagName(tag) • Retrieves all HTML objects associated with the given element name; this is one of the most important functions in the HTML DOM

  23. GetElementById • document.getElementById(id) returns whatever HTML element object the ID refers to, for example: • Paragraph • Table

  24. HTML Element • Once we get an element using the function document.getElementById, we can • Change the content (innerHTML) of the element • Change the attributes of the element • Change the direction of the element • Change the CSS class name of the element • And much more

  25. Getting HTML Elements By ID • First, note what you get when you display the element retrieved: • see garden.html • var s1 = document.getElementById ("stanza1"); window.alert(s1);

  26. HTML Element Attributes • All HTML objects have the following attributes, for which you can change using the HTML DOM • id • className • title • dir • innerHTML • Inner HTML is the content between the start and end tags of an HTML element

  27. Change CSS Styles Using getElementById • Create an HTML element, say a P element • Assign an ID to the element • Assign a CSS class name to the element • Get a handle to the HTML element using the document.getElementById(ID) function • Assign a new class name to the elements className attribute • See Blake Example and use View Source

  28. How to Change Inner HTML • Create an HTML element, say a p element with some content in it • Assign an ID to the element • Get a handle to the HTML element using the document.getElementByID(ID) function • Assign new content using handle.innerHTML • The innerHTML in this case is a string that can even contain HTML code! • See Blake Example

  29. getElementsByTagName • If you don’t have programming experience, don’t worry about this one! • Gets an array of all elements of a stated tag type, which you can access using Java-like array notation

  30. getElementsByTagName • <body> <p>Learned discussion of Marcel Proust here</p> <p>Biography of Cicero here</p> <script> var paragraphs = document.getElementsByTagName("p"); paragraphs[0].innerHTML = "Godzilla was taller"; paragraphs[1].innerHTML = "Bruce Lee was a better actor"; </script> </body>

  31. JavaScript and Events • JavaScript can be configured to perform actions when events occur. • The event name is coded as an attribute of an XHTML tag • The value of the event attribute contains the JavaScript code Example: Display an alert box when the mouse is placed over a hyperlink. <a href="http://www.google.com" onmouseover="alert('Google');">Google </a>

  32. Events

  33. HTML Button • <button> element is just what you think. It can be used with event attributes like onclick to trigger Javascript functions. <head> <meta charset="utf-8" /> <title>Demo</title> <script lang = "javascript"> function thankuser() { window.alert("thanks"); } </script> </head> <body> <button onclick = "thankuser();"> Click Me! </button> </body>

  34. Navigator Object • Contains information about the browser <body> <script type = "text/JavaScript"> window.alert(navigator.appName); </script> </body> Results are not always what you expect, because browser makers sometimes misidentify their products (try this with Chrome!)

  35. JavaScript That Redirects Browser Based on Input: <script type="text/javascript"> var legal = window.confirm("Are you 21 or older?"); if(legal ==false) { window.location = "http://www.google.com"; } else window.location = "http://www.guinness.com"; </script> </body>

  36. JavaScript Debugging(1) • Check the syntax of the statements • Pay very close attention to upper and lower case letters, spaces, and quotations • Verify that you have saved the page with your most recent changes • Verify that you are testing the most recent version of the page (refresh or reload the page) • Most browsers can display error messages: • In Firefox: Select Tools / Error Console • Chrome: Tools/Developer Tools

  37. Remember! • JavaScript is case-sensitive • Everything we have been doing this week and last is case-sensitive • If you misspell anything… you are doomed!

  38. View Source and JS View Source will *not* show you the output from execution of JavaScript, even with document.write, which is executed at load time.

  39. JavaScript Resources • JavaScript Tutorialshttp://www.w3schools.com/JS • JavaScript Tutorial for the Total Non-Programmer http://www.webteacher.com/javascript/ • More Beginning JavaScript Tutorials http://echoecho.com/javascript.htm • Core JavaScript 1.5 Reference Manual http://www.webreference.com/javascript/reference/core_ref • Creating Accessible JavaScripthttp://www.webaim.org/techniques/javascript

More Related