Advertisement
Guest User

Untitled

a guest
Nov 23rd, 2017
355
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 29.19 KB | None | 0 0
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <script src="jstut.js"></script>
  6.  
  7. <style type="text/css">
  8. body {font-size: 1.6em;}
  9. .hidden {display:none;}
  10. .show {display:inline !important;}
  11. button {
  12. border: 2px solid black; background: #E5E4E2;
  13. font-size: .5em; font-weight: bold; color: black;
  14. padding: .8em 2em;
  15. margin-top: .4em;
  16. }
  17. </style>
  18.  
  19. </head>
  20. <body>
  21. <p id="sayHello"></p>
  22. <script>
  23.  
  24. // You create variables that store values with var
  25. // Prompt opens a popup that requests info
  26. var yourName = prompt("What is your name?");
  27.  
  28. // If performs different actions depending on conditions
  29. if(yourName != null){
  30.  
  31. // Set text in an HTML element with the id sayHello
  32. // You concatenate (combine) strings with +
  33. document.getElementById("sayHello").innerHTML = "Hello " + yourName;
  34. } else {
  35.  
  36. // Alert opens a popup that contains a message
  37. alert("Please Enter Your Name Next Time");
  38. }
  39.  
  40. // ---------- VARIABLES ----------
  41. // variable names can't start with a number, contain spaces, but can
  42. // contain letters, numbers, underscores or $ (Are case sensitive)
  43. var myName = "Derek";
  44. var myAge = 40;
  45.  
  46. // Variables don't have a defined type, which can cause problems
  47. myName = 100;
  48.  
  49. // ---------- MATH ----------
  50. // document.write outputs data to the browser
  51. document.write("5 + 4 = ", 5 + 4, "<br/>");
  52.  
  53. // Using + instead of , will treat everything as a string unless you use ()
  54. document.write("5 + 4 = " + (5 + 4) + "<br/>");
  55.  
  56. document.write("5 - 4 = ", 5 - 4, "<br/>");
  57. document.write("5 * 4 = ", 5 * 4, "<br/>");
  58. document.write("5 / 4 = ", 5 / 4, "<br/>");
  59.  
  60. // Modulus remainder of a division
  61. document.write("5 % 4 = ", 5 % 4, "<br/>");
  62.  
  63. var maxNum = Number.MAX_VALUE;
  64.  
  65. document.write("Max Num = ", maxNum, "<br/>");
  66. document.write("Min Num = ", Number.MIN_VALUE, "<br/>");
  67.  
  68. // Numbers have 16 digits of precision
  69. precisionTest = 0.1000000000000001;
  70. document.write(precisionTest + 0.1000000000000001, "<br/>");
  71.  
  72. // Round number to 2 decimal places
  73. var balance = 1563.87;
  74. document.write("Monthly payment : ", (balance / 12).toFixed(2), "<br />");
  75.  
  76. var randNum = 5;
  77.  
  78. // Shortcut for adding 1
  79. document.write("randNum++ = ", randNum++, "<br/>");
  80. document.write("++randNum = ", ++randNum, "<br/>");
  81.  
  82. // The same exists for -
  83. document.write("randNum-- = ", randNum--, "<br/>");
  84. document.write("--randNum = ", --randNum, "<br/>");
  85.  
  86. // Perform a calculation on a value and assign the result
  87. document.write("randNum += 5 = ", randNum += 5, "<br/>");
  88. document.write("randNum -= 5 = ", randNum -= 5, "<br/>");
  89. document.write("randNum *= 5 = ", randNum *= 5, "<br/>");
  90. document.write("randNum /= 5 = ", randNum /= 5, "<br/>");
  91.  
  92. // Order of operations
  93. document.write("3 + 2 * 5 = ", 3 + 2 * 5, "<br/>");
  94. document.write("(3 + 2) * 5 = ", (3 + 2) * 5, "<br/>");
  95.  
  96. // Math properties and methods
  97. document.write("Math.E = ", Math.E, "<br/>");
  98. document.write("Math.PI = ", Math.PI, "<br/>");
  99.  
  100. document.write("Math.abs(-8) = ", Math.abs(-8), "<br/>");
  101. document.write("Math.cbrt(1000) = ", Math.cbrt(1000), "<br/>");
  102. document.write("Math.ceil(6.45) = ", Math.ceil(6.45), "<br/>");
  103. document.write("Math.floor(6.45) = ", Math.floor(6.45), "<br/>");
  104. document.write("Math.round(6.45) = ", Math.round(6.45), "<br/>");
  105. document.write("Math.log(10) = ", Math.log(10), "<br/>"); // Natural log
  106. document.write("Math.log10(10) = ", Math.log10(10), "<br/>"); // Base 10 log
  107. document.write("Math.max(10,5) = ", Math.max(10,5), "<br/>");
  108. document.write("Math.min(10,5) = ", Math.min(10,5), "<br/>");
  109. document.write("Math.pow(4,2) = ", Math.pow(4,2), "<br/>");
  110. document.write("Math.sqrt(1000) = ", Math.sqrt(1000), "<br/>");
  111.  
  112. document.write("Random # (1-10) = ", Math.floor((Math.random() * 10) + 1), "<br/>");
  113.  
  114. // Convert strings to numbers
  115. document.write("Converted String : ", Number("3.14"), "<br />");
  116.  
  117. document.write("Converted Int : ", parseInt("5"), "<br />");
  118. document.write("Converted Float : ", parseFloat("5.555"), "<br />");
  119.  
  120. // ---------- STRINGS ----------
  121. var randStr = "A long " + "string that " + "goes on and on";
  122.  
  123. // String length
  124. document.write("String Length : ", randStr.length + "<br/>");
  125.  
  126. document.write("Index for \"goes\" : ", randStr.indexOf("goes"), "<br/>");
  127.  
  128. // Return the value using a start and end index
  129. document.write(randStr.slice(19, 23) + "<br/>");
  130.  
  131. // Return everything after the start index
  132. document.write(randStr.slice(19) + "<br/>");
  133.  
  134. // Return the value using the start index and length
  135. document.write(randStr.substr(19, 4) + "<br/>");
  136.  
  137. // Replace a string
  138. document.write(randStr.replace("and on", "forever") + "<br/>");
  139.  
  140. // Get character at an index
  141. document.write("At Index 2 : ", randStr.charAt(2) + "<br/>");
  142.  
  143. // Split a string into an array
  144. var randStrArray = randStr.split(" ");
  145.  
  146. // Trim white space
  147. randStr = randStr.trim();
  148.  
  149. // Convert to uppercase
  150. document.write(randStr.toUpperCase() + "<br/>");
  151.  
  152. // Convert to lowercase
  153. document.write(randStr.toLowerCase() + "<br/>");
  154.  
  155. // Styling with JS
  156. var strToStyle = "Random String";
  157.  
  158. document.write("Big : ", strToStyle.big(), "<br />");
  159. document.write("Bold : ", strToStyle.bold(), "<br />");
  160. document.write("Font Color : ", strToStyle.fontcolor("blue"), "<br />");
  161. document.write("Font Size : ", strToStyle.fontsize("8em"), "<br />");
  162. document.write("Italics : ", strToStyle.italics(), "<br />");
  163. document.write("Google : ", strToStyle.link("http://google.com"), "<br />");
  164. document.write("Small : ", strToStyle.small(), "<br />");
  165. document.write("Strike : ", strToStyle.strike(), "<br />");
  166. document.write("Sub : ", strToStyle.sub(), "<br />");
  167. document.write("Sup : ", strToStyle.sup(), "<br />");
  168.  
  169.  
  170. // ---------- CONDITIONALS ----------
  171. // Relational Operators : == != > < >= <=
  172. // === : Equal value and type
  173. // Logical Operators : && \\ !
  174.  
  175. var age = 8;
  176.  
  177. if ((age >= 5) && (age <= 6)){
  178. document.write("Go to Kindergarten<br />");
  179. } else if (age > 18) {
  180. document.write("Go to College<br />");
  181. } else {
  182. document.write("Go to Grade ", age - 5, "<br />");
  183. }
  184.  
  185. document.write("true || false = ", true || false, "<br />");
  186.  
  187. document.write("!true = ", ! true, "<br />");
  188.  
  189. document.write("\"5\" == 5 = ", ("5" == 5), "<br />");
  190.  
  191. document.write("\"5\" === 5 = ", ("5" === 5), "<br />");
  192.  
  193. // Switch is used to match a limited number of options
  194. switch(age) {
  195. case 5 :
  196. case 6 :
  197. document.write("Go to Kindergarten<br />");
  198. break;
  199.  
  200. case 7 :
  201. document.write("Go to 1st Grade<br />");
  202. break;
  203.  
  204. default :
  205. document.write("Subtract 5 from your age<br />");
  206. }
  207.  
  208. // Ternary Operator assigns a value based on a condition
  209. // (condition) ? iftrue : ifFalse
  210. var canIVote = (age >= 18) ? true : false;
  211.  
  212. document.write("Can I Vote : ", canIVote, "<br />");
  213.  
  214. // ---------- LOOPING ----------
  215.  
  216. // while loops as long as a condition is true
  217. var i = 1;
  218. while (i <= 10){
  219. document.write(i, ", ");
  220. i++;
  221. }
  222. document.write("<br />");
  223.  
  224. // do while is used when you must go through the loop at least once
  225. do{
  226. var guess = prompt("Guess a number between 1 and 20");
  227. }while(guess != 15)
  228.  
  229. alert("You guessed it! 15 was the number");
  230.  
  231. // for is a self contained looping structure
  232. for(j = 0; j <= 20; j++){
  233.  
  234. // If j is divisible by 2 then skip back to the top of the loop
  235. if((j % 2) == 0){
  236. continue;
  237. }
  238.  
  239. // If j is equal to 15 break completely out of the loop
  240. if(j == 15){
  241. break;
  242. }
  243. document.write(j, ", ");
  244. }
  245. document.write("<br />");
  246.  
  247. var customer = {name : "Bob Thomas", address : "123 Main", balance : 50.50};
  248.  
  249. // for in cycles through an enumerable properties of an object
  250. for(k in customer){
  251. document.write(customer[k], "<br />");
  252. }
  253.  
  254. // ---------- ARRAYS ----------
  255. // Arrays have variable sizes and can contain multiple types in JS
  256. var tomSmith = ["Tom Smith", "123 Main", 120.50];
  257.  
  258. // Access first array item
  259. document.write("1st State : ", tomSmith[0], "<br />");
  260.  
  261. // Add an item
  262. tomSmith[3] = "tsmith@aol.com";
  263.  
  264. // Overwrite index 2 and fit everything else after index 2 without
  265. // overwriting (Put 0 for second parameter to not overwrite)
  266. tomSmith.splice(2, 1, "Pittsburgh", "PA");
  267.  
  268. // Delete the 4th index item
  269. tomSmith.splice(4,1);
  270.  
  271. // Convert an array into a string (Also use toString())
  272. document.write("Array : ", tomSmith.valueOf(), "<br />");
  273.  
  274. // Convert an array into a string with separator
  275. document.write("Array : ", tomSmith.join(", "), "<br />");
  276.  
  277. // Delete an index
  278. delete tomSmith[3];
  279.  
  280. // Sort an array (reverse() for reverse sort)
  281. // Works for sorting strings
  282. tomSmith.sort();
  283.  
  284. // Sort numbers
  285. var numbers = [4,3,9,1,20,43];
  286.  
  287. // Descending sort return y - x
  288. numbers.sort(function(x,y){ return x - y });
  289. document.write("Num Array : ", numbers.toString(), "<br />");
  290.  
  291. // Combine arrays
  292. var combinedArray = numbers.concat(tomSmith);
  293.  
  294. // Remove the last item
  295. tomSmith.pop();
  296.  
  297. // Add items to the end
  298. tomSmith.push("555-1212", "US");
  299.  
  300. // Deletes the first item
  301. tomSmith.shift();
  302.  
  303. // Adds item to the first index
  304. tomSmith.unshift("Tom Smith");
  305.  
  306. for (var i = 0; i < tomSmith.length; i++) {
  307. document.write(tomSmith[i], "<br />");
  308. }
  309.  
  310. // ---------- FUNCTIONS ----------
  311. // Functions provide code reuse and eliminate repetitive code
  312.  
  313. // Define a function that checks if a value is in an array
  314. function inArray(arrayToCheck, value){
  315. for(i = 0; i < arrayToCheck.length; i++){
  316. if(arrayToCheck[i] === value){
  317. return true;
  318. }
  319. }
  320. return false;
  321. }
  322.  
  323. var randArray = [1,2,3,4,5];
  324.  
  325. document.write("In Array : ", inArray(randArray, 4), "<br />");
  326.  
  327. // Local variables defined in functions can't be accessed outside of
  328. // the function
  329.  
  330. function times2(num){
  331. var var2 = 2;
  332. return num * var2;
  333. }
  334.  
  335. // Causes Error : document.write("Val of var2 : ", var2, "<br />");
  336.  
  337. // Pass a function as a parameter
  338. function times3(num){
  339. return num * 3;
  340. }
  341.  
  342. function multiply(func, num){
  343. return func(num);
  344. }
  345.  
  346. document.write("3 * 15 = ", multiply(times3, 15), "<br />");
  347.  
  348. // Define a function expression
  349. // We can assign functions to variables, store them in arrays,
  350. // pass them into other functions and return them from functions
  351. var triple = function(num){
  352. return num * 3;
  353. };
  354.  
  355. document.write("3 * 45 = ", multiply(triple, 45), "<br />");
  356.  
  357. // Receive variable number of arguments
  358. function getSum(){
  359. var sum = 0;
  360. for(i = 0; i < arguments.length; i++){
  361. sum += arguments[i];
  362. }
  363. return sum;
  364. }
  365.  
  366. document.write("Sum : ", getSum(1,2,3,4,5), "<br />");
  367.  
  368. // Return a variable number of values
  369. function times2(theArray){
  370.  
  371. var newArray = [];
  372. for(i = 0; i < theArray.length; i++){
  373. newArray.push(theArray[i] * 2);
  374. }
  375. return newArray;
  376. }
  377.  
  378. document.write("Array Doubled : ", times2([1,2,3,4,5]).toString(), "<br />");
  379.  
  380. // Recursive Function
  381. function factorial(num){
  382. if(num <= 1){
  383. return 1;
  384. } else {
  385. return num * factorial(num - 1);
  386. }
  387. }
  388.  
  389. document.write("Factorial of 4 : ", factorial(4), "<br />");
  390.  
  391. // 1st: num = 4 * factorial(3) = 4 * 6 = 24
  392. // 2nd: num = 3 * factorial(2) = 3 * 2 = 6
  393. // 3rd: num = 2 * factorial(1) = 2 * 1 = 2
  394.  
  395.  
  396. // ---------- EVENT HANDLING ----------
  397. function openAlert(mess){
  398. alert(mess);
  399. }
  400.  
  401.  
  402. // ---------- DATE ----------
  403. // Get a Date object
  404. var curDate = new Date();
  405.  
  406. document.write("Date : ", curDate.getDate(), "<br />");
  407. document.write("Month : ", curDate.getMonth(), "<br />");
  408. document.write("Day : ", curDate.getDay(), "<br />");
  409. document.write("Year : ", curDate.getFullYear(), "<br />");
  410. document.write("Time : ", curDate.getHours(), ":", curDate.getMinutes(),
  411. ":", curDate.getSeconds(), ":", curDate.getMilliseconds(), "<br />");
  412.  
  413. // Create a Date object for my birthday
  414. var myBD = new Date("December 21, 2015");
  415.  
  416. var msForBD = myBD.getTime();
  417. var timeNow = curDate.getTime();
  418. var tilMyBD = msForBD - timeNow;
  419.  
  420. document.write("Days til Birthday : ", tilMyBD / (1000 * 60 * 60 * 24), "<br />");
  421.  
  422. </script>
  423.  
  424. <!-- ---------- CHANGING ELEMENTS & EVENT HANDLING ---------- -->
  425. <!-- All the events can be found here http://www.w3schools.com/jsref/dom_obj_event.asp -->
  426.  
  427. <!-- Open alert on click -->
  428. <a href="JavaScript:void(0)" onClick="alert('Hello');">Say Hello</a><br />
  429.  
  430. <!-- Call a function on click -->
  431. <a href="JavaScript:void(0)" onClick="openAlert('Hi how are you');">Say Something</a><br />
  432.  
  433. <!-- Change text color on mouse rollover and roll out-->
  434. <a href="JavaScript:void(0)" onmouseover="this.style.color='red';"
  435. onmouseout="this.style.color='blue';"
  436. ondblclick="this.text='You Double Clicked Me'"
  437. onmousedown="this.text='Don\'t Press So hard'"
  438. onmouseup="this.text='Thank You'">Make me Red</a><br />
  439.  
  440. <!-- Get value in an input element and open alert on change -->
  441. <input type="text" id="randInput"
  442. onChange="var dataEntered=document.getElementById('randInput').value; alert('User Typed ' + dataEntered);"><br /><br />
  443.  
  444. <!-- When a user clicks a key provide info on the key clicked -->
  445. <form action="#" id="sampForm">
  446. <input id='charInput' type="text">
  447. <p id="keyData">Key Data Here</p>
  448. <input type="submit" value="Submit">
  449. <input type="reset" value="Reset">
  450. </form><br /><br />
  451.  
  452. <img src="ntt-logo.png" id="logo">
  453. <button id="logoButton">Get Logo</button><br />
  454. <input id='mouseInput' type="text" size="30"><br />
  455.  
  456. Mouse X: <input type="text" id="mouseX"><br />
  457. Mouse Y: <input type="text" id="mouseY"><br />
  458.  
  459. <button id="clearInputs">Clear Inputs</button><br />
  460.  
  461. <script>
  462.  
  463. function getChar(event) {
  464.  
  465. // event.which returns the key or mouse button clicked
  466. if (event.which == null) {
  467.  
  468. // Return the char if not a special character
  469. return String.fromCharCode(event.keyCode); // IE
  470. } else if (event.which!=0 && event.charCode!=0) {
  471. return String.fromCharCode(event.which); // Other Browsers
  472. } else {
  473. return null; // Special Key Clicked
  474. }
  475. }
  476.  
  477. document.getElementById('charInput').onkeypress = function(event) {
  478. var char = getChar(event || window.event)
  479. if (!char) return false; // Special Key Clicked
  480.  
  481. document.getElementById('keyData').innerHTML = char + " was clicked";
  482. return true;
  483. }
  484.  
  485. // Change text when the input gains focus
  486. document.getElementById('charInput').onfocus = function(event) {
  487. document.getElementById('keyData').innerHTML = "Input Gained Focus";
  488. }
  489.  
  490. // Change text when the input loses focus
  491. document.getElementById('charInput').onblur = function(event) {
  492. document.getElementById('keyData').innerHTML = "Input Lost Focus";
  493. }
  494.  
  495. // Change text when text is selected
  496. document.getElementById('charInput').onselect = function(event) {
  497. document.getElementById('keyData').innerHTML = "Text Selected";
  498. }
  499.  
  500. // Add a listener that triggers a function on browser resize
  501. window.addEventListener("resize", browserResized);
  502.  
  503. function browserResized() {
  504. document.getElementById('keyData').innerHTML = "I've been resized";
  505. }
  506.  
  507. // Make image invisible on click
  508. document.getElementById('logo').onclick = function(event) {
  509.  
  510. // Change the class for the image
  511. document.getElementById('logo').className = "hidden";
  512.  
  513. // Change the input element value
  514. document.getElementById('mouseInput').value = "Clicked on image with button " + event.button;
  515. }
  516.  
  517. // Make image visible on click
  518. document.getElementById('logoButton').onclick = function(event) {
  519. document.getElementById('logo').className = "show";
  520. }
  521.  
  522. // Change image src on mouseover
  523. document.getElementById('logo').onmouseover = function(event) {
  524. document.getElementById('logo').src = "ntt-logo-horz.png";
  525. document.getElementById('mouseInput').value = "Mouse Over image";
  526. }
  527.  
  528. // Change image src back on mouseout
  529. document.getElementById('logo').onmouseout = function(event) {
  530. document.getElementById('logo').src = "ntt-logo.png";
  531. document.getElementById('mouseInput').value = "Mouse Left image";
  532. }
  533.  
  534. // Get mouse x y coordinates
  535. document.body.onmousemove = function(e) {
  536. e = e || window.event;
  537.  
  538. // Get pageX, pageY : Mouse position relative to the html doc
  539. var pageX = e.pageX;
  540. var pageY = e.pageY;
  541. if (pageX === undefined) {
  542.  
  543. // clientX, clientY : Mouse position relative to the browsers viewport
  544. // scrollLeft, scrollTop : Pixels an element is scrolled left or
  545. // from the top
  546. pageX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
  547. pageY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
  548. }
  549.  
  550. document.getElementById('mouseX').value = pageX;
  551. document.getElementById('mouseY').value = pageY;
  552. };
  553.  
  554. // Clear all input elements
  555. document.getElementById('clearInputs').onclick = function(event) {
  556. var inputElements = document.getElementsByTagName('input');
  557.  
  558. for (var i = 0; i < inputElements.length; i++) {
  559. if (inputElements[i].type == "text") {
  560. inputElements[i].value = "";
  561. }
  562. }
  563. }
  564.  
  565. </script>
  566.  
  567. <!-- ---------- ELEMENT STYLING ---------- -->
  568. <!-- See all of them here http://www.w3schools.com/jsref/dom_obj_style.asp -->
  569.  
  570. <div id="sampDiv">
  571. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget turpis eget quam luctus malesuada ut ac nulla. Suspendisse fermentum magna neque, a auctor felis pretium eget. Fusce ornare feugiat magna, ut faucibus sapien congue ut. Nunc nec fringilla ex, nec varius nisl. Ut eget laoreet nisi. Aenean quis venenatis mauris, at volutpat ante. Donec sollicitudin lacinia ornare. In quis accumsan ligula, id egestas enim.
  572. </div>
  573.  
  574. <button id="chgBkColor">Background Color</button>
  575. <button id="chgBkImg">Background Image</button>
  576. <button id="chgBorderStyle">Border Style</button>
  577. <button id="chgBorderWidth">Border Width</button>
  578. <button id="chgBorderColor">Border Color</button>
  579.  
  580. <script type="text/javascript">
  581.  
  582. // Change background color
  583. document.getElementById('chgBkColor').onclick = function(event) {
  584. document.getElementById('sampDiv').style.backgroundColor = "#EFDECD";
  585. }
  586.  
  587. // Change background image
  588. document.getElementById('chgBkImg').onclick = function(event) {
  589. document.getElementById('sampDiv').style.backgroundImage = "url('repeatBkgrnd.png')";
  590. }
  591.  
  592. // Change border style
  593. document.getElementById('chgBorderStyle').onclick = function(event) {
  594. document.getElementById('sampDiv').style.borderStyle = "solid";
  595. }
  596.  
  597. // Change border width
  598. document.getElementById('chgBorderWidth').onclick = function(event) {
  599. document.getElementById('sampDiv').style.borderWidth = "thick";
  600. }
  601.  
  602. // Change border color
  603. document.getElementById('chgBorderColor').onclick = function(event) {
  604. document.getElementById('sampDiv').style.borderColor = "blue";
  605. }
  606. </script>
  607.  
  608. <!-- ---------- MANIPULATING THE DOM ---------- -->
  609.  
  610. <div id="sampDiv2"><p>Lorem ipsum dolor sit amet, <em>consectetur adipiscing</em> elit. Proin eget turpis eget quam luctus malesuada ut ac nulla. Suspendisse fermentum magna neque, a auctor felis pretium eget. Fusce ornare feugiat magna, ut faucibus sapien congue ut. Nunc nec fringilla ex, nec varius nisl. Ut eget laoreet nisi. Aenean quis venenatis mauris, at volutpat ante. Donec sollicitudin lacinia ornare. In quis accumsan ligula, id egestas enim.</p><p>Lorem ipsum dolor sit amet, <b>consectetur adipiscing</b> elit. Proin eget turpis eget quam luctus malesuada ut ac nulla. Suspendisse fermentum magna neque, a auctor felis pretium eget. <em>Fusce ornare</em> feugiat magna, ut faucibus sapien congue ut. <b>Nunc nec fringilla</b> ex, nec varius nisl.</p></div>
  611.  
  612. <img src="ntt-logo.png" id="logo2" alt="NTT Logo" height="180" width="180"><br />
  613.  
  614. <button id="goToGoogle">Go to Google</button><br />
  615.  
  616. <button id="forwardPage">Forward Page</button><br />
  617.  
  618. <button id="backPage">Back Page</button><br />
  619.  
  620. <button id="reload">Reload Page</button><br />
  621.  
  622. <script type="text/javascript">
  623.  
  624. // Get current web page info
  625. document.write("Current URL : ", window.location.href, "<br />");
  626. document.write("Current Host : ", window.location.hostname, "<br />");
  627. document.write("Current Path : ", window.location.pathname, "<br />");
  628.  
  629. // Change site on button click
  630. document.getElementById('goToGoogle').onclick = function(event) {
  631. window.location.href = "http://google.com";
  632. // OR
  633. // window.location.assign("http://google.com");
  634. }
  635.  
  636. // Go forward a page on click
  637. document.getElementById('forwardPage').onclick = function(event) {
  638. history.forward();
  639. }
  640.  
  641. // Go back a page on click
  642. document.getElementById('forwardPage').onclick = function(event) {
  643. history.back();
  644. }
  645.  
  646. // Use history.go(-2) or history.go(2) to jump multiple pages
  647.  
  648. // Reload page on button click
  649. document.getElementById('reload').onclick = function(event) {
  650. window.location.reload(true);
  651. }
  652.  
  653. // You can get all ps and then target them like an array
  654. var pElements = document.getElementsByTagName('p');
  655. pElements[3].style.backgroundColor = "#EFDECD";
  656.  
  657. // Target the html
  658. document.childNodes[1].style.backgroundColor = "#FAEBD7";
  659.  
  660. // Change the color of the 1st child in sampDiv2
  661. var sampDiv2 = document.getElementById('sampDiv2');
  662. sampDiv2.childNodes[0].style.backgroundColor = "#F0FFFF";
  663.  
  664. // Style the 1st child of sampDivs 1st child
  665. sampDiv2.childNodes[0].childNodes[1].style.backgroundColor = "#BFAFB2";
  666.  
  667. // JavaScript can get confused by text nodes when targeting elements
  668. // Text nodes are whitespace, which nodeType will identify with a 3
  669. // while elements as a 1
  670. // You can eliminate text nodes by deleting whitespace or by using a
  671. // minimizer (lastChild and firstChild may not work)
  672. document.write("Node Type : ", sampDiv2.childNodes[0].childNodes[0].nodeType, "<br />");
  673.  
  674. document.write("Node Name : ", sampDiv2.childNodes[0].childNodes[0].nodeName, "<br />");
  675.  
  676. sampDiv2.childNodes[1].childNodes[3].style.backgroundColor = "#BFAFB2";
  677.  
  678. // Changing element attributes
  679. var nttLogo2 = document.getElementById('logo2');
  680.  
  681. // Check for attributes
  682. document.write("Logo has alt : ", nttLogo2.hasAttribute("alt"), "<br />");
  683.  
  684. // Change attribute
  685. nttLogo2.setAttribute("alt", "NTT Logo 2");
  686.  
  687. // Get attribute
  688. document.write("Logo alt Value : ", nttLogo2.getAttribute("alt"), "<br />");
  689.  
  690. // Get all attributes and print them
  691. var attribList = document.getElementById('logo2').attributes;
  692.  
  693. for(i = 0; i < attribList.length; i++){
  694. document.write("Attribute ", i, " : ", attribList[i].nodeName, " : ", attribList[i].nodeValue, "<br />");
  695. }
  696.  
  697. // Add a p element after setting an attribute and text
  698. var paragraph3 = document.createElement("p");
  699.  
  700. paragraph3.setAttribute("id", "paragraph3");
  701.  
  702. paragraph3.innerHTML = "Proin eget turpis eget quam luctus malesuada ut ac nulla.";
  703.  
  704. sampDiv2.appendChild(paragraph3);
  705.  
  706. // Insert the element before the 1st child
  707. sampDiv2.insertBefore(paragraph3, sampDiv2.childNodes[0]);
  708.  
  709. </script>
  710.  
  711. <!-- ---------- OO JAVASCRIPT ---------- -->
  712.  
  713. <script type="text/javascript">
  714.  
  715. // Create a customer object by defining the attributes of John Smith
  716. // The variable is a reference to the object in memory
  717. var cust1 = {
  718. name: "John Smith",
  719. street: "123 Main",
  720. city: "Pittsburgh",
  721. state: "PA",
  722. email: "jsmith@aol.com",
  723. balance: 120.50,
  724. payDownBal: function(amtPaid){
  725. this.balance -= amtPaid;
  726. },
  727. addToBal: function(amtCharged){
  728. this.balance += amtCharged;
  729. }
  730. };
  731.  
  732. // Retrieve the value for the object
  733. document.write("Customer Name : ", cust1.name, "<br />");
  734.  
  735. // Change the value for the object
  736. cust1.street = "215 Main St";
  737. document.write("Customer Address : ", cust1.street, "<br />");
  738.  
  739. // Add a property to cust1
  740. cust1.country = "US";
  741. document.write("Customer Country : ", cust1.country, "<br />");
  742.  
  743. // Delete a property
  744. delete cust1.country;
  745.  
  746. // Cycle through all the properties for the object
  747. for (var prop in cust1) {
  748. if (cust1.hasOwnProperty(prop)) {
  749. document.write(prop, "<br />");
  750. }
  751. }
  752.  
  753. // Check if a property is in an object
  754. document.write("name in cust1 : ", "name" in cust1, "<br />");
  755.  
  756. // Interact with an object using a function
  757. function getInfo(cust){
  758. return cust1.name + " lives at " + cust1.street + " in " + cust1.city + " " + cust1.state + " email : " + cust1.email + " and has a balance of $" + cust1.balance;
  759. }
  760.  
  761. document.write(getInfo(cust1), "<br />");
  762.  
  763. // Call object methods
  764. cust1.payDownBal(20.50);
  765. cust1.addToBal(10.00);
  766.  
  767. document.write(getInfo(cust1), "<br />");
  768.  
  769. // Create an object constructor
  770. function Customer(name, street, city, state, email, balance){
  771. this.name = name;
  772. this.street = street;
  773. this.city = city;
  774. this.state = state;
  775. this.email = email;
  776. this.balance = balance;
  777.  
  778. this.payDownBal = function(amtPaid){
  779. this.balance -= amtPaid;
  780. };
  781. this.addToBal = function(amtCharged){
  782. this.balance += amtCharged;
  783. };
  784. }
  785.  
  786. var cust2 = new Customer("Sally Smith", "234 Main", "Pittsburgh", "PA", "ssmith@aol.com", 0.00);
  787.  
  788. cust2.addToBal(15.50);
  789.  
  790. // Define a shared prototype property for all objects
  791. Customer.prototype.isCreditAvail = true;
  792.  
  793. // We define prototype methods that are shared by every object created
  794. Customer.prototype.toString = function(){
  795. return this.name + " lives at " + this.street + " in " + this.city + " " + this.state + " email : " + this.email + " and has a balance of $" + this.balance.toFixed(2) + " Creditworthy : " + this.isCreditAvail;
  796. };
  797.  
  798. document.write(cust2.toString());
  799.  
  800. </script>
  801.  
  802. <!-- ---------- FORM VALIDATION ---------- -->
  803.  
  804. <div>
  805. Enter your name:
  806.  
  807. <!-- When they leave the input send a reference to the input element, and a reference to the hel error span -->
  808. <input id="name" name="name" type="text" size="30" onblur="isTheFieldEmpty(this, document.getElementById('name_help'))" />
  809. <span id="name_help"></span>
  810. <!-- this is the id number for the text box -->
  811. </div>
  812.  
  813. <div>
  814. Enter your street address:
  815. <input id="street" name="street" type="text" size="30" onblur="isAddressOk(this, document.getElementById('street_help'))" />
  816. <span id="street_help"></span>
  817. </div>
  818.  
  819. <div>
  820. Enter your city:
  821. <input id="city" name="city" type="text" size="30" onblur="isTheFieldEmpty(this, document.getElementById('city_help'))" />
  822. <span id="city_help"></span>
  823. </div>
  824.  
  825. <div>
  826. Enter your state code:
  827. <input id="state" name="state" type="text" size="2" onblur="isStateOk(this, document.getElementById('state_help'))" />
  828. <span id="state_help"></span>
  829. </div>
  830.  
  831. <div>
  832. Enter your phone number:
  833. <input id="phone" name="phone" type="text" size="15"
  834. onblur="isPhoneOk(this, document.getElementById('phone_help'))" />
  835. <span id="phone_help"></span>
  836. </div>
  837.  
  838. <div>
  839. Enter your email:
  840. <input id="email" name="email" type="text" size="30" onblur="isEmailOk(this, document.getElementById('email_help'))" />
  841. <span id="email_help"></span>
  842. </div>
  843.  
  844. <script type="text/javascript">
  845.  
  846. function editNodeText(regex, input, helpId, helpMessage)
  847.  
  848. {
  849. // See if the info matches the regex that was defined
  850. // If the wrong information was entered, warn them
  851. if (!regex.test(input)) {
  852.  
  853. if (helpId != null)
  854. // We need to show a warning
  855. // Remove any warnings that may exist
  856. while (helpId.childNodes[0]){
  857. helpId.removeChild(helpId.childNodes[0]);
  858. }
  859.  
  860. // Add new warning
  861. helpId.appendChild(document.createTextNode(helpMessage));
  862.  
  863. } else {
  864.  
  865. // If the right information was entered, clear the help message
  866. if (helpId != null){
  867.  
  868. // Remove any warnings that may exist
  869. while (helpId.childNodes[0]){
  870. helpId.removeChild(helpId.childNodes[0]);
  871. }
  872.  
  873. }
  874.  
  875. }
  876. }
  877.  
  878. // inputField – ID Number for the html text box
  879. // helpId – ID Number for the child node I want to print a warning in
  880. function isTheFieldEmpty(inputField, helpId) {
  881.  
  882. // See if the input value contains any text
  883. return editNodeText(/^[A-Za-z\.\' \-]{1,15}\s?[A-Za-z\.\' \-]{1,15}\s?[A-Za-z\.\' \-]{1,15}/, inputField.value, helpId, "Please enter a valid name.");
  884. }
  885.  
  886. // inputField.value – Value typed in the html text box
  887. function isAddressOk(inputField, helpId) {
  888.  
  889. return editNodeText(/^[A-Za-z0-9\.\' \-]{5,30}$/, inputField.value, helpId, "Enter a Street (Ex.1234 Main St.)");
  890. }
  891.  
  892. function isStateOk(inputField, helpId) {
  893.  
  894. return editNodeText(/^A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY]$/, inputField.value, helpId, "Enter a State Code in Uppercase (Ex.NY, PA, CA)");
  895. }
  896.  
  897. function isPhoneOk(inputField, helpId) {
  898.  
  899. return editNodeText(/^([0-9]( |-)?)?(\(?[0-9]{3}\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4}|[a-zA-Z0-9]{7})$/, inputField.value, helpId, "Enter a Phone Number (Ex.412-828-3000)");
  900.  
  901. }
  902.  
  903. function isEmailOk(inputField, helpId) {
  904.  
  905. return editNodeText(/^[A-Za-z0-9._-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/, inputField.value, helpId, "Enter an Email (Ex. derekbanas@newthinktank.com)");
  906.  
  907. }
  908.  
  909. </script>
  910.  
  911. <!-- ---------- EXCEPTION HANDLING ---------- -->
  912.  
  913. <script type="text/javascript">
  914. // Through exception handling we can catch and manage errors rather then
  915. // crashing by surrounding problem code in a try block and handling it
  916. // in a catch block
  917.  
  918. var custArray = ["Tom", "Bob", "Sally", "Sue"];
  919.  
  920. var getCust = function(index){
  921. if(index > custArray.length){
  922. throw new RangeError("Index must be >= 0 and <= " + custArray.length );
  923. } else {
  924. return custArray[index];
  925. }
  926. }
  927.  
  928. try {
  929. document.write("Customer : ", getCust(5), "<br />");
  930. }
  931. catch(ex){
  932. if (ex instanceof RangeError){
  933. document.write(ex.message + "<br />");
  934. }
  935. }
  936.  
  937. </script>
  938.  
  939. </body>
  940. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement