Links


BOOKMARKS


101/Misc

Scripts can be placed in the body and/or or in the head section of HTML.
Often you will see scripts at the bottom of the body section of a web page. This can reduce display time.
Separating HTML and JavaScript, by putting all the code in one place, is always a good habit.

You can put functions in the header and call to those functions from the body.

You can call to a function earlier on the HTML page than the where the function script is located.

JavaScript counts months from 0 to 11. January is 0. December is 11.

toDateString() displays a date "normally

<script>
var d = new Date();
document.getElementById("demo10").innerHTML = d.toDateString();
</script>

External Scripts

<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>

The Script tag can not be used in a .js file.

Debugging

Use console.log to help test with the browser's console.
The script, below, will show "11" in the console.

<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>

Escape characters

\' single quote

\" double quote

\\ backslash

\n new line

\r carriage return

\t tab

\b backspace

\f form feed


Ending statements with semicolon is optional in JavaScript.

JavaScript ignores extra spaces. You can add white space to your script to make it more readable.

Literals

Numbers

See also: http://www.w3schools.com/jsref/jsref_obj_number.asp

...can be written with or without decimals, and with or without scientific notation (e)

JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.
var x = 0xFF; // x will be 255

Never write a number with a leading zero (like 07).

NaN is javascript's return value for not a number.
BUT....typeof NaN; // returns "number"

 

var x = 123;
var y = new Number(123);
(x === y) // is false because x is a number and y is an object.

 


The toFixed() method rounds a number to a given number of digits.

For working with money, toFixed(2) is perfect.

<p id="demo9"></p>

<script>
var x = 9.656;
document.getElementById("demo9").innerHTML =
x.toFixed(0) + "<br>" +
x.toFixed(2) + "<br>" +
x.toFixed(4) + "<br>" +
x.toFixed(6);
</script>

Number(), can be used to convert JavaScript variables to numbers:
x = "10"
Number(x); // returns 10

 

Math.random() returns a random number betwween 0 and 1

Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments:
Math.min(0, 150, 30, 20, -8); // returns -8

Math.round() rounds a number to the nearest integer

See also: http://www.w3schools.com/jsref/jsref_obj_math.asp



Strings

...can be written with double or single quotes.

Expression literals

<p id="demo4"></p>

<script>
document.getElementById("demo4").innerHTML = 5 * 10;
</script>

The script, above, writes....

Arrays

...are written like [40, 100, 1, 5, 25, 10]

Object literals

{name:"Washu", breed:"Labrador", age:9}

Operators

= is used to assign values, + is used to add values, ++ is used to increment values.
% is for division remainder
-- is for decrease

Assignment Operators

For the examples below, x = 10 and y = 5

x = y (10 = 5) returns 5

x += y (10 + 5) returns 15

x -= y (10 - 5) returns 3

x *= y (10 * 5) returns 50

x /= y (10 / 5) returns 2

Variables

See also: Functions

The var keyword to define variables, and an equal sign to assign values to variables.

<p id="demo5"></p>

<script>
var length;
length = 6;
document.getElementById("demo5").innerHTML = length;
</script>

The script, shown above, writes....."


Some variable examples

var length = 16; = Number assigned by a number literal
var points = x * 10; = Number assigned by an expression literal
var Name = "Kelvin"; = String assigned by a string literal
var dogs = ["labrador", "GSD", "husky"]; = Array assigned by an array literal
var dog = {Name:"Washu", breed:"labrador"}; = Object assigned by an object literal


Misc variable info

= is assignment; while == or === actually means "equal."

It's a good programming practice to declare all variables at the beginning of a script.

Many variables can be declared in one statement
var lastName = "Doe", age = 30, job = "carpenter";

Variable without a value are undefined. The value might be something that has to be calculated, or something that will be provided later, like user input.

Variable can be dynamic & change in the script.
var x; // Now x is undefined
var x = 5; // Now x is a Number
var x = "Washu"; // Now x is a string

Quotes inside a string just can't be the same as the quotes defining the string
var answer = 'The dog is called "Washu"';

Empty a variable by setting it to null
var dog = null;

When a JavaScript variable is declared with the keyword "new", the variable is created as an object
Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed.

Arrays

JavaScript arrays are used to store multiple values in a single variable. An array can hold many values under a single name, and you can access the values by referring to an index number. Array indexes start with 0.

Syntax
var array-name = [item1, item2, ...];

One Array can hold various types of objects such as a funcation and a variable.

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;

var x = dogs.length; // The length property returns the number of elements in cars
var y = dogs.sort(); // The sort() method sort cars in alphabetical order

Objects

Properties are values associated with objects.

Methods are actions objects can perform.
Object methods are functions defined as object properties.

Objects are varibles with properties & methods.
Properties can be accessed in two ways.
dog.firstName;
dog["firstName"];

<p id="demo7"></p>

<script>
var dog = { firstName : "Washu",
breed : "Labrador",
age : 10,
Color : "black"
};

document.getElementById("demo7").innerHTML =
dog.firstName + " is " + dog.age + " years old.";
</script>

Functions

See also: Variables

functionName(parameter1, parameter2, parameter3) {
code to be executed
}

Function parameters are the names listed in the function definition.

Function arguments are the real values received by the function when it is invoked.

Inside the function, the arguments are used as local variables.

Variables declared within a JavaScript function, become LOCAL to the function.
Local variables have local scope: They can only be accessed within the function.
Local variables are created when a function starts, and deleted when the function is completed.

A variable declared outside a function, becomes GLOBAL.
A global variable has global scope: All scripts and functions on a web page can access it.

EXCEPTION: Variables with values are automatically global even when they are inside a function.

Misc Samples

Swap image back and forth when clicked

<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("washu")) {
image.src = "css/faye.png";
} else {
image.src = "css/washu.png";
}
}
</script>

Change style (or any HTML attribute) onClick

This will change

<script>
function myFunction() {
var x = document.getElementById("demo2");
x.style.fontSize = "25px";
x.style.color = "red";
} </script>
<button type="button" onclick="myFunction()">Click Me!</button>

Return typeof variable

<button onclick="myFunction3()">Try it</button>

<p id="demo3"></p>

<script>
function myFunction3() {
document.getElementById("demo3").innerHTML =
typeof "name" + "<br>" +
typeof 3.14 + "<br>" +
typeof false + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof {name:'washu', age:10};
}
</script>

Replace String

Replace "Dog" with "Washu" in the paragraph below:

Dog is awesome!

<button onclick="myFunction8()">Try it</button>

<p id="demo8">Dog is awesome!</p>

<script>
function myFunction8() {
var str = document.getElementById("demo8").innerHTML;
var txt = str.replace("Dog","Washu");
document.getElementById("demo8").innerHTML = txt;
}
</script>

Loop Through array to create list

<button onclick="myFunction11()">Try it</button>

<p id="demo11"></p>

<script>
function myFunction11() {
var index;
var text = "<ul>";
var dog = ["Labrador", "German Shepherd", "Husky", "Border Collie"];
for (index = 0; index < dog.length; index++) {
text += "<li>" + dog[index] + "</li>";
}
text += "</ul>";
document.getElementById("demo11").innerHTML = text;
}
</script>