JavaScript Essentials 2013
Introduction
What is JavaScript?
- Scripting language for the web
- No client-side IO features
- Not compiled
- Case Sensitive
Chapter 1: JavaScript General Conventions
- Case sensitive
- Use semicolon for end statement
- Comments
- //
- /* */
- Browser executes code as soon as it sees it
JavaScript Location
- Create function files for all the code logic
- Attach to the html pages as head or use inline calls as you need them
- Fully qualified <script> tag
<script src=”myscript.js” type=”text/javascript”>
</script>
- HTML5 assumes <script> tag is javascript
<script src=”myscript.js”>
</script>
- Have the <script> tag at the very bottom before </body> tag
Chapter 2: JavaScript Components and Syntax
Variables
- These create space in memory and assigned as ‘undefined’
var year; var customerEmail; var todaysDate; |
- Creates space in memory AND assigns it a value of ‘2011’
var year = 2011; |
Allowed Characters
- letters, numbers, _, $
If statement
if ( condition ) { // code goes here // }
if ( condition ) { // code goes here // } else { // code goes here // }
|
Code Block { }
If (somethingIsTrue){ // code block }
If (somethingIsTrue) { // code block }
If (somethingIsTrue){ // code block } |
Operators
Assignment
= |
Arithmetic
+ - * / += -= *= /= |
Increment/Decrement (unary operator)
++ -- a++ b-- --a --b |
Prefix
var a = 5; alert(++a) |
increment a, then run alert()
PostFix
var a = 5; alert(a++) |
run alert(), then increment a
Ternary
var result = condition ? true : false
var player12 = 500; var player2 = 600;
var highScore;
highScore = (playerOne > playerTwo) ? playerOne : playerTwo; |
Modulus ( remainder )
% |
Operator Precedence
* / + - (( 1 + 1 ) / 2) |
Comparison Operators
== <= >= != |
Logical AND/OR
&& AND || OR |
Assignment and Equality
= assignment == equality === strict equality |
Loops
While Loop
a=1; while (condition){
a++; } |
Do..While Loop
do{
a== } while (condition); |
For Loop
for(var a=1; a<100; a++){ //runs 99 times } |
Break
for (var a=1; a<100; a++){
if( imNotDone ){ // go back to the iteration // without doing remaining code for iteration continue; }
if( imDone ){ break; // out of loop } } |
Console
console.log
- Can change icons in firebug to aid in debugging
.log
.debug
.info
.warn
.error
Functions
- Best to declare them BEFORE calling them
function createMessage(parameters){ // code to run return mySomethingVar; } |
Parameter Mismatch
- Extra parameters will be ignored
- Too few parameters causes others to be ‘undefined’
Variable Scope
var globalVar;
function tempVars(){ var localVar; } |
Chapter 3: Arrays and Objects
Arrays
var myArray = []; var myArray = [1,2,3,”mouse”,:tree”,6] var myArray = new Array(); //object oriented version var myArray = Array(); //object oriented version var myArray = Array(5); // 5 slots in the array
var myTwoDimensionalArray = [,]; |
Array Properties
.length
Array Methods
.reverse() – creates a new array
.join()
.sort()
Find all Anchor tags on a page
document.getElementByTagName(“a”);
Numbers
- All JavaScript Numbers are 64-bit floating point numbers
Addition vs. Concatentation
Both Numbers: Arithmetic
var foo = 5; var bar = 5; console.log(foo+bar); //10 |
Both Strings: Concatenate
var foo = "5"; var bar = "5"; console.log(foo+bar); //55 |
Mixed: Treat as String
var foo = 5; var bar = "5"; console.log(foo+bar); //55 - one is a string |
Mixed: Some operations will generate NaN
var foo = 5; var bar = "5"; console.log(foo*bar); // NaN - not a number |
Can use this to check for validation of forms:
var foo = "55"; var mytest = Number(foo); // make it a Number, NaN if it can't if (!isNaN(mytest)){ // do something } |
Strings
Quotes Inside Quotes
‘Don’t mix your quotes’ BAD “Don’t mix your quotes” GOOD “He said,”Bye” and left” BAD “He said,\”Bye\” and left” GOOD |
String Properties
.length |
String Methods
.toUpperCase() .toLowerCase() .split(“,“) // slit at comma |
.indexOf(“string”) // # or -1 if not found
.slice(6,5) // grab char 7 and take 5 chars
< and > can be used for alphabetical
Object Orientation
Object Orientation in Use
var player1 = {name: "Fred", score: 100000, rank:1};
… …
|
Fred has a rank of: 1 and a score of 100000 Sam has a rank of: 2 and a score of 19999 |
Chapter 4: DOM
Document Object Model
document.
Element nodes don’t contain text
If element has an id…
document.getElementById(“someId”);
var myElement = document.getElementByID("abc"); |
ByTagName ( Creates an Array)
document.getElementsByTagName("a"); |
Getting Elements by Id or TagName
var mainTitle = document.getElementById("mainTitle"); console.log("This is an element of type: ", mainTitle.nodeType ); console.log("the Inner HTML is ", mainTitle.innerHTML); console.log("Child nodes: ", mainTitle.childNodes);
var myLinks = document.getElementsByTagName("a"); console.log("Links: ", myLinks.length); |
Changing Element Attributes
var mainContent = document.getElementById("mainContent"); mainContent.setAttribute("align","right");
var mainTitle = document.getElementById("mainTitle"); console.log(mainTitle.innerHTML);
var sidebar = document.getElementById("sidebar"); console.log(sidebar.innerHTML); |
Creating DOM Content
Creating Elements
.innerHTML Method
var newHeading = document.createElement("h1"); |
Better to use TextNode to assign text values
// create new elements var newHeading = document.createElement("h1"); var newParagraph = document.createElement("p");
// create associated text nodes.... var h1Text = document.createTextNode("Did you know?"); var paraText = document.createTextNode("Califormia produces over 17million gallons of wine each year!");
// append, instead of create... newHeading.appendChild(h1Text); newParagraph.appendChild(paraText);
// append to page DOM.. document.getElementById("trivia").appendChild(newHeading); document.getElementById("trivia").appendChild(newParagraph); |
//Alternatives to APPENDCHILD // create new element BEFORE THE END parent.insertBefore(newElement, existingElement); var myNewElement = docueme.createElement("li"); var secondItem = myElement.getElementsByTagName("li")[1]; myElement.insertBefore(myNewElement, secondItem); |
EVENTS and EVENT LISTENERS
Examples, normally..
- lowercase
- start with 'on'
- onload
- onclick
- onmouseover
- onblur
- onfocus
// #1 INLINE scripting <button onclick="alert('Hello, world');" > Run Some JavaScript </button> |
Use semicolon because whole thing is a STATEMENT
element.event = function(); |
// #2 ANONYMOUS FUNCTION myElement.onclick = function(){ // event handler code ... // ... // ... }; |
// #3 using DOM addEventListener... // (event sans 'on', functionname, false) document.addEventListener('click', myFunction, false); document.addEventListener('click', anotherFunction, false); document.removeEventListener('click', anotherFunction, false);
//Browsers incosistent..IE8 and previous document.attachEvent('onclick', myFunction); |
Use premade script for this….
Use JQuery (or another library) instead of writing you own cross-browser code
Common Events
document.onclick = function() {
document.onclick = function() { |
window.onload
- only write the window.onload function ONCE
- ONLY the last declared function will be used if there are multiple ones
function prepareEventHandlers(){ var myImage = document.getElementById("mainImage"); myImage.onclick = function(){ alert("You clicked the image"); } }
window.onload = function(){ //prep anything we need to prepareEventHandlers(); } |
onfocus & onblur
var emailField = document.getElementById("email");
emailField.onfocus = function() {
if ( emailField.value == "your email") {
emailField.value = "";
}
};
emailField.onblur = function() {
if ( emailField.value == "") {
emailField.value = "your email";
}
};
Timers
Assign a timeout to an INTERVAL, then
setTimeout(function,millisconds)
setInterval(function,millseconds)
clearInterval(intervalHandle)
// Two methods for timers - setTimeout and SetInterval (single / repeating)
function simpleMessage() { alert("This is just an alert box"); }
// settimeout is in milliseconds //setTimeout(simpleMessage,5000);
var myImage = document.getElementById("mainImage");
var imageArray = ["_images/overlook.jpg","_images/winery_sign.jpg","_images/lunch.jpg", "_images/bigSur.jpg","_images/flag_photo.jpg","_images/mission_look.jpg"]; var imageIndex = 0;
function changeImage() { myImage.setAttribute("src",imageArray[imageIndex]); imageIndex++; if (imageIndex >= imageArray.length) { imageIndex = 0; } }
// setInterval is also in milliseconds var intervalHandle = setInterval(changeImage,5000);
myImage.onclick = function() { clearInterval(intervalHandle); }; |
FireBug
Debugging controls
Breakpoint: Gutter: Left-Click
Set breakpoint by Expression: Gutter Right Click
Forms
Validating Forms
If forms have id or name, can use DOM to access
Document
TEXTFIELDS
CHECKBOXES AND RADIO BUTTONS
SELECT
FORM EVENTS
Validate form data entry by catching the onsubmit
onsubmit Return FALSE
- Return False on the ‘onsubmit’ event will prevent form submission; validate here
// handle the form submit event function prepareEventHandlers() { document.getElementById("frmContact").onsubmit = function() { // prevent a form from submitting if no email. if (document.getElementById("email").value == "") { document.getElementById("errorMessage").innerHTML = "Please provide at least an email address!"; // to STOP the form from submitting return false; } else { // reset and allow the form to submit document.getElementById("errorMessage").innerHTML = ""; return true; } }; }
// when the document loads window.onload = function() { prepareEventHandlers(); }; |
Show Hide Components
// show and hide sections of a form function preparePage() { document.getElementById("brochures").onclick = function() { if (document.getElementById("brochures").checked) { // use CSS style to show it document.getElementById("tourSelection").style.display = "block"; } else { // hide the div document.getElementById("tourSelection").style.display = "none"; } }; // only hide the form element IF JAVASCRIPT is ENABLED… // now hide it on the initial page load. document.getElementById("tourSelection").style.display = "none"; }
window.onload = function() { preparePage(); }; |
Setting Inline Styles
myElement.style.color = “#FF000”; myElement.style.left = “40px”; myElement.style.backgroundRepeat = “repeat-x”; |
Style Property Naming
- Properties with dashes, convert to camelCase
- Always set the values as a string
- Semicolon to end property assignment
Applying Classes
“class” is a reserved word in JavaScript
myElement.class myElement.className = “someCSSclass”; myElement.className= “”; |
- If an Element is assigned a certain class, replace it with….
- Tighter/closer matched CSS will override styling here…
// prevent a form from submitting function preparePage() { document.getElementById("mainContent").onclick = function() { if ( document.getElementById("mainContent").className == "example") { document.getElementById("mainContent").className = ""; } else { document.getElementById("mainContent").className = "example"; } }; }
window.onload = function() { preparePage(); }; |
Moving CSS styled items based off a timer
var currentPos = 0; var intervalHandle;
function beginAnimate() { document.getElementById("join").style.position = "absolute"; document.getElementById("join").style.left = "0px"; document.getElementById("join").style.top = "100px"; // cause the animateBox function to be called intervalHandle = setInterval(animateBox,50); }
function animateBox() { // set new position currentPos+=5; document.getElementById("join").style.left = currentPos + "px"; // if ( currentPos > 900) { // clear interval clearInterval(intervalHandle); // reset custom inline styles document.getElementById("join").style.position = ""; document.getElementById("join").style.left = ""; document.getElementById("join").style.top = ""; } }
window.onload = function() { setTimeout(beginAnimate,5000); }; |
Conventions
Variables and Functions
var score; var highScore; var evenHigherScore; function calculate(){... function calculateDistance(){... funtion checkFormFields(){...
|
Objects:
- Math
- Date
var myDate = new Date();
|
Brace Style ( Always Use Blocks { } )
if (x) { //... //... } else { //... //... } |
Define Functions BEFORE You Call Them
function animateBox() { // set new position if ( currentPos > 900) { // clear interval // reset custom inline styles } }
window.onload = function() { setTimeout(beginAnimate,5000); }; |
Search Javascript style guidelines
Javascript Minification
- SAVES SPACE
- Compressed to save space and EOL errors
- Replace long var and function names
- Tools
- JSMin
- YUI Compressor
- Google Closure Compiler
Simple
Advanced
JavaScript Quality Checker
Jslint.com
Take code, paste into, check
JavaScript Libraries
- jQuery
- Closure
- Mootools
- YUI
- Dojo
Intro to jQuery
<!-- loading jQuery BEFORE using it --> <script src="jquery-1.6.1.min.js"></script> <script src="script.js"></script> |
document.getElementById("myDiv").className = "highlight"; jQuery("#myDiv").addClass("highlight"); jQuery(".someClass") jQuery("p"); jQuery("a"); jQuery("li");
// able to drill down css selectors jQuery("p.description"); |
// use jQuery - basic //jQuery("#mainArticle").addClass("highlight");
// find all elements with a particular class //jQuery(".tourDescription").addClass("highlight");
// find all elements with a particular tag //jQuery("li").addClass("highlight");
// find the last li //jQuery("li:last").addClass("highlight");
// find any paragraph that contain the word "packages" //jQuery("p:contains('packages')").addClass("highlight"); |
jQuery Methods
document.getElementById("myDiv").classname = "highlight":
jQuery("#myDiv").addClass("highlight"); .removeClass("highlight"); .toggleClass("highlight"); |
$("#myDiv").addClass("highlight"); $("what to find").someAction(any params); |
jQuery Applications
// basic document.getElementById("mainArticle").className = "highlight";
// use jQuery - basic //jQuery("#mainArticle").addClass("highlight");
// find all elements with a particular class //jQuery(".tourDescription").addClass("highlight");
// find all elements with a particular tag //jQuery("li").addClass("highlight");
// find the last li //jQuery("li:last").addClass("highlight");
// find any paragraph that contain the word "packages" //jQuery("p:contains('packages')").addClass("highlight");
// EFFECTS
// hide all paragraphs. //$("p").hide(4000);
//$("p").fadeOut(4000);
// EVENTS
// simple click // avoid xpath/dom with jQuery..... //$("#pageID").click(function() { // $("#pageID").text("You clicked me!"); //});
// add $(this) to refer to current element //$("h2").click(function() { // $(this).text("You clicked me!"); //});
// add effects - this makes each paragraph fade out when clicked. //$("p").click(function() { // $(this).fadeOut(2000); //});
// Page load events - instead of window.onload() //$(document).ready(function () { // $("#pageID").text("The DOM is fully loaded."); //});
// you don't have to worry about accidentally calling it multiple times. //$(document).ready(function () { // $("h1").css("color","red"); //}); |
CONTENT DISTRIBUTION NETWORK (CDN)
- Faster to pull from Google
- Always update
- Improved bandwidth
- Improved parallel downloads ( by requesting from multiple domains )
Caching benefits
- Multiple websites using the CDN copy of jQuery, users won’t have to load when changing sites…improved performance for client
- Don’t use on internal/intranet sites where the internet may be interrupted without affecting the site
HTTP and HTTPS PAGES
- Use whatever protocol the page is using by removing the protocol in the URL
HTML5 and JavaScript
Main Features
- Varies by Browser
- Caniuse.com
JavaScript Additions
var a = document.getElementById("mainTitle"); var b = document.getElementsByTagName("li");
var c = document.getElementsByClassName("myclass"); var d = document.getElementsByClassName("first second"); |
HTML5 Storage
Web Workers
Feature Detection
if (document.getElementsByClassName ) { // it exsists, we can us it // ... } else { // it doesn't exists on this browser } |
Modernizer.com
Strict Mode
- Forces good JavaScript syntax
- Don’t mix and match Strict Mode files
JavaScript to Avoid
Document.WRITE
- Can only use it when page is initially loading
Broswer Sniffing
- Detect features, not browsers
Eval
- Security vulnerabilities executing code that is stored in variables
- Code can be injected
Psuedo-Protocols
- Mixing HTML and JS…bad practice
- If Javascript is turned off, won’t run
- Return false; keeps link from working and allow js to handle functionality
- JS should ADD functionality
Introduction to Regular Expressions
- Create the Regular Expression
- Then Apply to something else
- Looks for ‘hello’ to be matched against
var myRE = /hello/;
//or var myRE = new RegExp("hello"); var myString = 'Does thes sentence have the work hello in it?"; if ( myRE.test(myString) ) { alert("Yes"); } |
Creating Patterns
More Complex Patterns
- Email checking RegEx Examples
AJAX
- Asynchronous JavaScript And XML
- Ajax == JavaScript
- After web page is loaded in a browser, AJAX can call back to the server and update the page
- Create the request
- Handle the server response
- 2 different tasks so browser doesn’t hang up waiting on a response
// Prepare the Request var myRequest; //feature check! if (window.XMLHttpRequest){ //firefox, safari myRequest = new XMLHttpReuqest(); } else if (window.ActiveXObject){ //ie myRequest = new ActiveXObject("Microsoft.XMLHTTP"); }
// Prepare to accept the Response myRequest.onreadystatechange = function(){ console.log("We were called!"); }
// THEN configure and send myRequest.open("GET","http://mysite.com/somedata.php",true); myRequest.send(null); |
Introduction to Prototypes
- Built in language type
- Similar to ‘classes’
- Create constructor function, add a passed parameter
- Then call function and pass the value
function Player(n) { // don't use specific data within the constructor // use a parameter to do get the assignment value // this.name = "fred"; this.name = n; }
// calls the contructor function // var fred = new Player(); <-- no var fred = new Player("fred"); var fred = new Player("jeff"); |
Another Example
// Simple prototype example
// creating object properties function Player(n,s,r) { this.name = n; this.score = s; this.rank = r; }
// creating object method1 Player.prototype.logInfo = function() { console.log("I am:" , this.name); }
// creating object method2 Player.prototype.promote = function() { this.rank++; console.log("My new rank is: " , this.rank); }
var fred = new Player("Fred",10000,5); fred.logInfo(); fred.promote();
var bob = new Player("Bob",50,1); bob.logInfo(); bob.promote();
var jane = new Player("Jane",50000,10); jane.logInfo(); jane.promote(); |
Example: Countdown
// two global variables var secondsRemaining; var intervalHandle;
function resetPage() { document.getElementById("inputArea").style.display = "block"; }
function tick() { // grab the h1 var timeDisplay = document.getElementById("time");
// turn seconds into mm:ss var min = Math.floor(secondsRemaining / 60); var sec = secondsRemaining - (min * 60);
// add a leading zero (as a string value) if seconds less than 10 if (sec < 10) { sec = "0" + sec; } // concatenate with colon var message = min + ":" + sec; // now change the display timeDisplay.innerHTML = message;
// stop if down to zero if (secondsRemaining === 0) { alert("Done!"); clearInterval(intervalHandle); resetPage(); } // subtract from seconds remaining secondsRemaining--; }
function startCountdown() { // get contents of the "minutes" text box var minutes = document.getElementById("minutes").value; // check if not a number if (isNaN(minutes)) { alert("Please enter a number!"); return; } // how many seconds? secondsRemaining = minutes * 60; // every second, call the "tick" function intervalHandle = setInterval(tick, 1000); // hide the form document.getElementById("inputArea").style.display = "none"; }
// as soon as the page is loaded... window.onload = function () { // create input text box and give it an id of "minutes" var inputMinutes = document.createElement("input"); inputMinutes.setAttribute("id", "minutes"); inputMinutes.setAttribute("type", "text"); // create a button var startButton = document.createElement("input"); startButton.setAttribute("type", "button"); startButton.setAttribute("value", "Start Countdown"); startButton.onclick = function () { startCountdown(); }; // add to the DOM, to the div called "inputArea" document.getElementById("inputArea").appendChild(inputMinutes); document.getElementById("inputArea").appendChild(startButton); }; |
Example: Resize
- Resizes a page based on window.onresize and adjustStyle()
function adjustStyle() { var width = 0; // get the width.. more cross-browser issues if (window.innerHeight) { width = window.innerWidth; } else if (document.documentElement && document.documentElement.clientHeight) { width = document.documentElement.clientWidth; } else if (document.body) { width = document.body.clientWidth; } // now we should have it if (width < 600) { document.getElementById("myCSS").setAttribute("href", "_css/narrow.css"); } else { document.getElementById("myCSS").setAttribute("href", "_css/main.css"); } }
// now call it when the window is resized. window.onresize = function () { adjustStyle(); }; |
CSS to hide images on small screen
img { display: none; } |
Example: Accordion
- Html with #accordion css id
<div id="accordion"> <h3><a href="#">Customer notifications</a></h3> <div> <p>When you book a tour with Explore California, you should receive two notifications via email. The first will be a <strong>tour confirmation</strong>, which states that your tour is booked, gives you the dates of your tour, and lists all amenities included in your package. The second notification should arrive two weeks prior to the start of your tour. This will be a <strong>reminder notification</strong> and will contain your tour dates and current tour conditions, if applicable. <em>If you do not receive a confirmation within 24 hours, or the reminder notification two weeks out, contact us immediately</em>. We’ll make sure there are no problems in the system and confirm your tour.</p> </div> <h3><a href="#">Tour vouchers</a></h3> <div> <p>Some tour packages include tour vouchers. These tour vouchers allow you to participate in optional activities during a tour and are usually scheduled for downtime or as an optional choice to replace the day’s featured activity. The vouchers are only good during the tour and have no cash value, and cannot be redeemed if the tour is not taken. The tour vouchers are negotiated with 3rd party vendors. Although Explore California monitors these vendors closely, we cannot guarantee that scheduled activities will take place.</p> </div> <h3><a href="#">Trip planning</a></h3> <div> <p>After registration, you will be sent a PDF trip planning document specific to your tour. In the Trip Planner we offer packing advice, places of interest along the tour route, a historical and environmental overview of the tour, a list of any required equipment for the tour that is <em>not</em> provided by Explore California, and additional resources for researching the surrounding area and points of interest included in your tour. Additional information about specific tours can be found in our FAQ section.</p> </div> <h3><a href="#">Tour checklist</a></h3> <div> <p>As you prepare for your tour, we want to make sure that you have everything you need to fully enjoy your time in California. Having everything in place when you arrive makes it easy to sit back and enjoy all that your tour has to offer. With that in mind, we’ve prepared a small checklist to help you make sure you’re ready to go!</p> <ul> <li>Have you arranged for your mail/paper deliver?</li> <li>Are friends/family aware of your itinerary?</li> </ul> </div> </div>
… … … <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"></script> <script src="script.js"></script> </body> </html> |
window.onload = function () { $("#accordion").accordion(); }; |
Sitelist
http://developer.mozilla.org/en/JavaScript
http://developer.yahoo.com/javascript/
http://developer.yahoo.com/performance/
- Log in to post comments