1 / 40

JavaScript

JavaScript. James Ohene-Djan Sandbox 2013. What is JavaScript?. JavaScript a scripting language developed to provide interactivity or behaviour to otherwise static HTML pages JavaScript, 1995, Netscape (c/w HTML, 1991) Jscript, 1996, Microsoft ECMAScript, standardized version of Jscript

cecile
Download Presentation

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 James Ohene-Djan Sandbox 2013

  2. What is JavaScript? • JavaScript a scripting language developed to provide interactivity or behaviour to otherwise static HTML pages • JavaScript, 1995, Netscape (c/w HTML, 1991) • Jscript, 1996, Microsoft • ECMAScript, standardized version of Jscript • JavaScript consists of lines of executable computer code and is usually embedded directly in HTML pages; • JavaScript is an interpreted language; • JavaScript can be used freely, and is supported by all major browsers (e.g. Netscape 4.5 + and Internet Explorer 4 + are augmented with JavaScript/Jscript interpreter – both of which are based on ECMAScript); • Client-side.

  3. What is JavaScript used for? • Lots of things, including: • Dynamic page elements; • Link confirmation; • Client side calculations; • Animated buttons; • Browser detection; • Cookies; • Client side form validation; • Drop down menus. • And more recently: • XML; • Scripted HTTP / Ajax (XMLHttpRequest); • Third party APIs • http://developer.yahoo.com/yuim • http://code.google.com/apis/gears/ • http://dev.live.com/virtualearth/

  4. JavaScript basics JavaScript is usually embedded inside HTML documents using the <script> tag. For example: • <html> • <head> • <title>JavaScript1</title> • </head> • <body> • <script type="text/javascript"> • alert("My very first JavaScript"); • </script> • </body> • </html>

  5. JavaScript can be placed in either the head or the body of an HTML document.Scripts in the head section are executed only when they are called, or when a particular event occurs. <html> <head> <title>JavaScript2</title> <script type="text/javascript"> function aFunction() { alert("Thanks for that"); } </script> </head> <body> <form name="aForm"> <input type="button" value="Click Here" onclick="aFunction()"> </form> </body> </html>

  6. Scripts in the body section will be executed when the page loads. Here the document.write() method is used to dynamically output HTML text into an HTML document while it is being loaded into the browser <html> <head> <title>JavaScript3</title> </head> <body> <script type="text/javascript"> document.write("<h1>In the body section</h1>"); </script> </body> </html>

  7. A web browser makes use of objects that can also be used in JavaScript programming. Each object has associated methods. Types of Object Objects of predefined classes Date, String, Math,…. Browser objects window, document,…. HTML objects link, form, button,…. …

  8. Browser objects • the starting point for most JavaScript programs. Initiated at browser startup • examples window document location history navigator

  9. window object – the window in which an html page loads methods • open(), close(), alert(), confirm(), prompt() example <html> <head><title>JavaScript4</title><head> <body> <h1>Window 1</h1> <script type="text/javascript"> varnewWindow; newWindow = window.open("http://www.bbc.co.uk"); </script> </body> </html>

  10. document object – the current html page • methods • write(), open(), …. • example <html> <head> <title>JavaScript5</title> <script type="text/javascript"> function docOpen() { document.open() document.write("<h3>Hello World!</h3>") } </script> </head> <body> <script type="text/javascript"> document.write("<h1>This heading was created on-the-fly</h1>"); </script> <form> <input type="button" onclick="docOpen()" value="Open a new document"> </form> </body> </html>

  11. location object - provides information about the origin of an html document, can be used to control the web page displayed by the browser. • Methods • reload(), replace() • attributes • host, href, pathname, port, protocol • example <html> <head><title>JavaScript6</title></head> <center> <script type="text/javascript"> document.write("href= " + location.href + "<br>"); document.write("pathname= " + location.pathname + "<br>"); document.write("protocol= " + location.protocol); </script> </centre> </html>

  12. navigator object – provides information about the user’s browser • attributes • appCodeName, appName, appVersion, platform, userAgent • example <html><head><title>JavaScript7</title></head> <center> <h1>Elements of the navigator object</h1> You are using the following browser:<p> <script type="text/javascript"> document.write("<table border=1 width=50%>"); document.write("<td>appCodeName</td>") document.write("<td>" + navigator.appCodeName); document.write("</td><tr>"); document.write("<td>appName</td>") document.write("<td>" + navigator.appName); document.write("</td><tr>"); document.write("<td>appVersion</td>") document.write("<td>" + navigator.appVersion); document.write("</td><tr>"); document.write("<td>platform</td>") document.write("<td>" + navigator.platform); document.write("</td><tr>"); document.write("<td>userAgent</td>") document.write("<td>" + navigator.userAgent); document.write("</td><tr>"); document.write("</table>"); </script> </center> </html>

  13. Prefined classes • Belong to ECMAScript language standard • Examples • Date, String, Math <html> <head><title>JavaScript8</title></head> <body> <script type="text/javascript"> var d = new Date() document.write(d.getDate()) document.write(".") document.write(d.getMonth() + 1) document.write(".") document.write(d.getFullYear()) </script> </body> </html>

  14. Pop up windows - alert <html> <head><title>JavaScript9</title><head> <title>Alert Example</title> </head> <body> <script type="text/javascript"> alert("This Site Is Not Suitable for Anybody Over the Age of 30"); </script> </body> </html>

  15. Pop up windows - confirm <html> <head> <title>JavaScript10</title> </head> <body> <script type="text/javascript"> var reply; reply=confirm("Do you agree?"); if (reply) { alert("GOOD!"); } else { alert("NEVER MIND."); } </script> </body> </html>

  16. Pop up windows - prompt <html> <head> <title>JavaScript11</title> </head> <body> <script type="text/javascript"> username=prompt("Please enter your name","Enter your name here"); document.write("<h2>Hello "+username+" Welcome to My Homepage</h2><br>") </script> </body> </html>

  17. Variables and Operators • Variables should be declared/defined using the var command. Variables should start with a letter and not contain any embedded spaces • Assigning a value to an undeclared variable implicitly declares the variable (globally) • Attempting to read the value of an undeclared variable causes a runtime error • Values are most commonly assigned to variables using the = operator. • <html> • <head> • <title>JavaScript12</title> • </head> • <body> • <script type="text/javascript"> • var username; • var age; • username="bjones"; • age=32; • document.write(username); • document.write(age); • </script> • </body> • </html>

  18. Arithmetic operators

  19. Assignment operators

  20. Comparison operators

  21. Concatenate two strings using the + operator <html> <head> <title>JavaScript13</title> </head> <body> <script type="text/javascript"> text1="Welcome to" text2="my homepage." document.write(text1+text2); document.write("<br>") document.write(text1+" "+text2); </script> </body> </html>

  22. Selection - if (condition) {action1} else {action2} <html> <head> <title>JavaScript14</title> </head> <body> <script type="text/javascript"> var d = new Date() var time = d.getHours() if (time < 12) { document.write("<b>Good morning</b>") } else { document.write("<b>Good afternoon</b>") } </script> </body> </html>

  23. Logical operators: AND, OR and NOT <html> <head> <title>JavaScript16</title> </head> <body> <script type="text/javascript"> cw1_grade=parseInt(prompt("Please enter your mark for cw1","1")); cw2_grade=parseInt(prompt("Please enter your mark for cw2","1")); if (cw1_grade && cw2_grade) { document.write("Well done you passed") } else if ((cw1_grade && !cw2_grade) || (!cw1_grade && cw2_grade)) document.write("Sorry, but you have failed - but only just"); else document.write("Sorry, you have failed big time"); </script> </body> </html>

  24. Functions • A function contains code that will be executed by an event or a call to that function. Functions are usually defined at the beginning of a .html file (in the head section) or as an external function in a separate file altogether (.js file). • A function is defined with a name, values ("arguments") and statements. Functions can return a value to the calling expression.

  25. Function example1 <html> <head> <title>JavaScript17</title> <script type="text/javascript"> function AddTwoNumbers(n1,n2) { answer=n1+n2 return(answer) } </script> </head> <body> <script type="text/javascript"> x=parseInt(prompt("Input first number","Number1 goes here")); y=parseInt(prompt("Input second number","Number2 goes here")); sum=AddTwoNumbers(x,y); document.write("The sum of the two numbers is "+sum+"<br>"); </script> </body> </html>

  26. Function example1 .html file <html> <head> <title>JavaScript18</title> <script SRC="javascript18.js"> </script> </head> <body> <script type="text/javascript"> x=parseInt(prompt("Input first number","Number1 goes here")); y=parseInt(prompt("Input second number","Number2 goes here")); sum=AddTwoNumbers(x,y); document.write("The sum of the two numbers is "+sum+"<br>"); </script> </body> </html> function AddTwoNumbers(n1,n2) { answer=n1+n2 return(answer) } javascript18.js

  27. JavaScript Loops <html> <head> <title>JavaScript19</title> </head> <body> <table border=3> <tr><td>INCHES</td><td>CMs</td></tr> <script type="text/javascript"> for (inches=1; inches<=30; inches=inches+1) { document.write("<tr><td>"+inches+"</td><td>"+(inches*2.54)+"</td></tr>"); } </script> </table> </body> </html>

  28. <html> <head> <title>JavaScript20</title> </head> <body> <table border=3> <tr><td>mile</td><td>km</td></tr> <script type="text/javascript"> mile=5 while (mile <= 100) { document.write("<tr><td>"+mile+"</td><td>"+(mile*1.6093)+"</td></tr>"); mile=mile+5 } </script> </table> </body> </html>

  29. JavaScript Arrays <html> <head><title>JavaScript21</title></head> <body> <script type="text/javascript"> var cities = new Array() cities[0] = " london" cities[1] = " paris" cities[2] = " rome" for (i=0;i<cities.length;i++) { document.write(cities[i] + "<br />") } </script> </body> </html>

  30. Array - sort <html> <head><title>JavaScript22</title></head> <body> <script type="text/javascript"> vararr = new Array(6) arr[0] = "evans" arr[1] = "smith" arr[2] = "davies" arr[3] = "collins" arr[4] = "bowen" arr[5] = "thomas" document.write(arr + "<br />") document.write(arr.sort()) </script> </body> </html>

  31. Last Updated Script <html> <head><title>JavaScript23</title></head> <body> <script type="text/javascript"> <!-- document.write('<center>Last updated : '); document.write(document.lastModified); document.write('</center>'); // --> </script> </body> </html> Notice the use of HTML comment (<!--and -->) and JavaScript comment (//). These are used to prevent browsers that do not support JavaScript from writing the JavaScript code to the screen as text.

  32. Browser Detection <html> <head> <title>JavaScript24</title> <script type="text/javascript"> alert(navigator.appName); if (navigator.appName.indexOf("Microsoft")!=-1) window.location.href = "http://www.microsoft.com"; else if (navigator.appName.indexOf("Netscape")!=-1) window.location.href = "http://www.netscape.com"; else document.write("Browser "+navigator.appName+" not supported"); </script> </head> <body> </body> </html> Makes use of the navigator object and the indexOf method. The navigator object holds name, version, etc. details of the browser. The indexOf() method returns the index value for where the parameter you give it first appears in the string it is invoked on, or the value -1 if the parameter (string) does not appear.

  33. Animated Buttons <html> <head> <title>JavaScript25</title> </head> <body> <a href="http://www.gold.ac.uk" onmouseOver="document.button1.src = 'computing-select.jpg'" onmouseOut="document.button1.src = 'computing-norm.jpg'"> <ImgSrc="computing-norm.jpg" name="button1" border=0 ></a> </body> </html>

  34. Onclick event <html> <head> <title>JavaScript27</title> </head> <body> <center>SELECT A BACKGROUND COLOUR.<p> <form> <input type=button value="Blue" onclick='document.bgColor="Blue";'> <input type=button value="Green“ onclick='document.bgColor="Green";'> <input type=button value="Red " onclick='document.bgColor="Red";'> </form> </body> </html>

  35. Form Validation – simple check for valid email <html> <head> <title>JavaScript28</title> <script type="text/javascript"> function validate_email() { found_at=document.form1.email_address.value.indexOf("@") if (found_at == -1) { alert("Not a valid e-mail") return false } } </script> </head> <body> <form name="form1" action=”form_ok.html" onsubmit="return validate_email()"> Enter your E-mail address: <input type="text" name="email_address"> <input type="submit" value="Send input"> </form> </body> </html>

  36. form_ok.html <html> <head> <title>Form Validation Example 1</title> </head> <body> <h1>Form has been sent</h1> </body> </html>

  37. Form Validation – less simple check for valid email • <html> • <head> • <title>JavaScript29</title> • <script type="text/javascript"> • function validate_email(e_address) • { • varemailFilter=/^.+@.+\..{2,3}$/; • varillegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/ • if (!(emailFilter.test(e_address))) • { • alert("Not a valid e-mail"); • return false; • } • if (e_address.match(illegalChars)) • { • alert("Not a valid e-mail"); • return false; • } • } • </script> • </head> • <body> • <form name="form1" • action="http://www.comp.glam.ac.uk/pages/staff/jmware/form_ok.html" • onsubmit="return validate_email(email_address.value)"> • Enter your E-mail address: • <input type="text" name="email_address"> • <input type="submit" value="Send input"> • </form> • </body> • </html>

  38. <html> <head> <title>JavaScrip30</title> <script type="text/javascript"> function validate() { day=document.myForm.day.value; if ( (parseInt(day) < 1) || (parseInt(day) > 31) ) { alert("day field invalid"); document.myForm.day.focus(); return false; } month=document.myForm.month.value.toLowerCase(); if ( (month!="jan") && (month!="feb") && (month!="mar") && (month!="apr") && (month!="may") && (month!="jun") && (month!="jul") && (month!="aug") && (month!="sep") && (month!="oct") && (month!="nov") && (month!="dec") ) { alert("invalid month"); document.myForm.month.focus(); return false; } year=document.myForm.year.value; current = new Date(); if (year != current.getFullYear()()) { alert("invalid year - only taking bookings for current year"); document.myForm.year.focus(); return false; } return true } </script> </head> <body> <form name="myForm" action="valid_page.html" onsubmit="return validate()"> Please supply required departure date<br><br>Day <input type="text" name="day" size=1 maxlength=2 value="01"><br>Month <input type="text" size=1 maxlength=3 value ="jan" name="month"><br>Year <input type="text" size=2 maxlength=4 value ="2003" name="year"><br><br> <input type="submit" value="validate date"> </form> </body> </html> Simple date validation

  39. Pre-loading media javascript31.html – will work in its own right (but slowly the first time you load it) <html> <head><title>javascript31</title> </head> <body> <imgsrc="http://heritage.stsci.edu/2003/06/dumbbell/0306a.jpg" width=300 height=300> <imgsrc="http://heritage.stsci.edu/2001/24/mars/0124a.jpg" width=300 height=300> <imgsrc="http://heritage.stsci.edu/2001/15/saturn/0115a.jpg" width=300 height=300> </body> </html>

  40. javascript32.html – preloads images, user might (or might not) visit display page <html> <head><title>javascript32</title> <script type="text/javascript"> if (document.images) { img1 = new Image(); img1.src = "http://heritage.stsci.edu/2003/06/dumbbell/0306a.jpg"; img2 = new Image(); img2.src = "http://heritage.stsci.edu/2001/24/mars/0124a.jpg"; img3 = new Image(); img3.src = "http://heritage.stsci.edu/2001/15/saturn/0115a.jpg"; } </SCRIPT> </head> <body> <a href="javascript31.html">Show Image</a> </body> </html> Test out above – effect will only be properly demonstrated if you delete temporary internet files before executing preloadimage.html (in browser select Tools->Internet Options->Delete Files

More Related