380 likes | 506 Vues
This article provides a comprehensive overview of JavaScript, a scripting language developed by Netscape that shares syntax similarities with Java and C/C++. It highlights the language's capabilities to enable dynamic interactions within web pages through alerts, variables, functions, and event handlers. Readers will learn about HTML integration, the Document Object Model (DOM), and how JavaScript can manipulate web elements to create engaging user experiences. Various examples, including forms and image rollovers, illustrate JavaScript's utility in modern web development.
E N D
Additional Web Protocols JavaScript and XML An overview of web languages and emerging technologies
JavaScript Overview Scripting Language that uses a similar syntax to Java (or C/C++) developed by Netscape. Permits a higher level of interaction in Web pages Low level Example….. : <html> <body> <script language="JavaScript"> document.write('Hello'); </script> </body> </html>
JavaScript Alerts <html> <body> <script language="JavaScript"> alert('This is an Alert Box!'); </script> </body> </html> Display a dialogue box message
Variables in JavaScript • Just like any other programming language var age = 35; var height = “”; var name = “Gordon”; “var” part declares the variable Defining a variable to use later String variable example
Functions Hint: Use functions if you want to do the same thing more than once HTML comment For backwards compatibility <html> <script language="JavaScript"> <!-- hide the code function myFunctionname() { document.write('Welcome to my homepage!<br>'); document.write('This is JavaScript!<br>'); } myFunctionname(); myFunctionname(); myFunctionname(); // --> </script> </html>
What are Event Handlers? The image changes as a result of a user action causing a ‘link event’ to occur
Creating an Image Rollover • Note: Authoring packages sure as Dreamweaver make creation of these easier ! • However, it is important you understand the technology behind Web pages Example JavaScript Event Handlers <a href="#" onMouseOver="document.button1.src='button2.gif'" onMouseOut="document.button1.src='button1.gif'"> <img src="button1.gif" name="button1" width=140 height=30 border=0></a>
Image Swapping Standard Image tag used to load first image <img src="button1.gif" name="button1" width=140 height=30 border=0> Mouse Out Event Occurs 2 Reset Source Address onMouseOut="document.button1.src='button1.gif'" 1 Mouse Over Link Event Occurs Image Source Address set to second image onMouseOver="document.button1.src='button2.gif'"
The HTML-document The Document Object Model - DOM • JavaScript organises all elements on a web-page into a hierarchy • Every element is seen as an object. • Each object can have certain properties and methods. • JavaScript can easily manipulate the objects
HTML-document hierarchy Example To refer to the elements in JavaScript code document.forms[0].elements[0].value
Form Object Types What to run when submit is pressed <FORM METHOD="POST" ACTION="mailto:emailname@emailaddress"> Surname <INPUT TYPE="TEXT" NAME="surname" > <BR><BR> <INPUT TYPE="submit" NAME="Submit" VALUE="Submit"> </FORM>
Blur <INPUT TYPE="CHECKBOX" NAME="Popgrp" VALUE="Blur"> <BR> Five <INPUT TYPE="CHECKBOX" NAME="Popgrp" VALUE="Five"> <BR> Steps <INPUT TYPE="CHECKBOX" NAME="Popgrp" VALUE="Steps"> Note the same name is given as this is one object on the form Male <INPUT TYPE="RADIO" NAME="Gender" VALUE="Male"> Female <INPUT TYPE="RADIO" NAME="Gender" VALUE="Female">
<TEXTAREA NAME="comments" ROWS=5 COLS=20> </TEXTAREA>
Lists <SELECT> <SELECT NAME="Subjects" SIZE=5 MULTIPLE> <OPTION>English Language <OPTION>Mathematics <OPTION>Physics <OPTION>History <OPTION>Art <OPTION>Chemistry </SELECT>
Some examples of JavaScript Objects <form action="http://osiris.sunderland.ac.uk/gun-scripts/survey.pl" name=“myForm” method="POST"> <input type="text" name=”email" size=30> document.myForm.email.value <select name="why"> <option value=0 selected>Choose one... <option value=1>It was in Sunderland <option value=2>It looked interesting <option value=3>It was an uptodate course <option value=4>My parents made me <option value=5>It was the only offer I had <option value=6>Other </select> document.myForm.comments.value document.myForm.why.value <textarea name="comments" rows=5 cols=70 wrap="VIRTUAL"> </textarea>
<html> <head> <script language="JavaScript"> <!-- hide function calculation() { var x=parseFloat(document.calcu.numa.value); var y=parseFloat(document.calcu.numb.value); var result= x + y; alert(result); } // --> </script> </head> <body> <h3>My first Calculator</h3> <form name="calcu"> Input A <input type="text" name="numa" value=""> <br> Input B <input type="text" name="numb" value=""> <br> <input type="button" value="Calculate" onClick="calculation()"> </form> </body></html> assignment name of objects on form Forms, Function andJavaScript Example
Data Conversion On the last example we converted a string to a real number Using parseFloat(String) Exercise: The following all convert a string to an Integer value of 10. What does the second parameter represent ? parseInt(“A”, 16) parseInt(“12”, 8) parseInt(“1010”, 2) parseInt(“10”, 10)
Data Conversion Answer: The radix of the number e.g. the base of the number system Base 16 parseInt(“A”, 16) parseInt(“12”, 8) parseInt(“1010”, 2) parseInt(“10”, 10) Base 8 (1*8+1*2=10) Base 2 (1*8+0*4+1*2+0*1=10) Base 10
Same Functionbetter code ! <html> <head> <script language="JavaScript"> <!-- hide function calculation(x,y) { var result= parseFloat(x) + parseFloat(y); alert(result); } // --> </script> </head> <body> <h3>My first Calculator</h3> <form name="calcu"> Input A <input type="text" name="numa" value=""> <br> Input B <input type="text" name="numb" value=""> <br> <input type="button" value="Calculate" onClick="calculation(document.calcu.numa.value, document.calcu.numb.value)"> </form> </body></html> Passing data to a function
How is JavaScriptused on the Web? • To create documents ‘on-the-fly’ (client sided) • creating and closing windows, creating new documents • i.e. Pop up adverts – These are now normally blocked by default in Web Browsers • Form validation (client sided) • to reduce the load on servers by checking forms prior to posting • To increase the functionality of the user interface • improve the user interface e.g. Rollovers, Interactive Menu Systems
Creating documents‘on-the-fly’ Example: Opens a new Browser window without a status bar, toolbar or menubar and then loads a new page into the window <html> <head> <script language="JavaScript"> <!-- hide function openWin2() { myWin= window.open('http://osiris.sund.ac.uk/','new_window_1', 'width=400,height=300,status=no,toolbar=no,menubar=no'); } // --> </script> </head> <body> <form> <input type="button" value="Open New Window" onClick="openWin2();"> </form> </body> </html>
Another example When no file name is given, the result is a blank document function openWin3() { myWin= window.open('','new_window_1','width=400,height=300, status=no,toolbar=no,menubar=no'); // open document for further output myWin.document.open(); // create document myWin.document.write("<html><head><title>On-the-fly"); myWin.document.write("</title></head><body>"); myWin.document.write("<center><font size=3>"); myWin.document.write("This HTML-document has been created "); myWin.document.write("with the help of JavaScript!"); myWin.document.write("</font></center>"); myWin.document.write("</body></html>"); // close the document - (not the window!) myWin.document.close(); } Using JavaScript to generate HTML
StandardObjects <html><head> <script Language="JavaScript"> <!-- hide var timeStr, dateStr; function clock() { now= new Date(); hours= now.getHours(); minutes= now.getMinutes(); seconds= now.getSeconds(); timeStr= "" + hours; if (minutes < 10) timeStr+= ":0" + minutes else timeStr+= ":" + minutes; if (seconds < 10) timeStr+= ":0" + seconds else timeStr+= ":" + seconds; document.clock.time.value = timeStr; date= now.getDate(); month= now.getMonth()+1; year= now.getYear(); dateStr= "" + month; if (date < 10) dateStr+= "/0" + date else dateStr+= "/" + date; dateStr+= "/" + year; document.clock.date.value = dateStr; Timer= setTimeout("clock()",1000); } // --> </script> </head> <body onLoad="clock()"> <form name="clock"> Time: <input type="text" name="time" size="8" value=""><br> Date: <input type="text" name="date" size="8" value=""> </form></body></html> Use the actual time and date as a new one isn’t specified The Date Object Returns the date and time time date Rerun the function every 1000 msec
Form validation (client sided) • Can be used to • Check that all parts of the form have been completed • Check that certain characters exist • e.g. checking for the @ symbol in email address text input fields
Form validation (client sided) Example function Test if the value is blank function emailtest() { if (document.myForm.email.value == "" || document.myForm.email.value.indexof('@', 0) == -1) alert("No valid e-mail address!"); else alert("OK!"); } OR Test if the value contains an @ symbol
Form validation (client sided) Checking a form before it is processed by a CGI script function validate() { var formokay = true; some if statements checking the form fields (if any are invalid set the formokay to false) return formokay; } <form … onSubmit=“return validate()”> The onSubmit event handler is used
COMPLETE EXAMPLE <HTML> <HEAD> <TITLE>Feedback Form</TITLE> <script language="JavaScript"> <!-- Hide function testemail(form) { var emailok = true; if (form.EMAIL.value == "" || form.EMAIL.value.indexOf('@', 0) == -1) { alert("No valid e-mail address!"); emailok=false; } return emailok; } // --> </script> </HEAD> <BODY> <h3>Feedback form</h3> <FORM METHOD="POST" NAME="feedback" ACTION="mailto:gary.unthank@sunderland.ac.uk" onSubmit="return testemail(document.feedback)"> Please enter your comments about our product<BR> <TEXTAREA NAME="comments" ROWS=5 COLS=20></TEXTAREA> <BR><BR>Please enter your email address<BR> <INPUT TYPE="TEXT" NAME="EMAIL" > <BR><BR> <INPUT TYPE="submit" NAME="SUBMIT" VALUE="Submit"> </FORM></BODY> </HTML>
What is XML? An introduction to XML • XML = Extensible Markup Language • related to Standard Generalized Markup Language (SGML) • XML documents contain data only. They do not contain formatting information like HTML • Thus, it is up to the end user application to decide how the information is displayed • e.g. on a mobile phone or the Web via a Browser
<?xml version = "1.0"?> <!-- Your first XML page --> <article> <title>Example One: An example XML page</title> <date>Jan 01, 2002</date> <author> <firstname>Gary</firstname> <secondname>Unthank</secondname> </author> <summary>The first example XML document</summary> <content>A very short page of XML I created to show how XML is displayed on the Web </content> </article> XML ParserProcessing an XML document IE 5.5 msxml parser Sample XML document Checks the XML document and processes the data. In IE 5.5.+ this results in the the page being displayed
Example XML document <?xml version = "1.0"?> <!-- Your first XML page --> <article> <title>Example One: An example XML page</title> <date>Jan 01, 2002</date> <author> <firstname>Gary</firstname> <secondname>Unthank</secondname> </author> <summary>The first example XML document</summary> <content>A very short page of XML I created to show how XML is displayed on the Web </content> </article> XML declaration W3C current standard 1.0 Every XML document must contain one root element in which all others are placed within
XML - The semantic Web • XML permits document authors to create their own markup for any type of information • Alternatively XML documents can reference an external document that defines the document structure • Document Type Definition (DTD) • Schema (created in XML) • many parsers currently do not support Schemas due to it being a recent development • The aim being to make a Web that is machine readable i.e. search more effectively
Document Type Definition (DTD) A DTD enables an XML parser to verify whether an XML document is valid <!ELEMENT SimpleDTD ( title, date, author, summary, content )> <!ELEMENT title ( #PCDATA )> <!ELEMENT date ( #PCDATA )> <!ELEMENT author ( firstname, secondname )> <!ELEMENT firstname ( #PCDATA )> <!ELEMENT secondname ( #PCDATA )> <!ELEMENT summary ( #PCDATA )> <!ELEMENT content ( #PCDATA )> DTDs use Extended Backus-Naur Form e.g. the syntax, rules and structure #PCDATA Fields must contain parsed character data i.e. not <, >, and &
Adding a DTD referenceto an XML page <?xml version = "1.0"?> <!DOCTYPE SimpleDTD SYSTEM "simpleDTD.dtd"> <article> <title>Example two: An example XML page using DTD</title> <date>Jan 01, 2002</date> <author> <firstname>Gary</firstname> <secondname>Unthank</secondname> </author> <summary>The first example XML document using DTD</summary> <content>A very short page of XML I created to show how XML is displayed on the Web (also uses DTD) </content> </article> SYSTEM : External DTD file
XML Schema • Like XML documents schems are XML files (which have .xsd file extension) • Like DTDs these permit you to define the valid structure of an XML document • Schema also define valid element types • i.e. strings, number etc. • Read ‘Ian Stuart’s guide to Schema’ to see further example Schema. • http://lucas.ucs.ed.ac.uk/xml-schema
Example: XML Schema XML-Schema elements are prefixed by xsd: <?xml version = "1.0"?> <xsd:schema xmlns:xsd = "http://www.w3.ord/2001/XMLSchema" > <xsd:element name = "article"> <xsd:complexType> <xsd:element name = "title" type = "xsd:string"/> <xsd:element name = "date" type = "xsd:string"/> <xsd:element name = "author" type = "xsd:string"/> <xsd:complexType> <xsd:element name = "firstname" type = "xsd:string"/> <xsd:element name = "secondname" type = "xsd:string"/> </xsd:complexType> </xsd:element> <xsd:element name = "summary" type = "xsd:string"/> <xsd:element name = "content" type = "xsd:content"/> </xsd:complexType> </xsd:element> </xsd:schema>
Example: XML Schema Same as the previous example except a reference to the Schema is made Use elements defined by W3C <?xml version = "1.0"?> <article xmlns:xsi = "http://www.w3.ord/2001/XMLSchema-instance" xsi:MysimpleSchema = "simpleXMLSchema.xsd" > <title>Example three: An example XML page using an XML Schema</title> <date>Jan 01, 2002</date> <author> <firstname>Gary</firstname> <secondname>Unthank</secondname> </author> <summary>The first example XML document using an XML Schema</summary> <content>A very short page of XML I created to show how XML is displayed on the Web (also uses XML Schema) </content> </article> My XML Schema ! i.e. the file shown on the previous slide
Why bother ? What is wrong with HTML ? • XML permits users to evolve their own XML for their particular needs • BioML : for describing biopolymer sequence information • MathML : for displaying Mathematics on the Web • CML : for describing chemical information • Structuring documents with XML helps organise the web and will improve the Web • e.g. searching the Web will be easier as the meaning of the text and graphics will be defined
Machine Based Tutorial • The tutorial session requires you to: • Implement the JavaScript examples from today’s lecture and complete the further exercises • Additionally, create: • an XML page and a DTD page on a topic of your choice • an XML page and a Schema on a topic of your choice • Read through the first 6 hours (chapters) of the key text book (Bruce, B - Sams Teach Yourself Dreamweaver MX 2004 in 24 hours) in preparation for the next session.