DOC PREVIEW
Intro to Java script

This preview shows page 1-2-3-24-25-26 out of 26 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Intro to JavaScriptACM Webmonkeys @ UIUC, 2010What is JavaScript?Javascript is a scripting language used primarily on the web for client-side scriptingAlso used on Palm's WebOS for app development Has nothing to do with JavaLoosely-typed, dynamically boundSupports objects and closures, making it suitable for larger-scale projects"Client-side scripting"In the context of web apps, Javascript is a client-side language.This means it runs in the web browser, NOT on the serverYou cannot directly access your database or any files on your web server from JavaScript the way that PHP can You can communicate with the server via separate HTTP requests (this is how AJAX, etc. work)Always keep in mind that the code is running on the client's computer! Do not expect it to be secure!Browsers can execute arbitrary JS on your page JS is meant to improve usability and add fancy effects to your web pages' interfaces.One last note before we get startedNot all browsers will have JavaScript enabled.Plug-ins like NoScript will block your scripts from running by defaultBots (from Google et al.) do not have JS enabled. So, if you're using JavaScript on your site, make sure you have a degradation strategy for users without itIf needed, this can be "Please enable JavaScript to view this page"Adding JavaScript to your webpageTo include a script on your webpage, you need to add a <script> tag into the HTML. The syntax of the script tag is: <script type="text/javascript"> // JavaScript goes here. </script>Or, if you have an external JS file to include:<script type="text/javascript" src="path/to/file.js"></script> The script is evaluated by the browser when it is first encountered.Triggering JavaScript from your pageTo call a JavaScript function (you cannot call a script tag explicitly, you must wrap your code in a function), use one of two methods:1. A link (<a> tag) with an href of javascript:myFunc()<a href="javascript:doThisStuff();">Click Here!</a> 2. An event in any tag:<div onclick="doThisStuff();"></div><button onclick="callMyFunction('blah');">Note that events include onclick, onmouseover, onmouseout, onload, etc., and can be added as attributes to any HTML tag.Use of these events is often referred to as DHTML (dynamic HTML), but that doesn't really mean much.The basics of JavaScriptVariables in JavaScript are loosely-typed, so you don't need to define what type they are. var x; // defines x as a variable. Can be omitted.x = 4; // sets x to 4.x = "str"; // sets x to a string value, even if it was an int.y = x + 4; // operations work as in CYou can concatenate strings and variables with the + operator, so the above example would've set y to "str4".Arrays in Javascript are implemented as objects, so to make an array you do:myArr = new Array(); // (next line overwrites)myArr = [4, 2]; myArr.push(3);myArr is now [ 4, 2, 3 ];Can do associative arrays as well (i.e., string keys)Control structures, etc.Javascript has the same if statements and for and while loops that you'd expect (syntax is the same as C/PHP/etc)There's also the for-each structure, which iterates over each object in a collection (e.g., an array):for (obj in myArray) { alert("now looking at " + obj);}Functions in JavaScriptFunctions in JavaScript can be defined straightforwardly:function myFunction(x, y, z) { return x + y + z; } JavaScript is also a functional language, however, so you can even assign functions to variables (closures):foo = function(x, y, z) { return x + y + z; }alert(foo(1,2,3)); // alerts 6This latter property will come in handy later, but don't worry if you don't understand it immediately.A useful built-in function is the alert function, which brings up a dialog box containing the passed message.Good for debugging on a tight schedule.But how do we get anything done?In general, just adding numbers and concatenating strings in JavaScript is pointless unless we somehow output our result, or cause some sort of change in the page.To do this, we need to interact with the page itself.We could use the function document.write() to write onto the end of the page, but that's only so useful. The best way to do this is via the DOM model, which will let us manipulate individual elements on the page.The Document Object Model (DOM)The Document Object Model, or DOM, is an abstract model of a web page. Rather than looking at a page as a string of HTML, we consider the HTML as the elements it defines and create a tree:What's in a DOM element?Any DOM element has the following properties:innerHTML - returns the HTML text inside this element.e.g., document.body.innerHTML will return the text inside the body tagouterHTML - if possible, returns the inner HTML text plus the element's tagDoesn't work for body, but if you have some paragraph tag, myparagraph.outerHTML would return <p>blah blah blah</p>children - List of the element's child elements.You can also access any HTML or CSS attribute, like:mydiv.align = "center"; myparagraph.style.width = "400px";Getting around the DOMWithin any piece of JavaScript, you can use the global variable document to refer to the root node of the DOM tree. From the document element, you can access the properties head and body; for further levels of detail, however, we'll need to look up elements in particular.How can we look up an element?Option 1: by name (e.g. find all divs)use document.getElementsByName("div")Returns an array. Option 2: by ID (e.g. find div with ID "mydiv")First, make sure the element has an ID:<div id="mydiv">Blah</div>Then, use document.getElementById("mydiv");Returns the div itself, or null if not found.Let's try it out: rewriting textSuppose we have a text field, and when the user clicks a link, we want the text field's value to be overwritten to the word "hello". How can we do this?1. Give the text field an ID2. Create a link, and trigger a JavaScript function from it3. Create a JavaScript function to change the text field's value propertyThe code<html><head> <script type='text/javascript'>function changeTextField() { document.getElementById("myfield").value = "hello";}</script></head><body> Text field: <input type="text" id="myfield" /><a href='javascript:changeTextField();'>Click here!</a> </body></html>RecapSo, all that's really going on is that we created a function in Javascript which used a little bit of DOM manipulation (finding an element within the document by a specific ID) and set its value property to the string "hello".Then, we bound that function to be called when


Intro to Java script

Download Intro to Java script
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Intro to Java script and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Intro to Java script 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?