Web Design III: Teach Yourself JavaScript Marquette OPUS College of Engineering

Embed Size (px)

DESCRIPTION

Refresher – Internet 101 How does the internet work? Your PC/Phone/Tablet A Web Server Other Web Servers and Other PCs Web Provider

Citation preview

Web Design III: Teach Yourself JavaScript Marquette OPUS College of Engineering Welcome! Instructor: Karen Mayes Lead Instructor for Marquettes Engineering Outreach programs. Scientist, Teacher in the 19 th Grade. Lifelong learner AndNope. STILL not a web designer! Assistant Instructors: Marquette Engineering Students Class schedule: 8:30 am to Noon. Refresher Internet 101 How does the internet work? Your PC/Phone/Tablet A Web Server Other Web Servers and Other PCs Web Provider Our Web-Design Toolbox HTML: Fetches information from the server and displays it CSS: Makes displayed information pretty (Adds formatting) PHP: Allows the web server to carry out tasks by running scripts MySQL: Collects data in tables where it can be retrieved by PHP Javascript: Allows the client PC to carry out tasks by running scripts REMINDER! Planning: Its not optional! When you are designing a website, start by thinking about what you want to accomplish. What basic structure will your site have? HTML What do you want it to look like? CSS What information will you need to access on your server? MySQL What will you do with your information? PHP What input do you need from your users? HTML Forms What interactive features do you want on your web pages? Javascript JavaScript is a scripting language Remember Scripting languages do not need to be compiled. The raw code works without any additional steps. Javascript has virtually nothing to do with Java. Java is a programming language and must be compiled. JavaScript vs. PHP Both are scripting languages Both can perform many of the same functions Math operations, comparisons, if/then/else, etc. PHP runs on the web server. In order to run a user-commanded PHP script, you have to post the command to the server. This means you will need submit information every time you want to execute a command. Submitting form data opens a new web page. Javascript runs on the web browser. It can perform tasks immediately without having to submit data. It cannot talk to MySQL. JavaScript runs in browsers You, as the web designer, have ultimate control of the server. You have no control over the users browser. Different browsers interpret JavaScript differently. For the most part, if theres a browser that doesnt work the way everyone else does, its Internet Explorer. JavaScript help for beginnersAnd, when all else fails SUPER HELPFUL TOOL! Use the Firebug plugin to debug your scripts In PHP, the server can throw an error message at you with a line number. Browsers dont do this! Firebug is a plugin that allows you to observe a script as it happens. Using separate script pages Good practice is to keep all your scripts in one file and link to it from within your HTML page. We did this with our CSS stylesheet We could have done this (in many places) with PHP You dont HAVE to do this, but it keeps your code clean. Ultra-basic Javascript Syntax JavaScript uses the following characters in its syntax: .;{ }() These are (somewhat unfortunately) the same characters that PHP uses. The two languages (also unfortunately) do not always use them the same way. Examples: keyword keywordName; object.method(parameters){instructions;} JavaScript is Object Oriented Objects are groups of code that relate to a common subject. Those objects can be described (Properties) The objects can undergo actions You can create commands that affect those objects (Methods) An example: Lets say your web page tracks your video game scores. You would define a game object You would then define things about the game gameName type currentScore You can then use that information to perform tasks. Enter a new score and decide if its higher or lower Calculate how much higher or lower became Show progress to the next level/achievement Web browsers read JavaScript like you read books Browsers start at the top of a page and read down. Browsers start at the left (beginning) of a line of code and read to the right (end). This is important!! If you try to use a variable, object, method (or anything else!) that you havent defined, your browser gets confused! JavaScript variables JavaScript holds data in variables, much the same as PHP does. JavaScript has far fewer types of variables Number (no integers or floats!) String Boolean Object Array Undefined Defining variables in JavaScript The var keyword tells JavaScript youre defining something. var score; score=300; You can squish this together. var score = 300; To define a string, put the object in quotes. var gameName = Skyrim; Concatenation in JavaScript JavaScript uses + instead of . var name = Mike + + Wazowski; results in Mike Wazowski JavaScript interprets the variable type as it reads. var info = Mike results in 7Mike var info = Mike+3+4 results in Mike34 Weird variable types Undefined: Just that you havent created it yet. If you try to use a variable in a script somewhere that isnt defined yet, youll get a variable undefined error. Also: var stuff; is undefined because you havent put a value in the variable yet. Empty: A string with nothing in it. var stuff = ; 0: A number with value 0 var stuff=0; Null: A variable with nothing in it. Shows something is missing. Its like a placeholder. var stuff = null; Web browsers have short-term memory loss JavaScript variables are defined and used on a single web page (or sometimes even a small part of a single page.) As soon as you go to a new page or refresh the page, all the data in variables is erased. There are ways to carry data into a new page, but it doesnt happen automatically. Adding JavaScript to your HTML Use a tag! You can (should) specify the kind of script, but most browsers figure it out. The type attribute for JavaScript is: type=text/javascript Example: //put scripts here Linking a separate JavaScript file Use the src attribute. Example: If our JavaScript file is called myScript.js, and is found in our root folder, it would look like this: Some basic JavaScript code To print something in your web page: document.write (Message); To make a popup appear with a message: alert (A standard alert); If, else if, else statements Good news! Everything you learned about these statements works in JavaScript! Bad news! The syntax is different. PHP: if( $myGrade>12){ echo "Congratulations on completing high school!"; } elseif ($myGrade>=9){ echo "Congratulations on completing grade $myGrade!"; } else { echo "Good luck when you start high school!"; } echo "Goodbye!"; JavaScript: if(myGrade>12){ document.write(Congratulations on completing high school!); } else if (myGrade>=9){ document.write (Congratulations on completing grade +myGrade+!); } else { document.write (Good luck when you start high school!); } document.write (Goodbye!); Dot Notation JavaScript is Object-Oriented To do anything with an object, you need to: Specify which object you want Specify the property or method of the object you care about Give any extra needed parameters Example: document.write(Hi there!); ObjectMethodParameter. (); Arrays Arrays are variables that hold a series of items The items in an array appear in brackets after the arrays name. var workDays = [M, T, W, Th, F]; JavaScript keeps track of arrays using an imaginary numeric index, starting with 0. So M = 0T = 1W = 2Th = 3 F = 4 To fetch a particular value from an array, use its index. document.write (TGI+workDays[4]); Arrays have useful properties The length property of an array returns the number of values in an array. For Example, using the previous array, document.write(workDays.length); would return a value of 5 Arrays have useful methods pop() removes parameter(s) from the end of the array push() adds parameter(s) to the end of the array shift() removes parameter(s) to the start of an array unshift() adds parameters to the start of a script If you have to work weekends workDays.push (Sa, Su); PHP uses arrays, too. They look largely the same. $workDays = [M, T, W, Th, F]; They work largely the same. When PHP retrieves information from a MySQL query, it gets the information in an array An Example of a PHP array: Returns this: Writing a JavaScript Function You have the ability in JavaScript to write short sets of directions called Functions. A function does something you define. By creating the function, you can later use it as many times as needed in your document. You might create a function that checks if a text box is filled and changes the color of the box if it is. Well do that in a few moments. Syntax: defining a function Use the function keyword. Example: function sayHello (name){ document.write (Hello +name+!); } The name variable only exists inside the function. When you call the function, whatever you put in the parentheses is added to the name variable. To call the function: sayHello(Karen); This would return: Hello Karen! Functions are re-usable! Define the function once, use it many times! Example: sayHello(Bob); sayHello(Sue); sayHello(Mike Wazowski) JavaScript is tailored to work with browsers. PHP was tailored to work with MySQL. JavaScript has methods built into it specifically designed for web interactivity You can select and work with items on a web page using their ID or name. Using two documents We will create all our JavaScript code in its own document. We will reference this document in our php page. This is exactly what we did with our CSS document! We can then modify our php code to use the scripts we put in the JavaScript document. Select using HTML attributes We created a form with fields that had name attributes. If we also add ID attributes, we can use this information for JavaScript to locate and do things with it. For example, we can use the style.backgroundColor property to change a color. Add IDs to your fields JavaScript is much more cooperative if you select by ID instead of name. Just add the ID attribute into the form field tag. The name is used by PHP (not the ID) The ID info is added for JavaScript to use Create a JavaScript document and reference it. Open a new Notepad++ file. Specify JavaScript as the language. Save it in your root folder as your- initialsJavaScript.js Then, open your original family field entry form (for me this was kmayes.php) Add a script tag with the reference in it: Write a function! Lets check our family table text boxes and have them change color when they are filled. Start by defining a function. Function checkFilled(){ //well write our directions here } Selecting the form field: Lets change the color of the first field (the name field) when it has text in it. First, we need to zero-in on that form field. Do this by creating a variable. var inputField=document.getElementByID(name); The inputField variable now has selected the ability to select a form field by the ID we assigned it. Check to see if its filled Use an if statement. if(inputField ==""){ inputField.style.backgroundColor=white; } else { inputField.style.backgroundColor=yellow; By stating that the style.backgroundColor of our element is white or yellow, we MAKE the element white or yellow! Put it all together and call the function Our JavaScript: Add the following attribute to the form field tag, in order to have it call the function when the field contents change. Ready? Check it! Adding Libraries: JQuery Web pages have gotten very complex. For example: Selecting by ID alone might not be efficient. Lots of smart people put together a set of functions in a single document. These functions make JavaScript easier to use for web design by utilizing our CSS info. Adding JQuery you already did this! Just like you referenced your own javascript document, you can reference JQuery. Lots of big companies host JQuery and allow you to link to their document. Go to code.jquery.com to find the latest version. Example: Super-useful JQuery shortcut This: inputField=document.getElementById(name); Becomes this: inputField = $(#name); The Smarties-That-Be shortened this incredibly useful (but really long to type) command into a simple notation. $(#ID) JavaScript can do MANY things to your web page Auto-fill a form when a drop-down menu is selected. Allow you to click on an image and have the image pop up in front of the text without reloading the page. Change the cursor or web elements on the page when you hover over them. Instantly total a series of text fields as you enter data. There simply isnt time to show you all of these options. So now what? The rest is up to YOU. Imagine your web page. Plan it. Start using your resources. it!!! Good Books! Any of the For Dummies books JavaScript & Jquery by Jon Duckett Download this slide show!documents/WebDesign3.zip