The Demonstration has been expanded upon from the example to have the button toggle between the different messages rather than just changing from the
original message to the second message.
Added the changing styles button that combines the Change HTML and Change Style lessons.
JavaScript from the Dawn of the Web
JavaScript was a programming and scripting language developed 20 years ago by Brendan Eich who never would have thought it would become what it has
today.
JavaScript
Mentioned as the de-facto standard assembly of the web.
Used not only in browsers and the front end of web applications but also heavily on the server side for web application programming interfaces
like node.js.
Most commonly thought of as the most popular programming language in existence.
An essential for any programmer or web developer to learn.
JavaScript and Java are completely different languages, both in concept and design and JavaScript has nothing to do with Java.
A heavy programming language requiring the installation of additional software on the system.
The makers of JavaScript latched on to the free publicity and buzz that Java was getting in 1995.
JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
ECMA-262 is the official name. ECMAScript6 (released in June 2015) is the latest official version of JavaScript.
JavaScript functions primarily within a host environment like a web browser although others such as Adobe PhotoShop, Adobe Acrobat, and NoSQL
databases are fairly popular as well.
JavaScript is primarily used as a client-side scripting language.
Means that most of the coding is written directly into the HTML page and parsed by the browser when the page is rendered on the
client.
Primary function is to add to the level of interactivity on a what would otherwise have been a static page.
JavaScript is included in everyone's browser but you still must program the actions that you want to occur on the page and when you want them to
occur.
At page load
When a user clicks a Submit button
When a user focuses on a particular field or away from that field
When a user starts to type
After a certain period of time
A basic JavaScript program is simply a line of JavaScript code that is included directly in the HTML file that will execute when the page is loaded.
JavaScript does not have any built-in print or display functions but there are various ways that it can "display" information.
Realize that these display options are often for developers and not end users
JavaScript is written in plain text just like HTML and CSS but does follow a very specific syntax which developers must learn.
JavaScript is not a complied language but an interpreted language meaning you write the code and hand it over to the web browser and it takes care of
everything.
so no special complier is necessary.
Simple text files and a browser that has JavaScript enabled is all we need.
One of the MOST IMPORTANT things to remember about JavaScript is that it IS CASE SENSITIVE!!!!
So everything that you do in JavaScript is case SENSITIVE
Variables
Functions
Methods
Objects
If you don't get the case right you won't see any errors, your JavaScript code will simply not work.
Syntax
A set of rules defining the way in which JavaScript programs are constructed.
A computer program is simply a list of instructions to be executed.
In JavaScript these are executed by the web browser.
These individual instructions are referred to as statements.
Statements are separated by semicolons.
Statements are composed of multiple elements
Values
Operators
Expressions
Keywords
Comments
Two types of values exists in JavaScript statements
Literals - fixed values
Numbers - written with or without decimal points and without quotes.
1001
10.50
Strings - written within single or double quotes
"This is a string"
'This is also a string'
"55"
Variables - often used to store data
Keyword var is used to define the variable
The = sign is used to assign a value
Operators
Used to assign values to Variables
Assignment operators
=
Used to compute values
Arithmetic operators
+ - * /
Used to evaluate values
Comparison operators
==, !=, <, >
Expressions
A combination of values, variables, and operators, which computes to a value.
The computation is referred ot as an evaluation.
Expressions can also contain variables.
Keywords
Used to identify various actions to perform
Var - defines a variable
For - marks a block of code to be executed so long as a condition is true
If...else - marks a block of code to be executed based on a condition
Return - exits a function
Break - terminates a switch or a loop
Function - declares a function
None of these keywords will be allowed to be the name of a variable, object, or function that you create and
ALL are case-sensitive!
Comments
Can be added to any code within a JavaScript program in order to assist with readability and debugging
Single lines are commented using //
Multiple lines are commented using /* these are some comments */
The semicolon is the separator of JavaScript statements and most programs will include multiple lines of statements.
The semicolon is the important part
It can often be omitted but it should never be just in case
White space doesn't matter in JavaScript just like HTML and css
Add whitespace to improve readability
Break long code statements over multiple lines at an operator whenever possible.
N/A
Just information
Understanding Variables
In any programming language you will frequently need to hold information for later use and that is where the variable comes in.
Variables can be defined in order to carve out a little spot of memory in order to do two things
Hold contents for later retrieval.
Create a unique name with which the information can be identified.
Could be all types of information
Information a user inputs to a form
Value of an HTML element
Numbers, strings, and Boolean values
In some cases we might declare a variable without a value and the variable would be undefined.
At a later time, even the next line of code, we would then define the value which can be of multiple types
Numbers - defined using an assignment operator and without using quotes.
Strings - defined using an assignment operators and with quotes
Boolean - defined using the true or false keywords.
While other programming languages require you to define the type of the variable along with its value JavaScript does not because it is what is
called a "loosely typed" language.
Sometimes variables will need to contain multiple values simultaneously which is referred to as an array.
Arrays are simply variables that hold multiple values with no theoretical limit to the number of values they can contain
You can request a specific value for display or modification using the index
multiValues[2] = displays the value in the 3rd spot of the array because of the zero based index used in numbering the items in the array.
multiValue[6] = "another string of text" - would set the value to item 6 or create it if it didn't exist.
Arrays are everywhere in JavaScript!
The real strength of JavaScript arrays comes in their various properties and methods
Properties define information about an array such as the Length property.
Methods define executable code and functionality that belong to the array or object
Reverse()
Join()
Sort()
N/A
Just information
Working with Operators
When working with variables we invariably work with operators as well
Operators are used to perform some task and come in various forms
+ - * /
Add, subtract, multiply, divide
% - called the modulus and used to get a remainder
22 % 4 - would result in the answer 2
Increment Numbers
++
Decrement Numbers
--
Assignment operators include more than just the =
+=
-=
*=
/=
The + operator when dealing with strings performs a process called concatenation which simply combines multiple values.
Other operators are used to compare the values of variables and are used with conditional Expressions
Equality operators
== (equals)
=== (strictly equals)
!= (not equal)
!== (not equal value or not equal type
Conditional operators are used to compare values and are prinaryly used in loops within JavaScript which only take an action based on a certain
condition.
<
>
<=
>=
ANother way that you can cut down code from multiple if statements is to use a ternary operator
Very quickly when working with programming you realize that there is code that you want to be repeated.
Its more efficient to tell the browser to repeat something by typing it once then to have to retype countless times.
Looping isn't the difficult part
Fore every link in the page { // do this code }
For every field in a form on the page { // do this code }
200 times { // do this code }
Instead the difficulty is when to stop.
The Do...While loop is a variant of the while loop with one major difference.
It will always execute the code block at least once.
The first check to determine whether the condition is true or not comes after this initial execution.
The For loop is probably the most common type of loop to implement in large part because of the limited amount of code required for the loop.
Regardless of the type of loop there are common parts
Set up the index
Check the condition
Increment the condition
Normally a loop will continue until the condition of the loop no longer evaluates to True but there are two exceptions using JavaScript keywords
Break
A special word that jumps us out of the loop for good.
Not used as often with For and While loops.
Continue
A special word that jumps back to the top of the loop.
So it stops that particular iteration but not the loop as a whole.
Working with Loops
This is text that will be replaced by the computation result.
Just information
Creating Functions
There are times in JavaScript as in other programming languages that you would like to bundle a set of code so that it is reusable and functions
provide this capability.
Creating functions has many advantages
Refer to reusable code using a user friendly name
Easily accept and process input parameters
Quickly add functionality to your website through the use of libraries.
A function is simply a block of code designed to perform a particular task.
A function is declared
Something ont he page "calls" the function
Two basic types of functions exist
Anonymous functions
Named functions
Both of these are created using the JavaScript keyword function
Function syntax
Defined by the keyword function followed by a name and () or just ()
Names can consist of
Letters
Numbers
Underscores
$ signs
Parameters
Names listed in the function definition between the ()
Arguments
Real values received by the function when it is invoked
Behave as local variables inside the function
The code inside a function will execute when something invokes (calls) the function
An event occurs - a user clicks a button
It is invoked or called within JavaScript code
Automatically (self-invoked)
The return keyword defines the value that is "returned" back to the caller causing the function to stop
Best practice is to define the function in the code before the function is called
Functions should be defined early in the JavaScript file
Functions are then called later in the file
Functions can be defined globally or nested within other functions.
N/A
Just information
>
Understanding Types and Objects
Most programming languages require you to declare variables using a particular type which tells the programming engine what data type to expect
JavaScript is different in that it is a "loosely typed" language and doesn't care the type of object its dealing with in most cases
The general types
Numbers
Strings
Dates
Objects
Numbers in JavaScript o not have the intricacies that are present in other languages such as decimal, integer, large integer, floating point, etc.
All numbers in JavaScript are assumed to be floating point integers which would cause a problem but since massive numeric calculations aren't
usually performed in client-side code its not an issue.
If you surround numbers in quotes they will no longer be treated like a number but instead will be assumed to be a string
This could possibly cause an error in your code and so you can declare a value to be a number using the syntax
var foo = "55";
var myNumber = number(foo);
In addition to explicitly typing a variable you can use the built in JavaScript function NaN (Is Not a Number) in order to test the value of a
variable.
You can write an else statement if you actually want to check and verify that something IS a number.
The Math object in JavaScript can perform some very useful operations for developers using JavaScript
Strings are used for storing and manipulating text and the text can be inside single quotes or double quotes but not both
Can't start with single quotes and end with double quotes.
Can't use the same quotes more than once inside a string
Can use quotes inside a string as long as they are not the same as the outside quotes.
When you have a situation where you need to include special characters (like quotes) inside of a string value you have two options
Change the quotes i.e. single quotes inside of double quotes.
Escape the special characters using the \ character.
String properties
Length - the primary property that you will use which simply returns the length of the string.
The Date object allows you to work with Dates
Years
Months
Days
Hours
Minutes
Seconds
Milliseconds
Can be written as a string "Tue Dec 15 15:32:52 GMT-0500 (EST)
Can be written as a number 1450211572636
String Methods
charAt()
Match()
Replace()
Search()
Slice()
toLowerCase()
Trim()
toUpperCase()
Initiating a date can happen in different ways
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
By default creates a new date object with the current date and time but using other mechanisms you can choose a specified date and time
Once the date object is created there are various methods that allow you to operate on it.
Get and set the year, month, dat, hour, etc.
Display the date in different formats
Methods include
getDate() - get the day as a number
getDay() - get the weekday as a number
getFullYear() - get the four digit year
getHours() - get the hour
getMinutes() = get the minutes
Objects in JavaScript are everywhere, if you understand objects then you understand JavaScript.
Objects have properties (attributes) and methods (actions).
Consider a real life object like a pizza
All pizza objects have properties.
Toppings
Crust
Size
They have methods associated with them as well
Freeze
Cook
Prepare
Objects in JavaScript are the same in that they will all contain the same properties and methods but with differing values.
Consider an object called Person
Properties
firstName
lastName
fullName
DOB
Methods
Function definitions
Nearly everything in JavaScript can be an object: Booleans, Numbers, Strings, Dates, Maths, Regular expressions, Arrays, Functions, Objects
Basically everything except for primitive values are objects but even those can be created as objects.
Objects are simply variables containing variables
Variables can only contain a single value
Objects can contain multiple values in name:value pairs
The name:value pairs are referred to as properties
Methods are actions that can be performed on objects
An object property that contains a function definition
You can create JavaScript objects in various ways
Define and create a single object using an object literal
Define and create a single object using the keyword new
Define an object constructor and then create objects of the constructed type
Creating a single object using an object literal is the easiest way to create a JavaScript object.
You both define and create the object in a single statement
Uses a list of name:value pairs inside {}
The 2nd option is to use the NEW keyword to create an object though this is deemed unnecessary
The previous methods for creating objects are limited to creating a single object
There are times when you would like to create an object "type" that can then be reused to create multiple objects of a single type
The way to achieve this is to use the 3rd option of creating objects by using an object constructor function
The properties are the most important parts of an object
They are the values associated with an object
A collection of unordered properties
Can usually be added, changed, and deleted though some are read-only
Syntax
objectName.property - person.firstName
objectName["property"] - person["firstName"]
Object methods are actions that can be performed on objects
Essentially methods are properties that contain a function definition
You create object methods using this syntax
MethodName:function() {executable code}
You then access the method using this syntax
objectName.methodName()
Every JavaScript object has a prototype and the prototype is also an object
New objects inherit their properties and methods from their prototype
Objects created using an object literal or with new Object() inherit from the Object.prototype
Objects created from a particular object like new Date() would inherit from the Date prototype
You can create object prototypes to then use in creating additional objects and you do so using an object constructor function
You can add properties or methods
To existing objects
To all existing objects of a specific type
To an object prototype
Adding to objects only changes the object in question but adding to the prototype will modify new objects created using that prototype
Introduction to the HTML Document Object Model (DOM)
The JavaScript code that we write does not operate in a vacuum but instead it is attached to HTML web pages.
The web page is the script upon which we are working so we must be able to reach into the page to get information and have the page respond back to
our code.
Understanding the DOM is the way to do that, it is an incredibly important part of understanding the functionality of JavaScript.
What exactly is the DOM?
Its not a language
Its not a part of JavaScript
It's a fairly vague term
The web definition is "The Document Object Model is an application programming interface that defines logical structure of well-formed an XML and
HTML documents"
Taking apart the statement DOM will help to understand
Document - is the web page itself
Object - refers to the objects that are created based on the HTML structure
Model - a consistent way to approach the various objects
So the HTML DOM is a standard object model and programming interface for HTML which defines
HTML elements as objects
The properties of all HTML elements
The methods to access all HTML elements
The events for all HTML elements
The HTML DOM is a standard for how to get, change, add, or delete HTML elements
DOM methods are actions that you can perform on HTML elements
DOM properties are values that you can set or change
All HTML elements are defined as objects and accessible through JavaScript
A property is a value that you can retrieve or modify
Changing the content of an HTML element
A method is an action that you do
Adding an HTML element
Deleting an HTML element
N/A
Just information
Accessing DOM Elements
There are multiple ways of finding and accessing DOM elements which is the first step to dealing with the HTML DOM
If you want to manipulate the HTML elements you must first locate them
The key is understanding "where" in the DOM is the item that you wish to grab hold of as well as the critical question "Is it unique?"
Options
Find HTML elements by ID = document.getElementById
Find HTML elements by tag name - document.getElementByTagName
Find HTML elements by class - document.getElementByClassName
Find HTML elements by CSS selectors - document.querySelectorAll
Once you have the element you can access individual attributes using the getAttribute() method
This method will allow you to access the attributes for anu element on the page
N/A
Just information
>
Changing DOM Elements
Accessing DOM elements is the first step but often we would like to modify those elements either entirely or in part, such as attributes
One such way of changing elements is to modify the content which is performed using the innerHTML property
Another option is to modify attributes
Another way in which the HTML can be changed is to actually modify the style that is used using CSS properties
Any CSS styles can be modified on page load or based on events on the page
The key is to use the CSS property names without the (-) character
Font-family becomes fontFamily
Border-style becomes borderStyle
Background-color becomes backgroundColor
Using setAttribute("style", "color:blue"); would also be supported and can use the (-)
N/A
Just information
>
Creating DOM Elements
Although the innerHTML property can be used to add content to a page its not the cleanest method available with plenty of chance for error
Instead you can create elements within the DOM and once created add a text node to those elements
This results in a more precise and better way of modifying page content which always involves two steps
Create the element
Add the element to the right place in the document
The next step is either
Access the innerHTML property pf the element we just created to add content
Create a new text node and attach to the element (more precise)
Thus far our code has been loaded along with the web page which is really not very useful
JavaScript is supposed to control the behavior of the page and its interactivity with the user which means that our code should be able to respond to actions that are taken on the page
This is where events and event listeners come into play
You don't cause the events they are occurring all the time.
You choose which of these events that you want to respond to
You write an event listener in order to handle those particular events and respond the way that you would like
Three ways to react to events
Write the JavaScript code directly into the HTML
Specify the element and event you want to handle and write a function
Use the addEventListener() function
The first option is a simple option and is often done but really not recommended
It mixes the HTML code and the JavaScript
Its not very portable
Generally not a good idea
The 2nd option is often the best and involves identifying the element that you want to act upon and the event that
you would like to respond to
The element is referenced by using a variable
The event is chose from the list of possible events
An anonymous function is created that contains the code that you want to run
The 3rd option used the addEventListener() method
Parameters
The event you want to respond to minus the word on
The function that you want to call
True or False
There are many events that you can respond to
Onclick
Onload
Onunload
Onchange
Onmouseover
Onmouseout
Onmouseup
Onmousedown
Onfocus
Onblur
There are times when we would like behavior on a page automatically controlled based on time lapse
Though not technically events they are very similar in their function
Two built in functions will provide this capability quite easily in JavaScript
JavaScript libraries are collections of code that you can use in order to gain access to additional functionality or just to achieve results
more quickly and easily.
Libraries have been developed over time by advanced JavaScript programmers and the vast majority are freely available and considered open source
The use of libraries can really save a lot of time and effort
Several popular libraries exist and you don't have to make a single choice though jQuery is by far the most common
jQuery
Used by many of the largest companies in the World
USes CSS selectors to manipulate DOM objects on the page
Provides a companion UI framework and numerous other plug-ins
prototype
Provides a simple API to perform common web tasks
Enhances JavaScript by providing classes and inheritance
MooTools
A framework offering an API to make common JavaScript programming easier
Includes lightweight effects and some animations
In order to use these libraries you must add them to your page in the <script> tags either in the <head> or
<body> section of the document
Src attribute tells where to get the file
Added just like any other external script
Can be stored locally
Can be obtained using a Content Delivery Network (CDN)
Content Delivery Networks
If many organizations are using the same libraries it makes sense to place them in a common location that everyone can access
Helps to keep the size of pages small and the load times at a minimum
Essentially a network of servers that contain shared code libraries
Google provides a free CDN for a number of JavaScript libraries
N/A
Just information
Installing and Using jQuery
jQuery is just one of many libraries in use but it is the most popular library which helps assist developers
A lightweight "write less do more" library designed to make it much easier to include JavaScript on your website
Takes many common tasks which require lines and lines of code and wraps them in methods you can call with a single line of code
Simplified many complicated tasks in JavaScript
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
To begin using jQuery you either download it locally or use a CDN
Local jQuery files are preferred on production websites for speed and reliability
CDN is perfect for development, testing, and learning
jQuery Syntax
The syntax is tailored for selecting HTML elements and then performing actions on those elements $(selector).action()
A common problem when programming JavaScript has to do with scripts running before the page is loaded which sometimes prevents the scripts from
gaining access to HTML elements on the page
jQuery has a function called ready() that is designed to take care of that in that it waits for the page to be ready (all HTML elements loaded)
Essentially you would just place the code inside the ready function
Using a do...while loop to continue to get test scores until a user enters a sentinel value, then calculates the average score
Changed the original code to display all the numbers entered for review.