Download presentation
Presentation is loading. Please wait.
1
1 Week 10 A World Wind Tour of JavaScript JavaScript
2
2 Objectives l World wind tour of JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How differs from PHP »Working with JS and HTML tags. »Running onload, when done, on an event »Using JS objects »Objects and forms (validating) »Rollovers
3
3 JavaScript: Its Beginnings l JavaScript developed by Netscape & initially called livescript. l After Java came out, Netscape cut a deal with Sun to rename it to JavaScript (12/95). »They are separate, distinct languages. (Though JavaScript is simpler). l Microsoft … »Came out with their own flavor of JavaScript called “Jscript”. »They also added support for VBScript in IE. Differences are minor. l Eventually standardized … »JavaScript has been turned over to the European Computer Manufactures Association, and is now officially called ECMAScript »Both Netscape & IE4.0 and Netscape implement ECMAScript standard.
4
4 The “goods” on JavaScript l JavaScript can be used to: 1. perform simple client-side computations l For example, add up total costs of shopping cart before it is submitted. 2. facilitate dynamic and interactive Web page creation l For example, do image roll overs, pop up windows on click, expand a menu. 3. Verify HTML forms enhance HTML forms with data collections and form validation 4. manipulate user cookies -
5
5 The “not so goods” on JavaScript l JavaScript runs completely on Client machine l It does NOT have: 1. Any graphic capabilities l E.g., cannot show a graph of survey results. 2. Access to client (you PC) resources l Cannot print, modifying PC files, or launching client applications. 3. Access to any Web server resources l E.g., cannot send email, write to file, write to database.
6
6 PHP/JavaScript Similarities and Differences l What they have in common. Both languages can: 1.Be embedded in HTML documents 2.Cause dynamic content to be displayed (e.g., the current date) 3.Can be placed in external files and “included” into html files 4.Look more like a programming language than HTML l What they DON’T have in common: 1.The big difference … JavaScript runs 100% on client (i.e., PC). This means: A. JavaScript stuff runs noticeably faster (not dependent on Internet and Web Server) B. PHP has access to Web Server resources (mail, databases, files) 2.Using differences A.Writing JavaScript does NOT require a Web Server (but more concern about browser implementation differences). B.PHP’s syntax is easier to write and understand for beginners.
7
7 How PHP Pages are Run JavaScript does not run here JavaScript is run here by the browser but just before HTML
8
8 Objectives l World wind tour of JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How differs from PHP »Working with JS and HTML tags. »Running onload, when done, on an event »Using JS objects »Objects and forms (validating) »Rollovers
9
9 Adding JavaScript to HTML pages JavaScript is added to HTML pages using the tag. usually placed in the HEAD or BODY of the document <!-- Javascript code //--> If link to an external file (use.js suffix) If embed JS within HTML
10
10 A Simple example A Beginning Script document.write ("Welcome to the wonderful world of JavaScript"); It’s a little like PHP. These statements are run before HTML document interpreted by browser http://condor.depaul.edu/~dlash/extra/javascript/startingout.htmstartingout.htm
11
11 Where do you put it? Can add JavaScript to head or body of html document Functions are usually added to the head section assures that the functions OK (parsed) by the time they are called. Non-functions usually put in body then can call and functions in head
12
12 Objectives l World wind tour of JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How differs from PHP »Working with JS and HTML tags. »Running onload, when done, on an event »Using JS objects »Objects and forms (validating) »Rollovers
13
13 When does it run? It can run as the page loads as soon as the page is finished loading in response to user input (remember the form button?)
14
14 Document Object Document Object document.writeln("This page was last modified on” + document.lastModified); JavaScript that Runs as Page Loads Enter JavaScript. Within the html body (in this case) Normal HTML code document.write like print. Get lastModified browser vrbl.. The + is catenation. Calls function to get current date and output date http://condnor.depaul.edu/~dlash/extra/javascript/lastmodifiedworks.htmlastmodifiedworks.htm
15
15 JavaScript output (onload) is HTML input ….. The output of JavaScript statements is taken as HTML input... A Beginning Script document.write (" JavaScript commands are interpreted first "); document.write (" JS output often generates HTML "); http://condor.depaul.edu/~dlash/extra/javascript/secondjs.htmsecondjs.htm
16
16 Java Example 2 welcome to my page Here is my stuff function waitLittle() { setTimeout( "alertMe()", 5000 ); } function alertMe() { alert('test'); } This is some text over here. http://condor.depaul.edu/~dlash/javascript//javascript2.html/javascript2.html JavaScript that Runs when Loading Complete Execute this function call after 5000 miliseconds Create a pop-up box with test as text
17
17 JavaScript that Runs in Response to User Input <!-- function showTime() { document.forms["getDate"].curTime.value = (new Date()).toLocaleString(); } function alertme() { alert("Don't Do that"); } //--> <input type="button" name="getTime" onClick="showTime()" value="Show Current Time" /> http://nwswww.ih.lucent.com/~dlash/perlcourse/javascript/javascript3.htmjavascript3.htm When click call showtime Set the value of the form variable curTime to the current time If they click generate an alert
18
18 Dealing with Browsers that don’t Support JavaScript You may have noticed something a little strange about the examples so far. <!-- Javascript code //--> This makes the script invisible to browsers that don’t support JavaScript by “commenting it out”. In addition, you can provide some page content that only displays when the browser DOESN’T handle JavaScript: Your browser doesn’t support Javascript The only limitation with this is that this will NOT be displayed by NS if the user has JavaScript just disabled.
19
19 Some Important Aspects of JavaScript Case Sensitive: Variable names, functions you use - (e.g., Date not date ) Space Insensitive - generally ignored, except in strings Statements end in semicolon – Except JS will assume you meant to semicolon at the end of the line if the statement appears to be complete.
20
20 Objectives l World wind tour of JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How differs from PHP »Working with JS and HTML tags. »Running onload, when done, on an event »Using JS objects »Objects and forms (validating) »Rollovers
21
21 JavaScript And Objects... l JavaScript is object-oriented (Just a thing you can access) l Objects have »properties - are variables or other objects describing the object. –(like document.lastmodified). –In general these are accessed by ObjectName.ProperyName »methods - behaviors or built-in functions you use »accessed my ObjectName.MethodName() document.lastmodified Object name Property of object
22
22 Using JavaScript Objects … l Lots of useful properties available g l Here are some properties for window object: »document.lastModified – (read-only property) gives the document last changed date »document.URL - (read-only property) gives the URL of the document source code file. »window.referrer – (read-only property) gives the URL of the calling document. (It is an empty string, if user does not reach the URL by clicking a link. »window.title – (read-only property) gives the value in the... tag.
23
23 Printing out one of these Can use the plus sign (+) to attach string output with propert output document.write("last modified:” + document.lastModified + " "); Print out this string Attach to the string this property Attach to the entire string this html tag Write the following out.
24
24 For example Document Information Properties document.write("Referring link was:” + document.referrer) + " ") document.write("Document URL is:“ + document.URL +" ") document.write("The title is: " + document.title +" ") document. write("last modified:” + document.lastModified + " ") This is my web site. It is my Web Site all by myself. http://condor.depaul.edu/~dlash/extra/javascript/DocumentInformationProperties.htmDocumentInformationProperties.htm
25
25 The Math Object An example JavaScript object. Math.abs( number ) Math.sin( number ) Math.cos( number ) Math.round( number ) Math.ceil( number ) Math.floor( number ) Math.log( number ) Math.sqrt( number ) Math.random( number ) absolute value sine of an angle (expressed in radians) cosine of an angle (expressed in radians) closest integer value rounds up to next integer value rounds down to next integer value natural log of the number square root of the number returns a floating point number that is >= 0.0 but < 1.0 Other methods include: tangent, arc tangent, arc sine, arc cosine, tangent, power, angle of polar coordinates, maximum, and minimum. Also has constant definitions for values like pi and e (natural log base).
26
26 The Date Object The Date object to access time and date information. Unlike the Math object, need to create a Date object first: var dateObj = new Date(); You can specify the data/time when you create the object. xmasObj = new Date(“December, 25, 2002”); Can print out current date via: document.write ( new Date().toLocaleString()); Creates new date object
27
27 Objectives l World wind tour of JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How differs from PHP »Working with JS and HTML tags. »Running onload, when done, on an event »Using JS objects »Objects and forms (validating) »Rollovers
28
28 Document objects Getting access to page contents requires document object. Everything on the page is associated with an object. Some of these objects contain other objects. The object hierarchy is: window frame navigator history location document link anchor form element
29
29 JavaScript is Event Driven l Event-driven: When “event” occurs then take some action. l JavaScript supports several events such as: –onLoad –onUnload –onFocus –onBlur –onMouseOver –onMouseOut –onChange –onSelect l When click this form element then do this JavaScript function
30
30 Example of Events and Forms Consider the following Form with 3 text boxes. Onclick either first 2 text fields adds them up. If click last on create a pop-up First num Second num Total http://condor.depaul.edu/~dlash/extra/javascript/myform.htmmyform.htm
31
31 Document objects (cont.) my form Value1 Value2: Total: Uses an external javascript file. Form named totals Text box names first, second, total onClick call genAlert() function onClick call calcTotals() function
32
32 Document objects (cont.) The following would be in the file total.js: function genAlert() { message="Error: Do not change total score value. It will be filled in by the Web Application"; alert( message ); } function calcTotals() { f=document.totals; f.total.value = parseInt(f.first.value) + parseInt(f.second.value); } It would be useful to check if valid number but it works for what it does. Add the form element called “first” with the element called “second” Call form document.totals “f”
33
33 A simple variation.. my form Value1 Value2: Total: Call calcTotal() onload. Call give initial values to textboxes. Not a submit button but when hit button call calctotals also. http://condor.depaul.edu/~dlash/extra/javascript/myform2.htmmyform2.htm
34
34 Form Validation To validate forms need control onSubmit of form window.document.forms["inputValues"].submit(); To block submission of a form when the submit button is clicked, we define the onsubmit event for the form: onsubmit=“return checkitout();” a value of false will stop submit
35
35 Form Validation (cont.) Example, <form name="inputValues” method=“post” action=“URL”, onsubmit=“return inputValid();” > We would then define the function: function inputValid() { if (everthingIsOk) return true; else return false; }
36
36 Example using onSubmit() my form <form name="totals" method="post" action="savevalues.php" onSubmit="return inputValid();" > Value1 Value2: Total: Action set onSubmit set Changed to submit button type. http://condor.depaul.edu/~dlash/extra/javascript/myform3.htmmyform3.htm
37
37 Example using onSubmit() – total2.js function genAlert() { message="Error: Do not change total score value. It will be filled in by the Web Application"; alert( message ); } function calcTotals() { f=document.totals; f.total.value = parseInt(f.first.value) + parseInt(f.second.value); } function inputValid() { f=document.totals; calcTotals(); if ( parseInt(f.total.value) > 50 ) { return true; } else { alert("Please Continute until hit 50"); return false; } New function checks if total > 50. Re-calculate totals
38
38 Accessing Other Form Elements Can access and validate things like: select (including ones with the MULTIPLE attribute) password (the real value, not the line of asterisks) radio buttons checkboxes textarea hidden fields Getting these is beyond scope of class but can give an example …
39
39 Example Getting Radio and select buttons my form Pick a button One Two Three Select an Option: One Two Three Total: http://condor.depaul.edu/~dlash/extra/javascript/myform4.htmmyform4.htm
40
40 Example Getting Radio and select buttons function genAlert() { message="Error: Do not change total score value. It will be filled in by the Web Application"; alert( message ); } function get_radio_value( form, button ) { var RadioButton = document[form][button]; for (i=0; i<RadioButton.length; i++ ){ if (RadioButton[i].checked){ return RadioButton[i].value; } return 0; } function getSelectValue( formname, selectname ){ var theMenu = document[formname][selectname]; var selectedItem = theMenu.selectedIndex; if ( selectedItem == -1 ) { return 0; } else { return theMenu.options[selectedItem].value; } function calcTotals() { f=document.survey1; f.total.value=0; radio1 = get_radio_value("survey1", "first" ); select1 = getSelectValue( "survey1", "second" ); f.total.value=(parseInt(radio1)+parseInt(select1)); } For each radio button in the group If it is checked then return its value
41
41 Accessing Other Form Elements (cont.) But reading the form elements is not the only thing you can do. You can also alter them: var formObj = window.document.forms["sample"] formObj.elements["textBox"].value = "Random Text"; formObj.elements["passwrd"].value = "rosebud"; formObj.elements["checkbox4"][1].checked = true; formObj.elements["checkbox4"][0].checked = false; formObj.elements["checkbox1"].value = "Citizen_Kane" formObj.elements["checkbox1"].checked = true; formObj.elements["checkbox2"].checked = false; formObj.elements["checkbox3"].checked = false; formObj.elements["radio1"][3].checked = true; formObj.elements["select1"].selectedIndex = 2; formObj.elements["select1"].options[2].text = "Gioachino Rossini"; formObj.elements["select1"].options[2].value = "Rossini"; formObj.elements["select2"].options[4].text = "William Tell"; formObj.elements["select2"].options[4].value = "WillTell"; formObj.elements["select2"].options[4].selected = true; formObj.elements["select2"].options[2].selected = true; formObj.elements["select2"].options[1].selected = false;
42
42 One More Example html> my form Enter Soc Security
43
43 One More Example (Cont.) function inputValid() { f=document.totals; inSoc = (f.soc.value); social = /^(\d{9}|\d{3}-\d{2}-\d{4})$/; var matchIndex = inSoc.search(social); if ( matchIndex >= 0 ) { return true; } else { alert("Please enter 9 digits"); alert(matchIndex); return false; } http://condor.depaul.edu/~dlash/extra/javascript/
44
44 Objectives l World wind tour of JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How differs from PHP »Working with JS and HTML tags. »Running onload, when done, on an event »Using JS objects »Objects and forms (validating) »Rollovers
45
45 Creating Rollovers l You can create a “crude” rollover mechanism by changing src properities of a file. l Not the way best way to do this (since will not be downloaded until you mouse over the image.) http://condor.depaul.edu/~dlash/extra/javascript/RolloverBeethoven.htmRolloverBeethoven.htm
46
46 The Source Rollover Beethoven Rollover Beethoven <!--Callout: The Anchor tag responds to mouseover and mouseout events.--> <a href="#" onmouseover= "document['beethoven'].src=‘RolloverBeethoven_files/beethovenon.jpg';" onmouseout= "document['beethoven'].src=' RolloverBeethoven_files /beethovenoff.jpg';"> <img src=" RolloverBeethoven_files /beethovenoff.jpg" width="250" height="70" name="beethoven" border="0" alt="Picture of Beethoven"> The tag responds to mouseover and mouseout events. It is set to “null” value. Set the image src= property The default image Border=”0” prevents image border from appearing.
47
47 One more thing … debug If type javascript: In netscape only will create debug console: http://condor.depaul.edu/~dlash/extra/javascript/lastmod_error.htmlastmod_error.htm
48
48 Summary l World wind tour of JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How differs from PHP »Working with JS and HTML tags. »Running onload, when done, on an event »Using JS objects »Objects and forms (validating) »Rollovers
49
49 Overall Summary l We have looked at many things: –HTML – Great for static text, images, forms l Links, font tags, lists, tables, forms, frames. –Design – Think through how site looks l Talk with site owner l Consistent navigation l Graphic design use photo editing software –CSS – Allows greater control of text, > 1 developers, common format –PHP – Create dynamic content, run on WebServer, receive form input –JavaScript – Run on browser, validate forms, roll overs, pop ups, menu elements.
50
50 Overall Summary l A “real” Site might include all of these: »Html – to display content. »Design – photo-editor »CSS – to control look and feel »PHP – to send email, save to database »JavaScript –to validate forms, control certain elements l A “real” web developer would have much more experience with: »PHP (or some other script) – Databases, other things »JavaScript – »Frontpage type of software – l Hopefully you found information valuable and help take some of the magic out of Websites and website design
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.