JavaScript and jQuery Fundamentals

7,702 views

Published on

Published in: Education
0 Comments
8 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
7,702
On SlideShare
0
From Embeds
0
Number of Embeds
1,468
Actions
Shares
0
Downloads
507
Comments
0
Likes
8
Embeds 0
No embeds

No notes for slide

JavaScript and jQuery Fundamentals

  1. 1. <ul>JavaScript </ul><ul>Svilen Ivanov </ul><ul>Bulgarian Association of Software Developers </ul><ul>www.devbg.org </ul>
  2. 2. <ul>Definition </ul><ul><li>What is DHTML? </li></ul><ul><ul><li>Collection of technologies used together to create interactive and animated web sites </li></ul></ul><ul><ul><li>Makes possible a Web page to react and change in response to the user's actions </li></ul><li>DHTML Technologies </li></ul><ul><ul><li>(X)HTML
  3. 3. CSS
  4. 4. JavaScript
  5. 5. DOM </li></ul></ul>
  6. 6. <ul>DTHML = HTML + CSS + JavaScript </ul><ul><li>HTML defines Web sites content through semantic tags </li><ul><li>headings, paragraphs, lists, … </li></ul><li>CSS defines 'rules' or 'styles' for presenting every aspect of an HTML document </li><ul><li>Font (family, size, color, weight, etc.)
  7. 7. Background (color, image, position, repeat)
  8. 8. Position and layout (of any object on the page) </li></ul><li>JavaScript defines dynamic behavior </li><ul><li>Programming logic for interaction with the user, to handle events, etc. </li></ul></ul>
  9. 9. <ul>JavaScript </ul><ul><li>JavaScript is a front-end scripting language developed by Netscape for dynamic content </li><ul><li>Lightweight, but with limited capabilities
  10. 10. Can be used as object-oriented language </li></ul><li>Client-side technology </li><ul><li>Embedded in your HTML page
  11. 11. Interpreted by the Web browser </li></ul><li>Simple and flexible
  12. 12. Powerful to manipulate the DOM </li></ul>
  13. 13. <ul>JavaScript Advantages </ul><ul><li>JavaScript allows interactivity such as: </li><ul><li>Implementing form validation
  14. 14. React to user actions, e. g. handle key press
  15. 15. Changing an image on moving mouse over it
  16. 16. Sections of a page appearing and disappearing
  17. 17. Performing complex calculations
  18. 18. Custom HTML controls, e.g. scrollable table </li></ul><li>Implementing AJAX functionality: </li><ul><li>Partial page updates
  19. 19. Content loading and changing dynamically </li></ul></ul>
  20. 20. <ul>What Can JavaScript Do? </ul><ul><li>Can handle events
  21. 21. Can read and write HTML elements and modify the DOM tree
  22. 22. Can validate form data
  23. 23. Can access / modify browser cookies
  24. 24. Can detect the user’s browser and OS
  25. 25. Can be used as object-oriented language
  26. 26. Can handle exceptions
  27. 27. Can perform asynchronous server calls (AJAX) </li></ul>
  28. 28. <ul>The First Script </ul><ul><!-- first-script.html --> <li><html>
  29. 29. <body>
  30. 30. <script type=&quot;text/javascript&quot;>
  31. 31. alert('Hello JavaScript!');
  32. 32. </script>
  33. 33. </body>
  34. 34. </html> </li></ul>
  35. 35. <ul>Another Small Example </ul><ul><!-- small-example.html --> <li><html>
  36. 36. <body>
  37. 37. <script type=&quot;text/javascript&quot;>
  38. 38. document.write('JavaScript rulez!');
  39. 39. </script>
  40. 40. </body>
  41. 41. </html> </li></ul>
  42. 42. <ul>Using JavaScript Code </ul><ul><li>The JavaScript code can be placed in: </li><ul><li><script> tag in the head
  43. 43. <script> tag in the body – not recommended
  44. 44. External files, linked via <script> tag the head
  45. 45. Files usually have .js extension
  46. 46. Highly recommended
  47. 47. The .js files get cached by the browser </li></ul></ul><ul><script src=&quot;scripts.js&quot; type=&quot;text/javscript&quot;> <li><!– code placed here will not be executed! -->
  48. 48. </script> </li></ul>
  49. 49. <ul>JavaScript – When is Executed? </ul><ul><li>JavaScript code is executed during the page loading or when the browser fires an event </li><ul><li>All statements are executed at page loading
  50. 50. Some statements just define functions that can be called later </li></ul><li>Function calls or code can be attached as &quot;event handlers&quot; via tag attributes </li><ul><li>Executed when the event is fired by the browser </li></ul></ul><ul><li><img src=&quot;logo.gif&quot; onclick=&quot;alert('clicked!')&quot; /> </li></ul>
  51. 51. <ul>Calling a JavaScript Function from Event Handler – Example </ul><ul><li><!-- image-onclick.html -->
  52. 52. <html>
  53. 53. <head>
  54. 54. <script type=&quot;text/javascript&quot;>
  55. 55. function test (message) {
  56. 56. alert(message);
  57. 57. }
  58. 58. </script>
  59. 59. </head>
  60. 60. <body>
  61. 61. <img src=&quot;logo.gif&quot;
  62. 62. onclick=&quot;test('clicked!')&quot; />
  63. 63. </body>
  64. 64. </html> </li></ul>
  65. 65. <ul>Using External Script Files </ul><ul><li><html>
  66. 66. <head>
  67. 67. <script src=&quot;sample.js&quot; type=&quot;text/javascript&quot;>
  68. 68. <!-- The <script> tag is always empty. -->
  69. 69. </script>
  70. 70. </head>
  71. 71. <body>
  72. 72. <button onclick=&quot;sample()&quot; value=&quot;Call JavaScript
  73. 73. function from sample.js&quot; />
  74. 74. </body>
  75. 75. </html> </li></ul><ul><li>function sample() {
  76. 76. alert('Hello from sample.js!')
  77. 77. } </li></ul><ul><li>Using external script files:
  78. 78. External JavaScript file: </li></ul>
  79. 79. <ul>The JavaScript Syntax </ul>
  80. 80. <ul>JavaScript Syntax </ul><ul><li>The JavaScript syntax is similar to C# and Java </li><ul><li>Operators (+, *, =, !=, &&, ++, …)
  81. 81. Variables (typeless)
  82. 82. Conditional statements (if, else)
  83. 83. Loops (for, while)
  84. 84. Arrays (my_array[]) and associative arrays (my_array['abc'])
  85. 85. Functions (can return value)
  86. 86. Function variables (like the C# delegates) </li></ul></ul>
  87. 87. <ul>JavaScript Data Types </ul><ul><li>JavaScript data types: </li><ul><li>Numbers (integer, floating-point)
  88. 88. Boolean (true / false) </li></ul><li>String type – string of characters
  89. 89. Arrays
  90. 90. Associative arrays (hash tables) </li></ul><ul><li>var myName = &quot;You can use both single or double quotes for strings&quot;; </li></ul><ul><li>var my_array = [1, 5.3, &quot;aaa&quot;]; </li></ul><ul><li>var my_hash = {a:2, b:3, c:&quot;text&quot;}; </li></ul>
  91. 91. <ul>Everything is Object </ul><ul><li>Every variable can be considered as object </li><ul><li>For example strings and arrays have member functions: </li></ul></ul><ul><li>// file: objects.html
  92. 92. var test = &quot;some string&quot;;
  93. 93. alert(test[7]); // shows letter 'r'
  94. 94. alert(test.charAt(5)); // shows letter 's'
  95. 95. alert(&quot;test&quot;.charAt(1)); // shows letter 'e'
  96. 96. alert(&quot;test&quot;.substring(1,3)); // shows 'es'
  97. 97. var arr = [1,3,4];
  98. 98. alert (arr.length); // shows 3
  99. 99. arr.push(7); // appends 7 to end of array
  100. 100. alert (arr[3]); // shows 7 </li></ul>
  101. 101. <ul>String Operations </ul><ul><li>The + operator joins strings (slow)
  102. 102. What is &quot;11&quot; + 11?
  103. 103. Converting string to number: </li></ul><ul><li>string1 = &quot;lol &quot;;
  104. 104. string2 = &quot;cats&quot;;
  105. 105. alert(string1 + string2); // lol cats </li></ul><ul><li>alert(parseInt(&quot;11&quot;) + 11); // 22 </li></ul><ul><li>alert(parseInt(&quot;011&quot;) + 11); // 20 ???
  106. 106. alert(parseInt(&quot;011&quot;, 10) + 11); // 22 </li></ul><ul><li>alert(&quot;11&quot; + 11); // 1111 </li></ul>
  107. 107. <ul>Arrays Operations and Properties </ul><ul><li>Declaring new empty array:
  108. 108. Declaring an array holding few elements:
  109. 109. Appending an element / getting the last element:
  110. 110. Reading the number of elements (array length):
  111. 111. Finding element's index in the array: </li></ul><ul><li>var arr1 = new Array(); var arr2 = []; </li></ul><ul><li>var arr = [1, 2, 3, 4, 5]; </li></ul><ul><li>arr.push(3); var element = arr.pop(); </li></ul><ul><li>arr.length; </li></ul><ul><li>arr.indexOf(1); </li></ul>
  112. 112. <ul>Standard Popup Boxes </ul><ul><li>Alert box with text and [OK] button </li><ul><li>Just a message shown in a dialog box: </li></ul><li>Confirmation box </li><ul><li>Contains text, [OK] button and [Cancel] button: </li></ul><li>Prompt box </li><ul><li>Contains text, input field with default value: </li></ul></ul><ul><li>alert(&quot;Some text here&quot;); </li></ul><ul><li>confirm(&quot;Are you sure?&quot;); </li></ul><ul><li>prompt (&quot;enter amount&quot;, 10); </li></ul>
  113. 113. <ul>Sum of Numbers – Example (1) </ul><ul><li><!-- sum-of-numbers.html -->
  114. 114. <html>
  115. 115. <head>
  116. 116. <title>JavaScript Demo</title>
  117. 117. <script type=&quot;text/javascript&quot;>
  118. 118. function calcSum() {
  119. 119. value1 =
  120. 120. parseInt(document.mainForm.textBox1.value);
  121. 121. value2 =
  122. 122. parseInt(document.mainForm.textBox2.value);
  123. 123. sum = value1 + value2;
  124. 124. document.mainForm.textBoxSum.value = sum;
  125. 125. }
  126. 126. </script>
  127. 127. </head> </li></ul>
  128. 128. <ul>Sum of Numbers – Example (2) </ul><ul><li><body>
  129. 129. <form name=&quot;mainForm&quot;>
  130. 130. <input type=&quot;text&quot; name=&quot;textBox1&quot; /> <br/>
  131. 131. <input type=&quot;text&quot; name=&quot;textBox2&quot; /> <br/>
  132. 132. <input type=&quot;button&quot; value=&quot;Process&quot;
  133. 133. onclick=&quot;calcSum()&quot; />
  134. 134. <input type=&quot;text&quot; name=&quot;textBoxSum&quot;
  135. 135. readonly=&quot;readonly&quot;/>
  136. 136. </form>
  137. 137. </body>
  138. 138. </html> </li></ul>
  139. 139. <ul>JavaScript Prompt – Example </ul><ul><li>price = prompt(&quot;Enter the price&quot;, &quot;10.00&quot;);
  140. 140. alert('Price + VAT = ' + price * 1.2); </li></ul>
  141. 141. <ul>Conditional Statement (if) </ul><ul><li>unitPrice = 1.30;
  142. 142. if (quantity > 100) {
  143. 143. unitPrice = 1.20;
  144. 144. } </li></ul><ul><li>Greater than: >
  145. 145. Less than: <
  146. 146. Greater than or equal to: >=
  147. 147. Less than or equal to: <=
  148. 148. Equal: ==
  149. 149. Not equal: != </li></ul>
  150. 150. <ul>Conditional Statement (if) (2) </ul><ul><li>// conditional-statements.html
  151. 151. var a = 0;
  152. 152. var b = true;
  153. 153. if ( typeof(a) ==&quot;undefined&quot; || typeof(b) ==&quot;undefined&quot;) {
  154. 154. document.write(&quot;Variable a or b is undefined.&quot;);
  155. 155. }
  156. 156. else if (!a && b) {
  157. 157. document.write(&quot;a==0; b==true;&quot;);
  158. 158. } else {
  159. 159. document.write(&quot;a==&quot; + a + &quot;; b==&quot; + b + &quot;;&quot;);
  160. 160. } </li></ul><ul><li>The condition may be of Boolean or integer type: </li></ul>
  161. 161. <ul>Switch Statement </ul><ul><li>// switch-statements.html
  162. 162. switch (variable) {
  163. 163. case 1:
  164. 164. // do something
  165. 165. break;
  166. 166. case 'a':
  167. 167. // do something else
  168. 168. break;
  169. 169. case 3.14:
  170. 170. // another code
  171. 171. break;
  172. 172. default:
  173. 173. // something completely different
  174. 174. } </li></ul><ul><li>The switch statement works like in C#: </li></ul>
  175. 175. <ul>Loops </ul><ul><li>// loops.html
  176. 176. var counter;
  177. 177. for (counter=0; counter<4; counter++) {
  178. 178. alert(counter);
  179. 179. } </li></ul><ul><li>for (var key in haystack); </li></ul><ul><li>while (counter < 5) {
  180. 180. alert(++counter);
  181. 181. } </li></ul><ul><li>Like in C# </li><ul><li>for loop
  182. 182. while loop
  183. 183. do … while loop </li></ul></ul>
  184. 184. <ul>Functions </ul><ul><li>function average(a, b, c) {
  185. 185. var total;
  186. 186. total = a+b+c;
  187. 187. return total/3;
  188. 188. } </li></ul><ul><li>Code structure – splitting code into parts </li><ul><li>Data comes in, processed, result returned
  189. 189. Anonymous functions </li></ul></ul><ul><li>var average = function (a, b, c) { ... }
  190. 190. var res1 = average(1,2,3);
  191. 191. var myAvg = average;
  192. 192. var res2 = myAvg(1,2,3); </li></ul>
  193. 193. <ul><li>Function Arguments and Return Value </li></ul><ul><li>Functions are not required to return a value </li><ul><li>When calling function it is not obligatory to specify all of its arguments
  194. 194. The function has access to all the arguments passed via arguments array </li></ul></ul><ul><li>function sum() {
  195. 195. var sum = 0;
  196. 196. for (var i = 0; i < arguments.length; i ++)
  197. 197. sum += parseInt(arguments[i]);
  198. 198. return sum;
  199. 199. }
  200. 200. alert(sum(1, 2, 4)); </li></ul>
  201. 201. <ul><li>Objects </li></ul><ul><li>Classes are functions
  202. 202. Objects are associative arrays
  203. 203. this refers to the owning code
  204. 204. new copies the prototype into new reference </li></ul><ul><li>person = new Object()
  205. 205. person.first = &quot;Tim&quot;
  206. 206. person.last = &quot;Scarfe&quot;
  207. 207. person.sayHello = function() {
  208. 208. alert(&quot;Hello, &quot; + this.first + &quot; &quot; + this.last);
  209. 209. } </li></ul><ul><li>person.sayHello(); </li></ul>
  210. 210. <ul><li>Objects (2) </li></ul><ul><li>function User(first, last) {
  211. 211. this.first = first;
  212. 212. this.last = last;
  213. 213. this.sayHello = function() {
  214. 214. alert(&quot;Hello, &quot; + this.first
  215. 215. + &quot; &quot; + this.last);
  216. 216. }
  217. 217. }
  218. 218. var svi = new User(&quot;Svi&quot;, &quot;Ivanov&quot;);
  219. 219. var alex = new User(&quot;Alex&quot;, &quot;Ivanova&quot;);
  220. 220. svi.sayHello();
  221. 221. alex.sayHello(); </li></ul>
  222. 222. <ul>Document Object Model (DOM) </ul>
  223. 223. <ul><li>Document Object Model (DOM) </li></ul><ul><li>Every HTML element is accessible via the JavaScript DOM API </li><ul><li>Most DOM objects can be manipulated by the programmer
  224. 224. The event model lets a document to react when the user does something on the page </li></ul><li>Advantages </li><ul><li>Create interactive pages
  225. 225. Updates the objects of a page without reloading it </li></ul></ul>
  226. 226. <ul><li>Accessing Elements </li></ul><ul><li>Access elements via their ID attribute
  227. 227. Via the name attribute
  228. 228. Via tag name </li><ul><li>Returns array of descendant <img> elements of the element &quot;el&quot; </li></ul></ul><ul><li>var elem = document.getElementById(&quot;some_id&quot;) </li></ul><ul><li>var arr = document.getElementsByName(&quot;some_name&quot;) </li></ul><ul><li>var imgTags = el.getElementsByTagName(&quot;img&quot;) </li></ul>
  229. 229. <ul><li>DOM Manipulation </li></ul><ul><li>Once we access an element, we can read and write its attributes </li></ul><ul><li>// DOM-manipulation.html
  230. 230. function change(state) {
  231. 231. var lampImg = document.getElementById(&quot;lamp&quot;);
  232. 232. lampImg.src = &quot;lamp_&quot; + state + &quot;.png&quot;;
  233. 233. var statusDiv =
  234. 234. document.getElementById(&quot;statusDiv&quot;);
  235. 235. statusDiv.innerHTML = &quot;The lamp is &quot; + state&quot;;
  236. 236. }
  237. 237.
  238. 238. <img src=&quot;test_on.gif&quot; onmouseover=&quot;change('off')&quot;
  239. 239. onmouseout=&quot;change('on')&quot; id=&quot;lamp&quot; />
  240. 240. <div id=”status”></div> </li></ul>
  241. 241. <ul><li>Common Element Properties (2) </li></ul><ul><li>className – the class attribute of the tag
  242. 242. innerHTML – holds all the entire HTML code inside the element
  243. 243. Read-only properties with information for the current element and its state </li><ul><li>tagName, offsetWidth, offsetHeight, scrollHeight, scrollTop, nodeType, etc… </li></ul></ul>
  244. 244. <ul><li>Accessing Elements through the DOM Tree Structure </li></ul><ul><li>We can access elements in the DOM through some tree manipulation properties: </li><ul><li>element.childNodes
  245. 245. element.parentNode
  246. 246. element.nextSibling
  247. 247. element.previousSibling
  248. 248. element.firstChild
  249. 249. element.lastChild </li></ul></ul>
  250. 250. <ul><li>Accessing Elements through the DOM Tree – Example </li></ul><ul><li>// accessing-elements-demo.html
  251. 251. var el = document.getElementById('div_tag');
  252. 252. alert (el.childNodes[0].value);
  253. 253. alert (el.childNodes[1].
  254. 254. getElementsByTagName('span').id);
  255. 255.
  256. 256. <div id=&quot;div_tag&quot;>
  257. 257. <input type=&quot;text&quot; value=&quot;test text&quot; />
  258. 258. <div>
  259. 259. <span id=&quot;test&quot;>test span</span>
  260. 260. </div>
  261. 261. </div>
  262. 262. Warning: may not return what you expected due to Browser differences </li></ul>
  263. 263. <ul>The HTML DOM Event Model </ul>
  264. 264. <ul><li>The HTML DOM Event Model </li></ul><ul><li>JavaScript can register event handlers
  265. 265. Events are fired by the Browser and are sent to the specified JavaScript event handler function
  266. 266. Can be set with HTML attributes:
  267. 267. Can be accessed through the DOM: </li></ul><ul><li><img src=&quot;test.gif&quot; onclick=&quot;imageClickHandler()&quot; /> </li></ul><ul><li>var img = document.getElementById(&quot;myImage&quot;);
  268. 268. img.onclick = imageClickHandler; // function ref </li></ul>
  269. 269. <ul><li>The HTML DOM Event Model (2) </li></ul><ul><li>All event handlers receive one parameter </li><ul><li>It brings information about the event
  270. 270. Contains the type of the event (mouse click, key press, etc.)
  271. 271. Data about the location where the event has been fired (e.g. mouse coordinates)
  272. 272. Holds a reference to the event sender
  273. 273. E.g. the button that was clicked </li></ul></ul>
  274. 274. <ul><li>The HTML DOM Event Model (3) </li></ul><ul><li>Holds information about the state of [Alt], [Ctrl] and [Shift] keys
  275. 275. Some browsers do not send this object, but place it in the document.event
  276. 276. Some of the names of the event’s object properties are browser-specific </li></ul>
  277. 277. <ul><li>Common DOM Events </li></ul><ul><li>Mouse events: </li><ul><li>onclick, onmousedown, onmouseup
  278. 278. onmouseover, onmouseout, onmousemove </li></ul><li>Key events: </li><ul><li>Onkeypress, onkeydown, onkeyup
  279. 279. Only for input fields / global interface </li></ul><li>Interface events: </li><ul><li>onblur, onfocus
  280. 280. onscroll </li></ul></ul>
  281. 281. <ul><li>Common DOM Events (2) </li></ul><ul><li>Form events </li><ul><li>onchange – for input fields
  282. 282. onsubmit </li><ul><li>Allows you to cancel a form submission
  283. 283. Useful for form validation </li></ul></ul><li>Miscellaneous events </li><ul><li>onload, onunload </li><ul><li>Allowed only for the <body> element
  284. 284. Fires when all content on the page was loaded / unloaded </li></ul></ul></ul>
  285. 285. <ul><li>onload Event – Example </li></ul><ul><li><!-- onload.html -->
  286. 286. <html>
  287. 287. <head>
  288. 288. <script type=&quot;text/javascript&quot;>
  289. 289. function greet() {
  290. 290. alert(&quot;Loaded.&quot;);
  291. 291. }
  292. 292. </script>
  293. 293. </head> 
  294. 294. <body onload=&quot;greet()&quot; >
  295. 295. </body>
  296. 296. </html> </li></ul>
  297. 297. <ul>The Built-In Browser Objects </ul>
  298. 298. <ul><li>Built-in Browser Objects </li></ul><ul><li>The browser provides some read-only data via: </li><ul><li>window - the top node of the DOM tree, represents the browser's window
  299. 299. document - holds information the current loaded document
  300. 300. screen - holds the user’s display properties
  301. 301. browser - holds information about the browser </li></ul></ul>
  302. 302. <ul><li>DOM Hierarchy – Example </li></ul>window navigator screen location document history document form form input
  303. 303. <ul><li>Opening New Window – Example </li></ul><ul><li><!-- window-open.html -->
  304. 304. var newWindow = window.open(&quot;&quot;, &quot;sampleWindow&quot;,
  305. 305. &quot;width=300, height=100, menubar=yes,
  306. 306. status=yes, resizable=yes&quot;);
  307. 307. newWindow.document.write(
  308. 308. &quot;<html><head><title>
  309. 309. Sample Title</title>
  310. 310. </head><body><h1>Sample
  311. 311. Text</h1></body></html>&quot;);
  312. 312. newWindow.status =
  313. 313. &quot;Hello folks&quot;; </li></ul>
  314. 314. <ul><li>The Navigator Object </li></ul><ul><li>alert(window.navigator.userAgent); </li></ul>The browser window The navigator in the browser window The userAgent (browser ID)
  315. 315. <ul><li>The Screen Object </li></ul><ul><li>The screen object contains information about the display: </li></ul><ul><li>window.moveTo(0, 0);
  316. 316. x = screen.availWidth;
  317. 317. y = screen.availHeight;
  318. 318. window.resizeTo(x, y); </li></ul>
  319. 319. <ul><li>Document and Location </li></ul><ul><li>document object </li><ul><li>Provides some built-in arrays of specific objects on the currently loaded Web page </li></ul><li>document.location </li><ul><li>Used to access the currently open URL or redirect the browser </li></ul></ul><ul><li>document.links[0].href = &quot;yahoo.com&quot;;
  320. 320. document.write(&quot;This is some <b>bold text</b>&quot;); </li></ul><ul><li>document.location.href = &quot; http://www.yahoo.com/ &quot;; </li></ul><ul><li>document.location.replace(&quot; http://www.yahoo.com/ &quot;) </li></ul>
  321. 321. <ul><li>Form Validation – Example </li></ul><ul><li>// form-validation.html
  322. 322. function checkForm()
  323. 323. {
  324. 324. var valid = true;
  325. 325. if (document.mainForm.firstName.value == &quot;&quot;) {
  326. 326. alert(&quot;Please type in your first name!&quot;);
  327. 327. document.getElementById(&quot;firstNameError&quot;).
  328. 328. style.display = &quot;inline&quot;;
  329. 329. valid = false;
  330. 330. }
  331. 331. return valid;
  332. 332. }
  333. 333.
  334. 334. <form name=&quot;mainForm&quot; onsubmit=&quot;return checkForm()&quot;>
  335. 335. <input type=&quot;text&quot; name=&quot;firstName&quot; />
  336. 336.
  337. 337. </form> </li></ul>
  338. 338. <ul><li>The Math Object </li></ul><ul><li>The Math object provides some mathematical functions </li></ul><ul><li>// math.html
  339. 339. for (i=1; i<=20; i++) {
  340. 340. var x = Math.random();
  341. 341. x = 10*x + 1;
  342. 342. x = Math.floor(x);
  343. 343. document.write(
  344. 344. &quot;Random number (&quot; +
  345. 345. i + &quot;) in range &quot; +
  346. 346. &quot;1..10 --> &quot; + x +
  347. 347. &quot;<br/>&quot;);
  348. 348. } </li></ul>
  349. 349. <ul><li>The Date Object </li></ul><ul><li>The Date object provides date / calendar functions </li></ul><ul><li>// dates.html
  350. 350. var now = new Date();
  351. 351. var result = &quot;It is now &quot; + now;
  352. 352. document.getElementById(&quot;timeField&quot;)
  353. 353. .innerText = result;
  354. 354. ...
  355. 355. <p id=&quot;timeField&quot;></p> </li></ul>
  356. 356. <ul><li>Timers: setTimeout() </li></ul><ul><li>Make something happen (once) after a fixed delay:
  357. 357. Use timer handle to cancel </li></ul><ul><li>function bang() { ... }
  358. 358. var timer1 = setTimeout('bang()', 5000); </li></ul><ul><li>var timer2 = setTimeout(bang, 5000); </li></ul><ul><li>clearTimeout(timer); </li></ul>
  359. 359. <ul><li>Timers: setInterval() </li></ul><ul><li>Make something happen repeatedly at fixed intervals:
  360. 360. Use timer handle to cancel </li></ul><ul><li>function clock() { ... }
  361. 361. var timer = setInterval('clock()', 1000); </li></ul><ul><li>clearInterval(timer); </li></ul>
  362. 362. <ul><li>Timer – Example </li></ul><ul><li><!-- timer-demo.html -->
  363. 363. <script type=&quot;text/javascript&quot;>
  364. 364. function timerFunc() {
  365. 365. var now = new Date();
  366. 366. var hour = now.getHours();
  367. 367. var min = now.getMinutes();
  368. 368. var sec = now.getSeconds();
  369. 369. document.getElementById(&quot;clock&quot;).value =
  370. 370. &quot;&quot; + hour + &quot;:&quot; + min + &quot;:&quot; + sec;
  371. 371. }
  372. 372. setInterval('timerFunc()', 1000);
  373. 373. </script>
  374. 374. <input type=&quot;text&quot; id=&quot;clock&quot; /> </li></ul>
  375. 375. <ul>Debugging JavaScript </ul>
  376. 376. <ul><li>Debugging JavaScript </li></ul><ul><li>Modern browsers have JavaScript console where errors in scripts are reported </li><ul><li>Errors may differ across browsers </li></ul><li>Several tools to debug JavaScript </li><ul><li>Microsoft Script Editor </li><ul><li>Add-on for Internet Explorer
  377. 377. Supports breakpoints, watches
  378. 378. JavaScript statement debugger; opens the script editor </li></ul></ul></ul>
  379. 379. <ul><li>Firebug </li></ul><ul><li>Firebug – Firefox add-on for debugging JavaScript, CSS, HTML </li><ul><li>Supports breakpoints, watches, JavaScript console editor
  380. 380. Very useful for CSS and HTML too
  381. 381. You can edit all the document real-time: CSS, HTML, etc
  382. 382. Shows how CSS rules apply to element
  383. 383. Shows Ajax requests and responses
  384. 384. Firebug is written mostly in JavaScript </li></ul></ul>
  385. 385. <ul><li>Firebug (2) </li></ul>
  386. 386. <ul><li>JavaScript Console Object </li></ul><ul><li>The console object exists only if there is a debugging tool that supports it </li><ul><li>Used to write log messages at runtime </li></ul><li>Methods of the console object: </li><ul><li>debug(message)
  387. 387. info(message)
  388. 388. log(message)
  389. 389. warn(message)
  390. 390. error(message) </li></ul></ul>
  391. 391. <ul><li>jQuery </li></ul><ul><li>Cross-browser JavaScript library designed to simplify the client-side scripting of HTML
  392. 392. Why do we need it? </li><ul><li>Wraps browser quirks into unified API
  393. 393. Write less code
  394. 394. Designed to make it easier to navigate a document
  395. 395. Has a lot of plugins
  396. 396. Very mature, widely deployed </li></ul></ul>
  397. 397. <ul><li>jQuery introduction </li></ul><ul><li>Fast and concise JavaScript library that simplifies HTML document traversing, event handling, animating, and Ajax interaction
  398. 398. Why do we need it? </li><ul><li>Wraps browser quirks into unified API
  399. 399. Write less code
  400. 400. Designed to make it easier to navigate a document
  401. 401. Has a lot of plugins
  402. 402. Very mature, widely deployed </li></ul></ul>
  403. 403. <ul><li>jQuery Example </li></ul><ul><li>// jquery-basic.html
  404. 404. function toggle_visibility_pure_js(id) {
  405. 405. var e = document.getElementById(id);
  406. 406. if (e.style.display == 'none') {
  407. 407. e.style.display = 'block';
  408. 408. } else {
  409. 409. e.style.display = 'none';
  410. 410. }
  411. 411. }
  412. 412. function toggle_visibility_jquery(id) {
  413. 413. $(&quot;#&quot; + id).toggle(&quot;slow&quot;);
  414. 414. } </li></ul>
  415. 415. <ul><li>jQuery Selectors </li></ul><ul><li>The $ (“dollar”) function </li><ul><li>Convenient way to select element(s) of DOM using CSS syntax </li></ul></ul><ul><li>$(&quot;#foo&quot;); // element with id=”foo”, similar to
  416. 416. // document.getElementById() </li></ul><ul><li>$(&quot;div&quot;); // all &quot;div&quot; tags
  417. 417. $(&quot;div.red&quot;); // all &quot;div&quot; tags with class=&quot;red&quot;
  418. 418. $(&quot;div p&quot;); // all paragraphs within <div>
  419. 419. $(&quot;#foo > div&quot;); // all divs that are immediate
  420. 420. // children of tag with id=&quot;foo&quot;
  421. 421. $(&quot;input[type='button']&quot;) // all buttons on the page
  422. 422. $(&quot;*&quot;); // all DOM nodes
  423. 423. $(&quot;div:first&quot;); // first div of the document
  424. 424. $(&quot;div:even); // selects 1 st , 3 rd , 5 th etc. “div” </li></ul>
  425. 425. <ul><li>jQuery Methods </li></ul><ul><li>You can manipulate selected elements: </li><ul><li>Changing styles, text, attributes
  426. 426. Attaching event handlers and processing events
  427. 427. Allows method's chaining </li></ul></ul><ul><li>// adds click handler, changes style/text
  428. 428. $(&quot;div&quot;).addClass(&quot;yellowBox&quot;)
  429. 429. .text(&quot;I'm div&quot;)
  430. 430. .css(&quot;border&quot;, &quot;3px dashed red&quot;)
  431. 431. .click(function() {
  432. 432. $(this).hide(&quot;slow&quot;);
  433. 433. }); </li></ul>
  434. 434. <ul><li>jQuery Methods - Traversing </li></ul><ul><li>Easy filtering the matched elements: </li><ul><li>first(), last(), each(), is(), has()
  435. 435. children(), parent(), closest(), siblings()
  436. 436. filter(), find() </li></ul></ul><ul><li>// change the text of the divs
  437. 437. $(&quot;div&quot;).addClass(&quot;yellowBox&quot;)
  438. 438. .each(function(idx) {
  439. 439. $(this).text(&quot;I'm div #&quot; + (idx + 1));
  440. 440. }); </li></ul>
  441. 441. <ul><li>jQuery Methods - Traversing </li></ul><ul><li>Easy filtering the matched elements: </li><ul><li>first(), last(), each(), is(), has()
  442. 442. children(), parent(), closest(), siblings()
  443. 443. filter(), find() </li></ul></ul><ul><li>// change the text of the divs
  444. 444. $(&quot;div&quot;).addClass(&quot;yellowBox&quot;)
  445. 445. .each(function(idx) {
  446. 446. $(this).text(&quot;I'm div #&quot; + (idx + 1));
  447. 447. }); </li></ul>
  448. 448. <ul><li>jQuery Animation </li></ul><ul><li>Perform animation by changing CSS attributes </li><ul><li>Only numeric attributes
  449. 449. Colors -> jqueryui.com </li></ul></ul><ul><li>$(&quot;div&quot;).hover(function() {
  450. 450. $(this).animate({ fontSize: &quot;+=100%&quot;,
  451. 451. marginLeft: 40,
  452. 452. marginRight: 0 } );
  453. 453. }, function(){
  454. 454. $(this).animate({ fontSize: &quot;-=100%&quot;,
  455. 455. marginLeft: 20,
  456. 456. marginRight: 20 });
  457. 457. }) </li></ul>
  458. 458. <ul><li>AJAX Definition </li></ul><ul><li>Stands for Asynchronous JavaScript and XML
  459. 459. Technique for partial page updates
  460. 460. Benefits </li><ul><li>Transferring less data between server and browser
  461. 461. Achieves “near desktop application” user experience
  462. 462. Web application seems to be more responsive </li></ul></ul>
  463. 463. <ul><li>AJAX Transport </li></ul><ul><li>Performs HTTP requests using: </li><ul><li>hidden iframe
  464. 464. XMLHttpRequest </li></ul><li>HTTP response is: </li><ul><li>HTML
  465. 465. XML
  466. 466. JSON (JavaScript Object Notation) </li></ul></ul><ul><li>var json = { “name” : “Svilen Ivanov”,
  467. 467. “ age” : 30,
  468. 468. “ favouriteColors” : [ “black”, “white”, “red” ] };
  469. 469. alert(json.favouriteColors[0]); // “black” </li></ul>
  470. 470. <ul><li>AJAX with jQuery </li></ul><ul><li>Convenient method: $.post </li></ul><ul><li><label for=&quot;name&quot;>Say Hello to:</label>
  471. 471. <input type=&quot;text&quot; id=&quot;name&quot;>
  472. 472. <input type=&quot;button&quot; value=&quot;Go&quot; id=&quot;go&quot;>
  473. 473. <div id=&quot;result&quot; class=&quot;result&quot;></div>
  474. 474. ...
  475. 475. $(document).ready(function() {
  476. 476. $(&quot;#go&quot;).click(clickGo);
  477. 477. });
  478. 478. function clickGo() {
  479. 479. $.post('/ajax/SimpleAjax',
  480. 480. { name : $('#name').val() },
  481. 481. function(data) {
  482. 482. $('#result').show().html(data);
  483. 483. }
  484. 484. ); } </li></ul>
  485. 485. <ul><li>AJAX with jQuery </li></ul><ul><li>protected void doPost(
  486. 486. HttpServletRequest request,
  487. 487. HttpServletResponse response) throws ServletException, IOException {
  488. 488. String name = request.getParameter(&quot;name&quot;);
  489. 489. String result;
  490. 490. if (name.isEmpty()) {
  491. 491. result = &quot;Please enter name&quot;;
  492. 492. } else {
  493. 493. result = &quot;Hello, &quot; + name;
  494. 494. }
  495. 495. response.setContentType(&quot;text/html&quot;);
  496. 496. response.setCharacterEncoding(&quot;utf-8&quot;);
  497. 497. response.getOutputStream().write(
  498. 498. result.getBytes(&quot;utf8&quot;));
  499. 499. } </li></ul>
  500. 500. <ul><li>AJAX with jQuery and JSON </li></ul><ul><li>Convenient method: $.post </li></ul><ul><li>function clickGo() {
  501. 501. $.post('/ajax/SimpleJSON',
  502. 502. { name : $('#name').val() },
  503. 503. function(data) {
  504. 504. if (data.error) {
  505. 505. $('#result').css(
  506. 506. &quot;border-color&quot;, &quot;red&quot;);
  507. 507. } else {
  508. 508. $('#result').css(
  509. 509. &quot;border-color&quot;, &quot;black&quot;);
  510. 510. }
  511. 511. $('#result').show().html(data.text);
  512. 512. }, &quot;json&quot;
  513. 513. ); } </li></ul>
  514. 514. <ul><li>AJAX with jQuery and JSON </li></ul><ul><li>protected void doPost(
  515. 515. HttpServletRequest request,
  516. 516. HttpServletResponse response) throws ServletException, IOException {
  517. 517. ...
  518. 518. if (name.isEmpty()) {
  519. 519. result =
  520. 520. &quot;{ &quot;text&quot; : &quot;Please enter
  521. 521. name&quot;, &quot;error&quot; : true }&quot;;
  522. 522. } else {
  523. 523. result = &quot;{ &quot;text&quot; : &quot;Hello, &quot;
  524. 524. + name + &quot;&quot;, &quot;error&quot; : false }&quot;;
  525. 525. }
  526. 526. response.setContentType(&quot; text/javascript &quot;);
  527. 527. ...
  528. 528. } </li></ul>
  529. 529. <ul>Questions? </ul>
  530. 530. <ul><li>Exercises </li></ul><ul><li>Create an HTML page that has two text fields (first name and last name) and a button. When the user clicks the button, a message should show the text in the text fields followed by the current time.
  531. 531. Create a Web page that asks the user about his name and says goodbye to him when leaving the page.
  532. 532. Modify the previous HTML page to have a text field for email address and on clicking the button check if the email is valid (it should follow the format <something>@<host>.<domain>).
  533. 533. Create a Web page that shows 20 <div> elements with random location, size and color. </li></ul>
  534. 534. <ul><li>Exercises (2) </li></ul><ul><li>Create a drop-down menu </li><ul><li>Use table for the main menu blocks
  535. 535. Use hidden <DIV> elements (display: none; position:absolute; top:30px)
  536. 536. Use JavaScript and onmouseover and onmouseout event to change display: none/block </li></ul></ul>
  537. 537. <ul><li>Exercises (3) </li></ul><ul><li>Create a DTHML page that has <div> containing a text that scrolls from right to left automatically </li><ul><li>Use setInterval() function to move the text at an interval of 500 ms
  538. 538. Use overflow:hidden for the <div>
  539. 539. Use scrollLeft and scrollWidth properties of the <div> element </li></ul></ul>

×