lecture 7 basic javascript n.
Skip this Video
Loading SlideShow in 5 Seconds..
How to Create Your Own Website PowerPoint Presentation
Download Presentation
How to Create Your Own Website

How to Create Your Own Website

123 Vues Download Presentation
Télécharger la présentation

How to Create Your Own Website

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Lecture 7: Basic Javascript. How to Create Your Own Website

  2. Today’s Lecture: • Javascript programming: • Why is Javascript necessary? • Variables. • Reading and manipulating page values. • Getting element references. • Arithmetic. • Conditionals. • Loops.

  3. Why Use Javascript? • HTML determines the structure of the page: • Which elements appear on it. • How they are ordered. • How they interact with the page’s content. • The content (text, images) itself. • CSS determines the presentation of a page: • The font used to display text. • Foreground and background colors. • Borders, margins, and padding. • List styles. • Display type (block level, inline, …), floats, and positioning. • Both are fairly passive. • The only capacity for user interaction is built into the elements. • i.e. Links will navigate to new pages when clicked, submit buttons will submit their forms. Pretty much every form of interaction involves navigating to a new page. • :hover is the closest thing to an interactive CSS selector, but all this can do is change the presentation of an element when the mouse is over it. This is still limited. • Javascript allows for a far greater degree of interactivity. • You can alter the behavior of links or submit buttons, or subject them to additional checks before following them, or disable them entirely. • You can change parts of the page, based on variables that HTML has no conception of, such as the user’s local time of day. • You can create “cookies”, which store information on the user’s system, to record user preferences (for example, text entered into a particular form field), and you can do things with them later. • You can respond to pretty much anything the user does to your page in many ways that were not previously possible. • But with great power comes great responsibility. • You have the potential to create popup windows, trap users in infinite loops of message boxes, disable right clicks on your page, and prevent things from working as expected. • If you misuse these powers, you will very quickly lose all visitors to your site. • Your users can also manually shut Javascript off in their browsers. If you rely on it and it’s turned off, your site will break.

  4. What is Javascript? • It is a bone fide programming language. • It is dynamically typed, meaning that the language itself makes little distinction between text (“Strings”), numbers, or other types of data. • (Note that this can still affect a script’s behavior as it runs). • It runs within the browser, meaning that it usually exhibits fairly consistent behavior across operating systems. • Unfortunately, it can do different things in different browsers! • There is nothing on the web that doesn’t exhibit variance by browser. The parts of the language I’ll show you are fairly uniform, however. • Although implementing several programming language paradigms, Javascript is usually used as a procedural language. • That is, a language oriented around giving commands directly to the browser and checking to see how they change the browser’s state. • (Javascript also contains elements of the object oriented, functional,and prototype-based paradigms, which we won’t discuss in this course). • It is an interpreted language, meaning that the program code is read directly by the browser rather than being translated into machine code first. • Thus all off your scripts’ source code can be viewed by the user. • Desktop applications are compiled, meaning what you actually run is a machine code representation, not the original source code (it is thus more difficult to reverse engineer desktop programs than it is to reverse engineer scripts). • In other words, don’t expect to keep secrets about how your scripts work from your users (nor should you; the web’s openness is one of the keys to its success).

  5. Basic Building Blocks • Variables: • Like mathematical variables, these can represent any value they’re set to. • E.g. x = 4; y = x * 2; z = “Hello”; a = document.getElementById(“MyElem”); b = a; • Operators: • Comparisons between or modifications of values: operations such as +, -, *, /, <, >, and ==. • Yes, ==, not =, checks for equality. “=“ sets values. “==“ checks them. • Statements (Basic programming language keywords): • //Comments (for your own use; not interpreted by the language). • var a; //Creates a new variable called “a”. • if (a == b) { //do something if a and b have the same value } • while (c * 2 < 100) { //keep doing something until c*2 >= 100 } • Functions: • More complex operations that allow you to manipulate variables or map input data to output data: • E.g. varstr = “Test”; varstrupper = str.toUpperCase(); //strupper contains “TEST”. • function TwoNPlusOne(val) { return val * 2 + 1; } //maps any value to twice itself plus 1. • alert(TwoNPlusOne(4)); //Creates a messagebox with the text “9”. • Javascriptprograms are combinations of these building blocks. Each executable line of code ends in a semicolon (“;”). Ifs, whiles, and functions contain code inside, enclosed in {}s.

  6. Our First Function • Perhaps the most useful function for debugging Javascript programs: • alert() • This function pops up a message box displaying whatever value is passed to it: • e.g.: alert(5); will pop up a message box saying “5”. • alert(“Test”); will pop up a message box saying “Test”. • alert(document) will pop up a message box saying [Object: HTMLDocument] (or something similar which represents the “document” object at the root of the DOM tree). • You can use it anywhere in your javascript programs. • You can also use it to display popup messages to your users.

  7. Variables • Like in mathematics, symbols that can be assigned any value. • This can include numbers, strings, references to elements on the page, etc. • Created (or declared) using the keyword “var”. • E.g. var a; a = 5; var b = 10; • Variables have scope of the block in which they are declared. • E.g.:function f() {var x = 5; alert(x); //Ok. } function g() { alert(x); //Error: x only exists (is only “in scope”) inside of function f. } • Scope saves memory (the memory associated with x can be freed after f() exits instead of persisting for the whole program) and reduces program clutter. • Variables can be reassigned: var a = 5; a = 10; is valid and will result in “a” being 10. • Variables can be assigned to other variables; e.g. var a = b;

  8. Operators • Standard mathematical operators: • +, -, *, /, % (modulus; remainder). • e.g. 3 + 2 = 5, 3 - 2 = 1, 5 * 3 = 15, 12 / 4 = 3, 7 % 3 = 1. • Standard comparison operators: • Greater than (>), greater than or equal to (>=), less than (<), less than or equal to (<=), equal to (==), not equal to (!=). • e.g. 3 > 2, 3 >= 3, 2 < 3, 4 == 4, 2 != 4 • Arithmetic shorthand operations: • (These are common in most programming languages) • x++; //Increment x by 1; equivalent to x = x + 1. • x--; //Decrement x by 1; equivalent to x = x - 1. • x += 5; //x = x + 5 • x -= 3; //x = x - 3 • x *= 2; //x = x * 2 • x /= 4; //x = x / 4 • x %= 2; //x = x % 2 • Boolean operators: • These are used inside of conditionals (“if” statements). • They’re used to pair two or more conditions: • if (x == 4 && y == 5) //True if x is 4 AND y is 5. (both) • if (x == 4 || y == 5) //True if x is 4 OR y is 5. (either) • if (!x == 4) //True if x is NOT equal to 4 (in this case, we can use != instead, but not always). • De Morgan’s law: Negate two ANDed conditions p and q and they become an OR of !p and !q, and vice versa: • if (!(x == 4 && y == 5)) //True if either x is not 4 or y is not 5 (if ((!x == 4) || (!y == 5))) • Order of operations is important: as in math, parenthesis, (exponents), multiplication, division, addition, subtraction. • When in doubt, parenthesize to enforce the order you want.

  9. Truth Tables – Boolean Logic x == 4 && y == 5 x == 4 || y == 5

  10. Conditionals • These capture “if A, then do B” logic. • Conditional statements begin with “if”, which has the following syntax: • if (x > 5) { alert(“x is greater than 5!”); alert(“Congratulations!”); } else { alert(“x is not greater than 5.”); alert(“Sorry!”); } • There is also an “else” statement, which determines what code runs if the “if” above it is not satisfied. • Any code can go inside of the blocks, including other ifs: • if (x > 5) { var a = “x is greater than 5”; if (x > 10) { a = a + “ and greater than 10, too!”; } else { a = a + “ but not greater than 10…”; } alert(a); }

  11. Loops • Loops refer to blocks of code that may be executed more than once. • There are two types of loops: conditional loops and counting loops. • Conditional loops do something until certain conditions are satisfied. • Counting loops do something a fixed number of times. • Two loop statements in Javascript: while and for: • var x = 0; while (x < 5) { alert(x); //Will pop up “0”, “1”, “2”, “3”, “4”. x = x + 1; } • Equivalently, for loops declare variables, change them at each step, and compare them in a single statement:for (x = 0; x < 5; x = x + 1) { alert(x); }

  12. Functions • Like mathematical functions, they take input parameters and (optionally) return an output value. • Functions encapsulate the functionality of many lines of code, removing the need to copy & paste this code in many places. • Instead, the function can just be invoked in every place that its functionality is required. • Example: • function factorial(x) { • var res = 1; • for (i = 1; i <= x; i++) //”i++” is shorthand for “i = i+1”. • res = res * i; • return res; //Output value is 1*2*3*…*x = x! • } • Example calls: • alert(factorial(4)); //Prints “24”. • alert(factorial(5)); //Prints “120”. • alert(factorial(factorial(3)); //Prints “720” (factorial(3) = 6). • Instead of copying and pasting the loop each time, you can now just call factorial(x) whenever you need to compute a factorial. • Moreover, if you wish to change your code in the future, you only need to make the changes in one place and they will be reflected everywhere that the factorial function is used without further modification.

  13. This example is available at Basic Javascript Example

  14. Getting references to elements • Of course, we wish to manipulate elements on the current page. • To do this, we need some means of accessing the element. • The easiest way is to directly jump to the element by its ID. • (Another means is to traverse the DOM tree until it’s found, but that’s complex). • We do this using the “document.getElementById(ID)” function. It returns a reference to the element with the specified ID attribute. • If it isn’t found, it returns a special value in Javascript called “null”. • You can check for “null” in an “if” and handle this case appropriately. • if (a == null) { //do something } • What do we do with this reference? Store it in a variable, of course! • And then we can manipulate it as we please: • vartargelem = document.getElementById(“MyID”); • = ‘black’; //Plunge it into darkness.

  15. Manipulating the Page • Each element contains a “style” field, which allows you to modify that element’s CSS styles. • Usually the name of the style is the same as it is in CSS, without dashes and with each word after the first capitalized (e.g. background-color: becomes backgroundColor). • Most attributes can be directly modified. • E.g. The destination of a link can be changed by setting link.href = “newurl”. • Image sources can also be updated by changing src. • The existing values can be retrieved as well, without making modifications. These values can then be used in subsequent alterations. • varoldhref = link.href;

  16. Events • HTML elements have several events, which are Javascript functions triggered when certain things happen to the element. • For example, when a page finishes loading, the body “onload” event is triggered. • When an element (and not only a button, link, or other normally “clickable” element) is clicked, the “onclick” event fires. • “onmouseover” is triggered when the mouse hovers over an element, and “onmouseout” is triggered when it leaves that element. • These two are perfect for making advanced rollovers that :hover isn’t versatile enough to handle. • “onsubmit” is triggered on <form> tags when the form is submitted. • Each one of these attributes takes Javascript code as a value. • It’s best to just call a function located in your script from these. • Many of these functions can be interrupted by returning false within the function you called. • For example, if a link is clicked, the code in “onclick” will run, and if it returns false, the link will not be followed. • If a form’s “onsubmit” function returns false, the form won’t be submitted. • This is a way to prevent default actions from being taken if certain conditions aren’t met. • Some form validation works this way, for example, by preventing forms from being submitted if required fields are missing. • Don’t assume that this is secure, however. It happens in the user’s browser, and a malicious user will be able to easily circumvent it. Form fields should be re-validated in server side scripts. • Example: <form method=“post” action=“myform.cgi” onsubmit=“return checkForm()”> <!-- Note that we explicitly return the return value of the function in the event --> <input type=“text” name=“secret” id=“secret” /> </form> <script> function checkForm() { if (document.getElementById(“secret”).value != ‘secretvalue’) { alert(“To submit this form, the value of the textbox must be secretvalue”); return false; //Stops the form from being submitted. } else { return true; //Everything checks out; submit the form. } } </script>

  17. Building a Validated Form

  18. Next Time • More advanced Javascript, manipulating the DOM tree.

  19. A Nonprofit Organization of New Jersey, USA