Week 12: Demo
JavaScript Exam Study Guide
In preparing for the WRITTEN exam I would suggest:
- Review the Study Guide below to make sure you are familiar with all relevant concepts and functionality we have covered this semester. Any areas that you are unsure of review the original lectures.
- Be prepared to illustrate your knowledge of Javascript.
- Be prepared to illustrate your knowledge of jQuery.
- Reviewing your past assignments, labs, etc. may have some use. The written exam involves writing some code.
In preparing for the PRACTICAL exam I would suggest:
- Review the Study Guide below.
- Review your past assignments, labs and demos/resources.
- Note that on the practical exam you can use ANY combination of Javascript and jQuery and WILL be able to reference your past work and webdev notes and samples, as well as third party references such as W3Schools, Mozilla, and even Stack Overflow.
Written Examination
- Questions can be true/false, multiple choice, short fill-in, longer code writing, or narrative descriptions/explanations:
To find a character within a string you would use
which of the following methods:
A) charAt B) indexOf C) substring D) findChar
E) None of the above
The regular expression that represents all occurrences
of commas in a string is: ___________
What does an array loop do? (short answer)
- Write a short set of code:
Above are two parallel arrays.
Write below the code that would loop through the arrays,
pulling out the value from the second array that matches
the data from variable "userinput" from the first array.
- Analyze/explain code functionality or theory:
Above is a fairly standard "for" loop. Explain what it is doing.
- Debug:
Find the errors in a supplied line of code.
Practical Examination
- You will be given instructions on building a page that fulfills certain functionalities. You must put together the page to implement the goals of the exam. If applicable you will also be provided a screenshot of what the page will look like.
- On the Practical Exam you CAN use a combination of Javascript and jQuery.
- Like most class assignments, the key is to work through the page requirements step-by-step. It is suggested that you first plan out the routine using JavaScript comments, and then fill in the code/functionality. That way if you run out of time or forget how to do something you can get partial credit for certain routines/functionalities.
- Even if you are not able to complete the exam (to produce a fully functional page that operates as instructed) you will be given partial credit for all of your work. So make sure you complete as much as possible.
- To prepare for this exam, review your past labs and assignments and the "Functionality" part of the Study Guide below.
- You will have a CHOICE of two practical exams so that you can try to target (or avoid) a particular area of scripting, such as object manipulation and/or data. Partial examples of past practical exam area:
- Customize page: User selects images and inputs values to customize a page/div.
- Number games: UI and basic game mechanics for number games.
- Array data: Output array data into page, search through array data, take user-entered data and add to arrays.
- Calculations: A) Output and create averages of sales data, B) Write scripting for order form.
Based on the above, what are some related concepts (per topic)?
JavaScript and jQuery Review
Review: Locating an object
- In both JS and jQuery, before manipulating an object you first have to "find"/target it.
- Javascript: You can locate/target any object through using a css selector with the document.querySelector() method. For instance, the examples below target the body, an object with an ID of "container", and the first object with a class of "thumbnail" (but not all thumbnails):
document.querySelector("body")
document.querySelector("#container")
document.querySelector(".thumbnail")
Reminder: In order to use jQuery you have to LOAD the jQuery library/code
- jQuery: In jQuery we can also "find" an object through css selectors, we just do it through the default $() method, or jQuery(). Like the Javascript examples, the code examples below target the body, #container and all .thumbnail objects.
$("body")
$("#container)
$(".thumbnail")
Review: Adding Event Triggers to objects
- Instead of executing code right away, you bind an event to an object (the users clicks on it, mouseovers, etc.), and then inside that event create a temporary, unnamed function with the code.
- Javascript: We add/bind events to objects with the addEventListener() method. The method is added to an object, and then inside the method is the function with the code to be executed. For examples:
document.querySelector("#box1").addEventListener("click", function(){
// code to be run when someone clicks on #box1
};
- jQuery: The on() command in jQuery acts just like addEventListener() in Javascript, allowing us to add an event to an object, and then have an (unnamed) function with code be run when that event occurs on the object.
$("#box1").on("click", function(){
// code to be executed when the user clicks on #box1
});
Review: "this" object
- this can be used inside an event-triggered code to reference/represent the object that was triggered (that user clicked, moused, etc.).
- Javascript: Use this inside a function inside an addEventListener() block. For instance:
document.querySelector("#text1").addEventListener("change", function(){
alert("You changed the value of the textbox to " + this.value);
});
- jQuery: Operates the same, as a reference to the triggered object inside an on() event block. The main distinction is that since jQuery binds will often cover a series of objects, it represents just the one triggered. So for instance, in the example below the bind applies to all anchor tags (a), but when triggered this only represents the exact one triggered.
$("a").on("click", function(){
alert("You just clicked a link and are going to " + this.attr("href"));
});
Editing properties of objects
- You can edit the html (tag) attributes of objects, the css/style properties of objects, and the html contents of divs... through Javascript and jQuery.
Note: Only 'official' html tag attributes are accessible directly off a JS object reference. If you want to access attributes that are made up (such as a caption attribute for photos), you use the .getAttribute() method... which can access any attribute of a tag, whether it is an official/OKed attribute or not.
- JavaScript: Offical html properties of objects are directly off the object, such as obj.src. Style properties are under a sub-object named .style, and the html content of a div/container is represented by .innerHTML.
document.querySelector("#pic1").src="dent.jpg";
document.querySelector("body").style.color="red";
document.querySelector("#box1").innerHTML = "This is the new div content.";
Note: attr() or css() with only one argument is used to "read" the value, and with two is used to "set" the value.
- jQuery: The attr() method accesses html object attributes and the css() method reads/sets css/style attributes. And the html() method sets the html content of a container/div.
$("#pic1").attr("src", "dent.jpg");
$("body").css("color", "red");
$("#box1").html("This is the new div content.");
- Style properties names in Javascript: Javascript does not allow/support object names with dashes/hyphens in them, so common css/style properties such as background-color would not be valid. So all multi-word style properties have alternative names in JS. You basically remove each dash and Upper Cap each subsequent word ("camel"-case).
- So some common Javascript versions of CSS properties are:
- color
- fontSize
- fontFamily
- fontWeight
- fontStyle
- textTransform
- textAlign
- textIndent
- lineHeight
- backgroundColor
- backgroundImage
- visibility
- left
- top
- zIndex
Variables, named functions, conditional logic
Variables can be created exactly the same in Javascript and jQuery. And once you "load" jQuery into a page you can alternate/switch between JS and jQ on different lines if you choose (but do NOT put object-specific regular Javascript and jQuery in the same line).
Similarly, you set up functions exactly the same in Javascript vs jQuery. Remember, jQuery is written in Javascript. And you can mix JS and jQ in different lines of a function.
And finally, like variables and naming functions, there is no special jQuery version of conditional logic. You use the same syntax to set up "conditions" regardless of whether you will have Javascript, jQuery or both inside of the logic branch.
Additional examples of JS versus jQ:
- Read the css "background-color" property in Javascript: let bg = document.querySelector("#instructions").style.backgroundColor
- Set the css "background-color" of #instructions to yellow in Javascript: document.querySelector('#instructions').style.backgroundColor = 'yellow'
- Read the css "background-color" property in jQuery: let lh = $('#instructions").css("background-color")
- Set the css "background-color" of #instructions to yellow in jQuery: $('#instructions").css("background-color", 'yellow')
JavaScript and jQuery Concept Reference and Study Guide
Fundamental Javascript Concepts:
- Styles: CSS Properties define aspects of objects. When writing in HTML, use style blocks and property names are like "background-color" with declarations such as "width: 200px". When manipulating in JS, property names are like "backgroundColor" and declarations such as "width='200px'". When manipulating with jQuery use .css(). You should already be familiar with CSS and HTML. For the JS and jQuery you can review Editing style properties and the CSS block in Query review and JS
- Objects: Generally created with HTML tags. Often have UNIQUE "id" properties. If you can "locate" an object with Javascript, you can then read a property, write/change a property, or otherwise manipulate it. See Intro to programming and JS
- Variables: Can store (read and write) data such as strings, numbers, objects, functions.
let favcolor = "red";
let favnumber = 77;
let img2 = document.querySelector('#image2');
- Methods: Functionality or "mini-programs" already built into the language. Call/activate them by name. ALWAYS call with parenthesis. Sometimes call "off" an object.
- Functions: "Mini-programs" written by YOU that are called/run by name. Can set up with arguments (so that data is passed INTO them when called). Always define AND call them with parentheses.
// Simple function with NO parameters that ALWAYS changes page to red
let go_red = function(){
document.querySelector("body").style.backgroundColor = 'red';
}
// call/activate with
go_red();
// Function with ONE parameter, color to change page to
function change_bg (newcolor){
document.querySelector("body").style.backgroundColor = newcolor;
}
// call/activate with
change_bg('teal');
// Function with TWO parameters, ID of image to change and new src
function change_image (imageID, newSRC){
document.querySelector("#" + imageID).src = newSRC;
}
// call/activate with
change_image('image2', 'image3.jpg');
- "if" and conditional logic: Write a condition/expression that if "true" the following set of code is run. Can have else if and else clauses.
if(favcolor == "red") {
alert('i like the color red too!');
}
if(document.querySelector('#emailbox').value.indexOf('usc.edu') != -1) {
alert('Go Trojans!');
}
if(your_age >= 18) {
alert('You can vote in the U.S.!');
}
- Arrays: More complex type of variable that can store multiple rows of data (rather than just one piece). Created by a command such as "var favcolors = new Array".
// Simple/single array
let favcolors = new Array();
favcolors[0] = "red";
favcolors[1] = "pink";
favcolors[2] = "yellow";
favcolors[3] = "purple";
favcolors[4] = "teal";
// also / or
let favcolors = [];
favcolors.push("red");
favcolors.push("pink");
favcolors.push("yellow");
favcolors.push("purple");
favcolors.push("teal");
also
let favcolors = ["red", "pink", "yellow", "purple", "teal"];
// Parallel arrays
let imagepath = new Array; let imagedescr = new Array;
imagepath[0] = "sign1.jpg" imagedesc[0] = "stop sign";
imagepath[1] = "sign2.jpg" imagedesc[1] = "caution sign";
imagepath[2] = "sign3.jpg" imagedesc[2] = "yield sign";
imagepath[3] = "sign4.jpg" imagedesc[3] = "speed limit sign";
- Dynamic Documents: Populating containers (divs, body) with new content by new innertHTML (in JS) or using the html() method (in jQuery).
// Javascript innertHTML property of containers
<div id="box1"></div>
<script>
document.querySelector('#box1').innerHTML = 'new content for div';
</script>
// jQuery html() function
$('#box1').html('new content for div');
- "for" and Conditional Loops: Loop/repeat a set of code based on defined conditions.
//simple for loop with alert
for(let i=0;i<9;i++){
alert('Current number is ' + i);
}
- Data Validation: Use methods such as indexOf() to determine if data matches desired content and/or formats.
See indexOf, data validation.
- Data Transformation: Use methods such as charAt(), substring(), and replace() and regular expressions to modify data into different formats or content. See portions of Loops, charAt, substring, replace.
- Array loops: Building code that "loops" around the data of an array, such as to build dynamic page content. (sample code)
let newhtml = "";
for(let i=0;i<dogimages.length;i++){
newhtml += "<img src='" + dogimages[i] + "'> ";
}
document.querySelector("#content").innerHTML += newhtml;
- Searching through arrays: Using if clauses inside a for loop, parse through array data to find/match desired information.
Fundamental jQuery Concepts:
- Load library and starter/ready block
<script src="http://code.jquery.com/jquery.js"></script>
<script>
$(document).ready(function(){
});
</script>
- Targeting objects through selectors
- (document), (this) and (window) objects
- Using on() to delay code based on an event/action on an object
$('#button2').on("click", function(){
// do something when button is clicked
});
- Basic jQ object methods like show and hide, toggle, fadeIn and fadeOut, slideDown and slideUp, etc. And using delay() to "pause" between those simple object animations.
- Altering objects with jQ methods like html(), css() and attr()
$('#image2').attr("src". "image3.jpg");
$('body').css('background-color', 'red');
$('#box2').html('new div content');
- Chaining multiple commands off one object.
- Using Javascript structural commands (if statements, for loops, variables, arrays and functions) inside jQuery.
Review of Functionality you should be familiar with (in Javascript and jQuery):
- Detect user interaction (with objects)
<input type="button" id="button1">
in Javascript
document.querySelector("#button1").addEventListener("click", function(){
// JS to execute when user clicks on #button1
})
in jQuery
$("#button1").on("click", function(){
// jQuery to run when user clicks on #button1
});
- Manipulate objects through their html/tag attributes and style properties (sample code)
Javascript
document.querySelector('#image1').src = 'image2.jpg';
document.querySelector("body").style.backgroundColor='red';
document.querySelector('#box2').style.width = '200px';
jQuery
$("#image1").attr("src", "image2.jpg");
$("body").css("background-color", "red");
$("#box2".css("width", "200pox");
- Store data/objects in variables
Javascript
let favcolor = "red";
let favnumber = 77;
let img2 = document.querySelector('#image2');
jQuery
let favcolor = "red";
let favnumber = 77;
let img2 = $("#image2");
- Store data in arrays/parallel arrays and randomly pick out information, Use/output all data, and/or Match and extract one set of data
- Use data to dynamically create items on a page or edit objects
- Create a "workflow" of events on a page
- Through logic have a page operate or react differently based on user interaction and/or data
- Validate and/or change user data
Material NOT on the exam: You will not be responsible on the exam for:
- animate(): The jQuery animate() command
- Prop-value maps: Concepts and syntax of creating "property": "value" maps of data.
- Scripting media: jQ or Javascript media commands and properties
- Syncronizing elements: Complex object sequences.
Javascript Review Guide (by former class assistant Anupam):
jQuery Review Guide (by former class assistant Anupam):
Handy Student Review Guide (by former class assistant Hal Pan):