1 / 110

JavaScript basics

JavaScript basics. Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at http://employees.oneonta.edu/higgindm/javascript/scriptexamples.html Text examples are in http://.../Higgindm/csci245/javascript as js or html under their text names.

reid
Download Presentation

JavaScript basics

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 basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at http://employees.oneonta.edu/higgindm/javascript/scriptexamples.html Text examples are in http://.../Higgindm/csci245/javascript as js or html under their text names

  2. background • JavaScript was originally called LiveScript (pre-’95) and was developed by Netscape. It changed its name to JavaScript and became a joint venture with Sun. ECMA developed a standard for JavaScript in the late 90s which is also an ISO standard and the official name of the language is ECMAScript. ECMA is at version 3 which corresponds to Netscape’s 1.5.

  3. Parts of JavaScript • Core: operators, expressions, statements and subprograms • Client-side: browser control and user interaction (ie., mouse-clicks, input) • Server-side: language features for use on a server – not covered in this text.

  4. Client-side JavaScript • XHTML-embedded scripting language. • Client-side JavaScript can substitute for some server-side functionality – especially things like checking form data to make sure phone numbers have an area code or ss numbers have the right format. • The browser interprets the JavaScript. • Client-side JavaScript cannot substitute for server-side file networking and database operations. • Applets – which are also client-side code (albeit delivered as byte-code to a client by a server) can often be replaced by JavaScript. • Since Applets can access nearly the full java API(s) they are much more powerful than JavaScript, but also harder to learn.

  5. interaction • Mouseclicks and form data can trigger java script functions. • DOM allows JavaScript to access and modify the CSS properties and content of any element of a displayed XHTML – enabling dynamic presentation. (this is covered in text chapter 6)

  6. interpreter • Browsers use their JavaScript interpreters to process scripts embedded in html. • Client-side input data checking is an important role for JavaScript. Without this, form information goes to the server, which must locate errors and relay them back to the client.

  7. Placement in head or body of html • Typically function definitions or code for handling events is placed in the head (and accessed if/as needed). • Script meant to be processed just once as part of document content goes in the body. Scripts in the head are cataloged but not interpreted at that time. Scripts in the body are processed as encountered.

  8. OO • javaScript is not OO, but Object based. There are no classes, polymorphism or object inheritance. • It does support something called prototype-based inheritance. • However, documents and elements are modeled with objects and so there is an object-sense to JavaScript.

  9. objects • JavaScript objects are collections of properties, roughly corresponding to C++ or Java objects. Each is a data or method property. Data properties may be primitives or references, although in JavaScript the latter are themselves usually called Objects. • The text will usually use properties to mean data properties and methods to mean method properties.

  10. Reserved words

  11. More about reserved words • Look at http://www.ecma.ch to see a list of future reserved words. • Also some predefined words: alert, open, self, java • // on a line signals comment to end • C++/Java multiline comment syntax: /*…*/ • Most browsers now do recognize JavaScript so placing script in special comments is less important, except it may cause validation problems for XHTML validators if the JavaScript includes recognized tags like <br/>

  12. So… • Use the usual comment introduction for scripts • You must close script with java/c++ comment on its own line followed by end of XHTML comment: • <!-- • Put JS here • // -->

  13. (skipping down in text ppt)Conversions • In the expression 7*”3” • JavaScript would try (and succeed) in converting “3” to 3 and perform the arithmetic because * is a numeric operator. • If “3” were replaced by “Bob” the result would be NaN

  14. output to the html document • Document.write(“here is your answer”,answer,”<br/>”); • Basically writes (dynamic) html content

  15. A really simple script <html> <body> usual content <script type="text/javascript"> <!-- var answer=1234; document.write("<br/>here is your answer",answer,"<br/>"); //now end script // --> </script> more usual html content </body> </html>

  16. the earlier example using an alert instead of document.write(..) <html> <body> usual content <script type="text/javascript"> <!-- var answer=1234; alert("here is your answer: " +answer); // --> </script> more usual html content </body> </html>

  17. First the alert, then the page

  18. Some more examples • http://employees.oneonta.edu/higgindm/javascript/AddNumsEx.html • http://employees.oneonta.edu/higgindm/javascript/scriptexamples.html • (many of my examples and code posted there) • http://employees.oneonta.edu/Higgindm/javascript/baseconverterEx2.html • http://employees.oneonta.edu/Higgindm/javascript/dialogboxEx.html

  19. Aside on two operators: “strict” comparison • === and !== disallow type conversions in evaluation. • The usual == and != allow type conversions of operands, so “3”==3 evaluates to true. • === disallows type conversions so 3===“3” evaluates to false.

  20. Text pg 149 quadratic roots <html> <body> <script type = "text/javascript"> <!-- // Get the coefficients of the equation from the user var a = prompt("What is the value of 'a'? \n", ""); var b = prompt("What is the value of 'b'? \n", ""); var c = prompt("What is the value of 'c'? \n", ""); // Compute the square root and denominator of the result var root_part = Math.sqrt(b * b - 4.0 * a * c); var denom = 2.0 * a; // Compute and display the two roots var root1 = (-b + root_part) / denom; var root2 = (-b - root_part) / denom; document.write("The first root is: ", root1, "<br />"); document.write("The second root is: ", root2, "<br />"); // --> </script> </body> </html>

  21. Previous html, first prompts for coefficients a,b,c

  22. Borders2.html: javascript prompts for table borders enhances html display

  23. borders2 uses switch statement <body> <script type = "text/javascript"> <!-- var bordersize; bordersize = prompt("Select a table border size \n" + "0 (no border) \n" + "1 (1 pixel border) \n" + "4 (4 pixel border) \n" + "8 (8 pixel border) \n"); switch (bordersize) { case "0": document.write("<table>"); break; case "1": document.write("<table border = '1'>"); break; case "4": document.write("<table border = '4'>"); break; case "8": document.write("<table border = '8'>"); break; default: document.write("Error - invalid choice: ", bordersize, "<br />"); }

  24. More of borders2 document.write("<caption> 2001 NFL Divisional Winners </caption>"); document.write("<tr>", "<th />", "<th> American Conference </th>", "<th> National Conference </th>", "</tr>", "<tr>", "<th> East </th>", "<td> New England Patriots </td>", "<td> Philadelphia Eagles </td>", "</tr>", "<tr>", "<th> Central </th>", "<td> Pittsburgh Steelers </td>", "<td> Chicago Bears </td>", "</tr>", "<tr>", "<th> West </th>", "<td> Oakland Raiders </td>", "<td> St. Louis Cardinals </td>", "</tr>", "</table>"); // --> </script> </body> </html>

  25. Date functions

  26. Javascript for first part of date <script type="text/javascript"> <!-- var today=new Date(); var dates=today.toLocaleString(); var day=today.getDay(); var month=today.getMonth(); var year=today.getFullYear(); var timeMillis=today.getTime(); var hour=today.getHours(); var minute=today.getMinutes(); var seconds=today.getSeconds(); var millis=today.getMilliseconds(); document.write("Date:" + dates + "<br/>", "Day:" + day + "<br/>", "Month:" + month + "<br/>", "Year:" + year + "<br/>", "Time Millis:" + timeMillis + "<br/>", "Hour:" + hour + "<br/>", "Minute:" + minute + "<br/>", "Second:" + seconds + "<br/>", "Millis:" + millis + "<br/>"); // --> </script>

  27. insert code for loop timer var start=new Date(); var product=1.00001; //add a loop for(var count=0;count<10000;count++) product=product+1.00001*1.0002-1.000008888/1.0001; var end=new Date(); var diff=end.getTime()-start.getTime(); document.write("<br/>loop took" + diff+"millis");

  28. Control examples • Text examples borders.html and date.html show switch and for statements. • JavaScript supports if and if…else, also while and do…while loops with java/c++ syntax.

  29. while loop example <script type = "text/javascript"> <!-- // whose factorial do you want? var a = prompt("Whose factorial?\n", ""); // Compute the factorial var fact= 1;//multiplicative identity var ctr=1; while(ctr<=a) { fact=fact*ctr; ctr++; } document.write("The factorial of ", a, " is "); document.write( fact, "<br />"); // --> </script>

  30. Factorials using while

  31. Fib numbers using while loop

  32. Entered 34 and 23

  33. Larger of 2 ints <script type = "text/javascript"> <!-- // var x = prompt("first?\n", ""); var y = prompt("second?\n", ""); //convert to numbers…. var a=Number(x); var b=Number(y); // Compute the ordering var big; var small; if (a>b){big=a;} else {big=b;} small=big==a?b:a; document.write("The bigger is", big, "the smaller "); document.write( small, "<br />"); // --> </script>

  34. Fixed previous to handle numbers

  35. another version <script type = "text/javascript"> <!-- var a = prompt("first?\n", ""); var b = prompt("second?\n", ""); // Compute the ordering for strings var x=parseInt(a); var y=parseInt(b); var big; var small; if (a>b){big=a;} else {big=b;} small=big==a?b:a; document.write("The bigger string is", big, "the smaller string is"); document.write( small, "<br />"); // Compute the ordering for ints if (x>y){big=x;} else {big=y;} small=big==x?y:x; document.write("The bigger int is", big, "the smaller int is"); document.write( small, "<br />"); // -->

  36. Lab 1 for javascript • Expand the previous example. The user enters 3 integers via prompts, display them in descending order.

  37. Objects • Objects can be created with the new keyword and call to a constructor as in var obj=new Object(); • The created object here has no initial properties. • Properties themselves can be objects, (or not), accessible via the dot or [] operator, as in var theprop=airplane.engine;//or var theprop=airplane[engine]; • The next slide shows how to set and display some properties.

  38. Displaying properties of an object in a loop <script type = "text/javascript"> <!-- var myAirplane = new Object(); myAirplane.make = "Cessna"; myAirplane.model = "Centurian"; myAirplane.horsepower="245hp"; myAirplane.seating=6; myAirplane.color="blue"; document.write("<p><b>The properties of airplane list is:</b> ", "<br />"); for (var prop in myAirplane) document.write(myAirplane[prop] + "<br />"); document.write("</p>"); // --> </script>

  39. Csci245/javascript/airplaneprops.html

  40. Arrays • Arrays are dynamically allocated from the heap in JavaScript • Only the locations actually assigned values occupy space in memory, despite array length. • Length is a R/W “property” so it can be set, and retrieved. myarray.length=100 myarray.length=44 • is a legal sequence. 44 would be length though there might not actually be anything allocated.

  41. Arrays…text example: insert names <body> <script type = "text/javascript"> <!-- // The original list of names var name_list = new Array("Al", "Betty", "Kasper", "Michael", "Roberto", "Zimbo"); var new_name, index, last; // Loop to get a new name and insert it while (new_name = prompt("Please type a new name", "")) { // Loop to find the place for the new name last = name_list.length - 1; while (last >= 0 && name_list[last] > new_name) { name_list[last + 1] = name_list[last]; last--; } // Insert the new name into its spot in the array name_list[last + 1] = new_name; // Display the new array document.write("<p><b>The new name list is:</b> ", "<br />"); for (index = 0; index < name_list.length; index++) document.write(name_list[index], "<br />"); document.write("</p>"); } //** end of the outer while loop // --> </script> </body>

  42. Inserting names…prompt

  43. Csci245/sebesta/Insert_names.html

  44. In case of errors in Firefox • Mozilla already provides some help in a javascript console in the tools menu.

  45. Debugging for JavaScript in Firefox • If you have your own machine, download firebug, a plugin for Firefox very helpful in debugging javascript (which will include the js libraries like Backbone and jQuery).

  46. Firebug session

  47. For IE • Go into tools/internet options/advanced tab and check/uncheck boxes as in next slide.

  48. For IE

  49. plunker • There are several javascript debugger/tester thingies out there. Plunker is one.

  50. Go to http://plnkr.co/edit/?p=catalogue

More Related