1 / 74

BIT116: Scripting Lecture 04

BIT116: Scripting Lecture 04. Instructor: Craig Duckett cduckett@cascadia.edu. Wednesday, January 15 th , 2014. Basic JavaScript , Variables. Let's Begin With Some JavaScript Buzzwords. Objects JavaScript is an Object-Oriented Language

daryl
Download Presentation

BIT116: Scripting Lecture 04

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. BIT116: ScriptingLecture 04 Instructor: Craig Duckett cduckett@cascadia.edu Wednesday, January 15th, 2014 Basic JavaScript, Variables

  2. Let's Begin With Some JavaScript Buzzwords

  3. Objects JavaScript is an Object-Oriented Language An object is a kind of thing. A dog, a computer, and a bicycle are all objects in the physical world. To JavaScript, there are objects it deals with in web browsers, such as windows and forms, and the elements of the form, such as buttons, text boxes, check boxes, and so on. Because you can have more than one dog, or more than one window, it makes sense to give them names. While you could refer to your pets as Dog1and Dog2 and Dog3, it’s a bad idea because its easier to tell the dogs apart if they have uniquenames. In the same way, all the examples in this course will give JavaScript objects their own unique names.

  4. Properties Objects have properties. A dog has fur, the computerhas a keyboard, and the bicycle has wheels. In the JavaScript world, a documenthas a title, and a form can have a check box. Changing a property of an object modifies that object, and the same property name can be a part of completely different objects. Let’s say that you have a property called empty. It’s okay to use empty wherever it applies, so you could say both that the dog's belly is empty and that the dog's bowl is empty. Note that the computer’s keyboard and the bicycle’s wheels aren’t only properties; they are also objects in their own right, which can have their own properties. So objects can have sub-objects.

  5. Methods The things that objects can do are called methods. Dogs bark, computers crash, and bicycles roll. JavaScript objects also have methods: buttons click(), windows open(), and text can be selected(). The parentheses "( )" signal that we’re referring to a method, rather than a property.

  6. Dot Notation ( or Dot Syntax) You can put together objects, properties, and methods to get a better description of an object, or to describe a process. In JavaScript, these pieces are separated by periods (also known as dots, as in Internet addresses). This is called dot notation or dot syntax. Here are some examples of objects and their properties written in this way: bicycle.wheels dog.paws.front.left computer.drive.dvd document.images.name window.status And here are some examples of objects and methods written in dot syntax: dog.bark() document.write() forms.elements.radio.click()

  7. The Document Object Model (DOM) On a web page, the objects that make up the page (or document) are represented in a tree structure. You’ve seen this sort of thing before when building HTML pages; the top level of the page is contained in the <html> tag, and inside that you’ll find the <head> and <body> tags, with other tags within each of those, and so on. JavaScript considers each of the items in the document tree to be objects, and you can use JavaScript to manipulate those objects. The representation of the objects within the document is called the Document Object Model (DOM). NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT the DOM IN OTHER LECTURES

  8. The Document Object Model (DOM) Each of the objects on the tree is also called a node of the tree. We can use JavaScript to modify any aspect of the tree, including adding, accessing, changing, and deleting nodes on the tree. Each object on the tree is a node. If the node contains an HTML tag, it’s referred to as an element node. Otherwise, it’s referred to as a text node. That’s all you need to know about the DOM and nodes for now; you’ll learn more about them later as the course progresses. NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT the DOM IN OTHER LECTURES

  9. Events Events are actions that the user performs while visiting your page. Submitting a form and moving a mouse over an image are two examples of events. JavaScript deals with events using commands called event handlers. An action by the user on the page triggers an event handler in your script. The 12 most common JavaScript event handlers are listed on the right. Event Handlers NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT EVENTS IN OTHER LECTURES

  10. Events In JavaScript, if the user clicks a button, the onclickevent handler takes note of the action and performs whatever duties it was assigned. When you write a script, you don’t have to anticipate every possible action that the user might take, just the ones where you want something special to occur. For instance, your page will load just fine without an onloadevent handler. But you need to use the onloadcommand if you want to trigger a script as soon as the page loads.

  11. Values In JavaScript, a piece of information is a value. There are different kinds of values; the kind you’re most familiar with are numbers. A string value is characters—such as a word or words—enclosed in quotes. A boolean tests whether a statement is true or false Null is used to indicate an empty object Value Types NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT VALUES TYPES IN OTHER LECTURES

  12. Variables Variablescontain values. For example, the variable name is assigned the string “Rex Winkus”. Another way to write this is name = "Rex Winkus". The equals sign is the assignment operator and can be read as “is set to.” In other words, the variable name now contains the value “Rex Winkus”. JavaScript is case sensitive. This means that nameis not the same as Name, and neither is the same as NAME. Variable names cannot contain spacesor other punctuation, or start with a number. They also can’t be one of the JavaScript reserved words. Reserved Words WE WILL GO INTO MORE DETAIL ABOUT VARIABLES A BIT LATER IN THIS LECTURE

  13. Operators Operators are the symbols used to work with variables. You’re already familiar with operators from simple arithmetic; plus and minus are operators. While both x++ and ++x add one to x, they are not identical; the former increments x after the assignment is complete, and the latter before. For example, if x is 5, y = x++ results in y set to 5 and x set to 6, while y = ++x results in both x and y set to 6. The operator -- (minus sign) works similarly. If you mix numeric and string values when adding two values together, the result is a string. For example, "catch" + 22 results in "catch22". Operator Types NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT OPERATOR TYPES IN ANOTHER LECTURE

  14. Comparisons You’ll often want to compare the value of one variable with another, or the value of a variable against a literal value (i.e., a value typed into the expression). For example, you might want to compare the value of the day of the week to “Monday”, and you can do this by checking if todaysDate == "Monday"(note the two equals signs). Comparisons NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT COMPARISON TYPES IN ANOTHER LECTURE

  15. Assignments When you put a value into a variable, you are assigning that value to the variable, and you use the '=' assignment operator to do the job. For example, you use the equals sign to make an assignment, such as name = "Rex Winkus". There are a whole set of assignment operators. Other than the equals sign, the other assignment operators serve as shortcuts for modifying the value of variables. For example, a shorter way to say x = x + 5 is to say x+ = 5. Assignments NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT ASSIGNMENT TYPES IN ANOTHER LECTURE

  16. A Brief Word About Functions Before we get into the Accessing JavaScript in a Web Page examples coming up next, you need to learn a bit about functions, which you’ll use often when writing JavaScript. A function is a set of JavaScript statements that perform a task. Every function must be given a name (with the rare exception of using an anonymous function which we’ll discuss later on in this course) and can be invoked, or called, by other parts of the script. Functions can be called as many times as needed during the running of the script. NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT FUNCTIONS IN ANOTHER LECTURE

  17. A Brief Word About Functions For example, let’s say that you’ve gotten some information that a user typed into a form, and you’ve saved it using JavaScript. If you need to use that information again and again, you could repeat the same code over and over in your script. But it’s better to write that code once as a function and then call the function whenever you need it. Easy-peasy! A function consists of the word function followed by the function name. There are always parentheses after the function name, followed by an opening curly brace (you'll hear me call this an "opening squiggle"). The statements that make up the function go on the following lines, and then the function is closed by a closing curly brace (you'll hear me call this a "closing squiggle"). Here’s what an example of what a function looks like: function sayWhat() {  Notice the camelCase alert("JavaScript is Groovy, Man!"); } Notice that the line with alert is indented. That makes it easier to read your code. All of the statements between the first brace and the last one (and you probably noticed that those two lines are not indented) are part of the function. That’s all you need to know for now about functions. NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT FUNCTIONS IN ANOTHER LECTURE

  18. Conditional Code A conditional tells code to run if something is true and possibly if something is not true if (conditional) { /* then this part */ } else { /* else this part */ } Another way to say the same thing: (conditional) ? { /* then this part */} : {/* else this part */ } Neither way is more “right” than the other. NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT CONDITIONALS IN ANOTHER LECTURE

  19. The <noscript> Tag If the user is using an older browser that doesn't support JavaScript or has his-or-her JavaScript functionality disabled, including the <noscript> tag in your HTML code can alert the user that JavaScript is required for proper page functionality. It is not required to include the <noscript> tag in the exercises and Assignments for this class, but I wanted to reference it in case you see it while you research JavaScript in other web sites or by Goggling it.

  20. Case Sensitivity BE AWARE: JavaScript is case sensitive! When you name a variable or function, pay attention to your uppercase and lowercase letters. myFunctionis not that same thing as MyFunction or myFUNCTION or myfunction. Also, you must refer to built-in objects with the proper casing. Mathand Datestart with uppercase letters, but not window and document. Most built-in methods are combined words by capitalizing all but the first, such as getElementById (often referred to as camelCase).

  21. Comments As with all programming languages—and as we've seen with Java—comments are an important part of the coding process even though they don’t actually do anything in the code itself. They are helpful hints for other people who might read your code. More often, they can remind you of why you wrote that weird piece of code a month ago. Single-linecomments look like this: // This is a single-line comment return true; // Comment after code Multilinecomments look like this: /* This comment can wrap into the next line and even the next line and the next */

  22. Semicolons As with Java, JavaScript statements should end with semicolon like sentences end with a period. Technically they are optional, but that’s only because JavaScript interpreters add them automatically at the end of most lines. It’s best to get into the habit of adding the semicolons yourself because there can be strange side effects when you let the interpreter do it for you. All of the demo examples used throughout this class will hopefully demonstrate proper semicolon usage.

  23. White Space and Newlines Most whitespace such as spaces, tabs, and empty lines is ignored in JavaScript and usually just aids readability. In fact, on large-scale production code, all nonessential whitespace is usually stripped out so that script files download quicker. In the class examples and demo pages, I’ll try to demonstrate how best to use whitespace for readability.

  24. Scope In most of the United States, if you claimed "I'm going to Broadway!" people will assume that you're referring to a street in New York City. While the street is in New York, people globally understand your reference. You can think of Broadway as a global. However, if you're in Seattle and you say you're going to Broadway, people might assume that you're referring to the street on Capitol Hill. This is a local value. In Seattle, not being clear whether you're referring to the local "Broadway" or the globally known "Broadway" can lead to confusion. In Seattle, the default is the locally known version and you have to explicitly state "Broadway in New York City" in order to refer to the other. Outside of Seattle, people will think of New York City's "Broadway" first, unless they too have some other local version of "Broadway." The scope of each of these streets is where each is the default, i.e., the one that will be automatically thought of if no other identifying information is given. With JavaScript code, the easiest way to avoid questions about a variable's scope is to avoid using two variables with the same name in two different places doing two different things.

  25. Balanced Brackets and Quotes It is easy to make mistakes when it comes to punctuation. Remember that every time you open a bracket, such as [ , ( , or { , or a quote mark, such as ' or ", you must close it in the correct order. It can be trickier than you think.

  26. Window Object and Document Object

  27. The Window Object and the Document Object As you learn JavaScript you will be using some code that works with the Windows object and other code that works with the Document object, however the Window object and the Document object are not the same. So, what is the difference between the two? Good question! The "window" is the first thing that gets loaded into the browser. This window object has the majority of the properties like length, innerWidth, innerHeight, name, if it has been closed, its parents, and more. What about the document object then? The documentobject is your html, asp, php, or other document that will be loaded into the browser. The document actually gets loaded inside the window object and has properties available to it like title, URL, cookie, etc. What does this really mean? That means if you want to access a property for the window it is window.property, if it is document it is window.document.property which is more commonly used in short as document.property.

  28. Windows Object (Properties and Methods) The Windows Object (W3Schools) Document Object (Properties and Methods) The Document Object (W3Schools) The Window Object and the Document Object Examples: Return URL of Current Page: document.write(window.location.href); Return Path Name of Current URL: document.write(window.location.pathname); Load a New Document: function newDoc(){window.location.assign("http://www.programajama.com")} <input type="button" value="Load New Document" onclick="newDoc()">

  29. Accessing JavaScript in a Web Page

  30. Accessing JavaScript in a Web Page Web browsers are built to understand HTML and CSS and convert those languages into a visual display on the screen. The part of the web browser that understands HTML and CSS is called the layout or rendering engine. But most browsers also have something called a JavaScript interpreter. That’s the part of the browser that understands JavaScript and can execute the steps of a JavaScript program. Since the web browser is usually expecting HTML, you must specifically tell the browser when JavaScript is coming by using the <script> tag. The <script> tag is regular HTML. It acts like a switch that in effect says “Hey, web browser, here comes some JavaScript code; you don’t know what to do with it, so hand it off to the JavaScript interpreter.” When the web browser encounters the closing </script> tag, it knows it’s reached the end of the JavaScript program and can get back to its normal duties.

  31. Accessing JavaScript in a Web Page • JavaScript can appear in several places: • Inline(JavaScript inside a tag) • Internal(JavaScript in a <script> tag) • External(JavaScript in a separate file with a .js extension) • Dynamic(In an external file loaded by JavaScript)

  32. Inline JavaScript

  33. Inline JavaScript Inline JavaScript appears inside an individual tag. The JavaScript commonly appears inside a event attribute, such as onClick(see below and next slide), or document.write(see Slide 41) <!DOCTYPE html> <html> <head> <title>Hello World 1</title> </head> <body> <form> <input type="button" value="Hello World" onClick="alert('Hello Yourself!')"> </form> </body> </html> http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/helloworld1.html

  34. Inline JavaScript <!DOCTYPE html> <html> <head> <title>Hello World 2</title> </head> <body> <p><a href="#" onClick="alert('Hello Yourself!')">Hello World</a></p> </body> </html> • Notice how the a tag has two attributes (properties) with special values: • hrefattribute is "#" although it might also be empty " ", or contain "javascript:;" • - this disables normal link behavior • onclickattribute is alert('Some Message'); • - onclickis an event — the JavaScript runs when the event happens, in this case when the link receives a click http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/helloworld2.html

  35. Inline JavaScript <!DOCTYPE html> <html> <head> <title>Hello World 3</title> </head> <body> <p><a href="javascript:alert('Hello Yourself!')">Hello World</a></p> </body> </html> In this variation, the JavaScript is actually insidethe href attribute. This is equivalent to the onClick example—we don’t need to explicitly specify the "click" event, because the href takes care of that for us. http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/helloworld3.html

  36. Inline JavaScript The above inline examples demonstrate a single line of JavaScript code—the alert()function—which displays a message in a modal dialog box. Inline JavaScript can be useful for certain specific tasks, but inline should be your third choice. External JavaScript files should be your first choice, internal JavaScript your second.

  37. Internal JavaScript

  38. Internal JavaScript Internal JavaScript appears inside a <script> tag, like this: <!DOCTYPE html> <html> <head> <title>Hello World 4</title> </head> <body> <h2>Hello World</h2> <script> // JavaScript goes here, between the opening and closing <script> tags. // Notice use of "//" comment style while in between the <script> tags. alert('Hello Yourself!'); </script> </body> </html> http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/helloworld4.html

  39. Internal JavaScript <!DOCTYPE html> <html> <head> <title>Hello World 5</title> </head> <body> <h2>Hello World</h2> <h2> <script> document.write("Hello Yourself!"); </script> </h2> </body> </html> http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/helloworld5.html

  40. Internal JavaScript <!DOCTYPE html> <html> <head> <script> function popUp() { alert("Hello Yourself!") } </script> </head> <body> <input type="button" onClick="popUp()" value="Hello World"> </body> </html> http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/helloworld6.html

  41. External JavaScript File

  42. External JavaScript File • To use an external JavaScript file in a web page, use the <script> tag with the src attribute pointing to the JavaScript file. • Example: • <script src="somejavascript.js"></script> • When using the <script> tag to load an external JavaScript file, do not also use the tag as a container for internal JavaScript — that is, do not put JavaScript (or anything thing else) between the opening tag and the closing tag. • External JavaScript files are text files containing JavaScript, and nothing else. • Edit using any text editor. Serious JavaScript developers typically edit files using an Integrated Development Environment (IDE) such as Dreamweaver or Komodo Edit. • Do not use the <script> tag in an external JavaScript file itself — the <script> tag goes in the web page. • When using two or more script tags on a page, the order of the tags can be significant, in terms of JavaScript processing. http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/helloworld9.html http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/helloworld.js

  43. Dynamic JavaScript “Dynamic” JavaScript Versus JavaScript Fundamentally, all JavaScript can be considered dynamic. All dynamic means in this context is that the script is performed on the client’s computer rather than on the server. However, “dynamic” most commonly refers to scripts that control, access, or manipulate HTML elements on the page. Dynamic JavaScript used to be called DHTML – Dynamic HTML – however, this term is rather misrepresentative of what’s really going on. DHTML is differentiated from Ajax by the fact that a DHTML page is still request/reload-based. With DHTML, there may not be any interaction between the client and server after the page is loaded; all processing happens in JavaScript on the client side. By contrast, an Ajax page uses features of DHTML to initiate a request (or 'subrequest') to the server to perform actions such as loading more content.

  44. Variables

  45. Variables When programming, you will often want to change the value of a number, text, or other data. For example, if you are keeping a count of how many oranges you have in a bowl, the number won’t always be the same, since oranges can be added or removed from the bowl at any time. Suppose you want to store the number of oranges in the bowl someplace – and you want that value to change when the number of oranges changes. To do this in a script, you will need to use a variable. A variable holds a value in memory which can then be used or changed. For example, if you decided to write down the number of oranges in a bowl, you might write something like this: Number of Oranges in Bowl: 18 If the number of oranges changed then you would rewrite that number: Number of Oranges in Bowl: 17

  46. Variables • So, as you may recall from the Java class, a variablestores a value that can change as the program executes. When you code a JavaScript application, you frequently declare variables and assign values to them. • Variables are useful because: • They can be used in places where the value they represent is unknown when the code is written • They can be updated or changed programmatically ( as the program is running) • They can save time in writing and updating scripts • They can make the purpose of the code easier to understand • Pseudocode Example: • totalPrice = 2.50 + 2.25 + 1.99 + 44.50 • or • totalPrice = candy + chips + beverage + gas

  47. Defining Variables Now that you understand what variables are and why you want to use them, you need to learn how to make them work in your scripts. You create variables by declaringthem. Then you assign values to them using the JavaScript assignment operator, the single '=' symbol. When you name your variables, you need to follow the rules for naming variables in JavaScript, as well as consider the meaningfulness of the name. Declaring Variables To declare text as a variable, you use the varkeyword (var is short for variable), which tells the browser that the text to follow will be the name of a new variable: var variableName; For example, to name your variable numberOfOranges, the declaration looks like this: var numberOfOranges; In this example, you have a new variable with the name numberOfOranges. The semicolon ends the statement. The variable numberOfOranges does not have a value assigned to it yet.

  48. Assigning Values to a Variable You can give your variables a value at the same time that you declare them or you can assign them a value later in your script. To assign a value to a variable, you use the JavaScript assignment operator, which is the equal to (=) symbol. If you want to declare a variable and assign a value to it on the same line, use this format: var variableName = variableValue; For example, to name your variable numberOfOranges and give it the numeric value 18, use this statement: var numberOfOranges = 18; Here is what each piece of the code above does: varThis is a special keyword in JavaScript that is used to define a variable. numberOfOrangesThis names the variable numberOfOranges . =This is the assignment operator, which assigns the value on its right side to the variable name on its left side. 18This is the value that will be assigned to the variable, which in this case will be 18. ;The semicolon ends the statement, and the browser will move on to any additional statements in the code.

  49. Assigning Values to a VariableCONTINUED BE AWARE: As we learned in Java, be careful not to think of the assignment operator (=) as having the meaning “is equal to.” This operator only assigns a value from right to left (left  right). The operator for “is equal to” is two (2) equal signs together (==), as we’ll cover again in a later class. Naming Variables Before you start naming your own variables, you need to be aware of JavaScript’s naming rules. The factors you need to consider when choosing names are case sensitivity, invalid characters, and the names that are reserved by JavaScript. Additionally, you should try to give your variables names that are both easy to remember and meaningful. Using Case in Variables JavaScript variables are case sensitive—numberOfOranges, numberoforanges, NUMBERoFoRANGES and NumberOfOrangesare four different variables. When you create a variable, you need to be sure to use the same case when you write that variable’s name later in the script. If you change the capitalization at all, JavaScript sees it as a new variable or returns an error. Either way, it can cause problems with your script. It is for this reason that I like to use camel case when naming my variables (and functions too) and stick with it through all my scripting.

More Related