User:Qebafhzn/Javascript Studies

Syntax
Putting Javascript into an html file: code

Creating text: document.write ("String")

Putting JavaScript into the head section calls the script before the page loads, in the body after the page loads.

Creating variables (CASE SENSITIVE) : var variable_name = value

Variables within a function are different from function to function, but variables outside a function are global. You can also put functions in the variable, most functions need or create values.

Returning variables: return variable

Creating multi-condition script:

if (condition) { function } else { function }

If the condition is true, the first function will be executed. If false, the other function will be executed.

Creating multi-block switch script:

switch (variable) { case value: function break case other_value: function break case yet_another_value: function break case default: function }

Value is the value of the variable stated, default is if the value is not one of the values listed in the cases.

Popup boxes:

alert ("Text in alert")

An alert just tells you information.

confirm ("Text for confirmation")

A confirmation returns true or false depending on what you clicked.

prompt ("Text to prompt";"Default text in prompt box")

A prompt returns string depending on what you typed.

To create functions:

function function_name (var1;var2...) { code with variables }

Custom functions just allow you to squeeze lots of code into one line. When you use the function, the value of the variable is stored in the code block.

Loops repeat a script for a designated amount of time or condition.

"For" loops loop the script for a designated number of times.

for (i=0;i<=10;i++) { script }

This repeats the script provided that variable i is less than or equal to 10. i starts at 0, and each repetition through the script increases i by 1. However, you have first designate i before the loop. You can use i inside of the loop. If you replace "script" with document.write(i), it will show 0 1 2 3 4 5 6 7 8 9 10, so that each loop generates a different text.

"While" loops are the very same thing, except you only include the middle statement that was included in the "for" segment, and the other segments are designated outside the loop.

Breaking a loop is jargon for stopping the loop. For example, if you want to loop through a script until i is 10, but you want to stop it before i is 3, write this:

while (i<=10) { if (i==3) { break } script }

You can also continue the loop. Continuing the loop breaks the loop and starts again at the next value. Since the normal break statement stops a loop before the condition is true, continuing a loops skips over one of the values. For example:

while (1<=10) { if (1==3) { continue } script }

If "script" is replaced with document.write(i), it will write 0 1 2 4 5 6 7 8 9 10, since continuing skips over a number.

Events can be used as real-time boolean comparisons, such is onmouseover puts true when your mouse is on the object.

You can use try/catch statements to debug a script. Try looks for errors, and if it does, it puts a value into the variable err. the throw statement decides which variable to put in err. The catch statement displays a message if a variable has a value.

var x=12 try { if( x>10) throw "Err1"; else if(x<0) throw "Err2"; } catch(er) { if (er=="Err1") document.write("Error! The value is too high"); if (er == "Err2") document.write("Error! The value is too low"); }

This will write Error! The value is too high since x is over 10.

You can also write a onerror statement as an easier way to find errors. You have to designate a function to display all the errors, we'll call this handleErr. The onerror creates the variables msg, the error, url, the website with the error, and l, the line on which the error is located.

onerror=handleErr; var txt="";

function handleErr(msg,url,l) { txt="There was an error on this page.\n\n"; txt+="Error: " + msg + "\n"; txt+="URL: " + url + "\n"; txt+="Line: " + l + "\n\n"; txt+="Click OK to continue.\n\n"; alert(txt); return true; }

adddlert("Welcome guest!");

Objects
In Javascript, there are objects, which is the type of value a variable has. For example, we have string objects, math objects, date objects, etc. They have properties, which are values within a value, such as the length of a piece of string. (String as in text, not fibers.) Methods are actions that can be done to certain objects, such as making all the letters in a string to uppercase.

String
String is text.

Properties
constructor = The type of the object. length = The length in characters of the string.

Methods
anchor(anchortext) = Makes an anchor using anchortext. big = Makes the string big. blink = Makes the string blink. bold = Makes the string bold. charAt(#) = Returns the character that is in the #th position in the string. charCodeAt(#) = Same as above, except it returns the unicode. concat(str) = Combines the selected string with str. fixed = Makes the string fixed. fontcolor(color) = Makes the string into the color color. color can be in hex, rbg, or named. fontsize(#) = Makes the string into the size #. String.fromCharCode(unicode) = Makes a string out of unicode. Not a method of a variable, but a static method. indexOf(value,startingpoint) = Returns a value based on what character number the string "value" was found in the specified string. startingpoint determines at what position to start at. If the value is never found, -1 will show. italics = Makes the text italic. lastIndexOf(value,startingpoint) = Like indexOf, except it records the last occurrence of the value. startingpoint goes backwards. link(url) = Makes the text link to url. match(value) = If value is found in the string, it will display that string. If not, it will display null, or boolean false. replace(/oldstring/;"newstring") = Replaces oldstring with newstring. putting i after the slashed in oldstring causes it to be case insensitive. small = Makes the string small. strike = Strikes through the string. sub = Makes the string into subscript. substr(start;end) = Takes the characters from position "start" until position "end" and extracts them. sup = Makes string into superscript. toLowerCase = Makes the string into lowercase. toUpperCase = Makes the string into uppercase. toSource = Shows the source code of any object.

Date
Date is a time and/or date. To set a variable as a date, use var d = New Date.

Methods
Date = Returns todays date and time. No variable needed. getDate = Returns the day of the month. getDay = Returns the day of the week. getMonth = Returns the month of the year. getFullYear = Returns the year. getHours = Returns the hour of the day. getMinutes = Returns the minute of the hour. getSeconds = Returns the second of the minute. getMilliseconds = Returns the millisecond of the second. If you put UTC between the "get" and the unit of time, you will get the UTC equivalent. If you replace "get" with "set," you can change the date of the object. getTime = Returns the milliseconds since 1/1/1970, or the Unix Time. getTimezoneOffset = Returns the difference in minutes of the local time and the UTC. parse = Turns a string into a date and calculates Unix Time. toString = Turns a date into string. Putting UTC in between to and String turns a date's UTC equivalent into string. UTC = Returns the UTC equivalent of Unix Time.

Arrays
An array is a set of multiple values in a variable. To set up a variable as an array object, type var arr = New Array. Each array has an index starting from 0. To place a value in the first slot of an array, type arr[0] = String. To place a value in the second, type arr[1] = Integer. To access all the values in an array, type arr. To access the value in a certain index of an array, type arr[x].

Properties
length = The number of values in an array.

Methods
concat(arr) = Combines 2 or more arrays. join = Turns an array into a piece of string. pop = Removes the last value from an array. push(value) = Adds a value to the end of the array. reverse = Reverses the order of the values in the array. shift = Removes the first value from an array. slice(#1,#2) = Displays the values at index #1 until index #2. Does not affect array. sort(by) = Sorts an array alphabetically. To sort numerically, make a function "by," with the arguments a and b, and the code is return a-b. splice(index,howmany,values,...) = Removes "howmany" values starting at position "index," and replaces it with "values." To add instead of replace, put 0 for howmany. toString = Converts an array into string, each element separated by a comma. unshift(values,...) = Adds values to the beginning of an array.

Boolean
Boolean basically means yes/no, 1/0, on/off, etc. To convert something into boolean, type var b = New Boolean. Unstringed true is true, along with any positive integer, and any type of string, including "false." Unstringed false is false, along with unstringed null, NaN, and integers 0 and below. Comparisons make boolean values, which comes in handy when scripting.

Integers
Integers are numbers, from negative infinity to positive infinity and every number in between. Including decimals, such as 3.14159.

Properties
E = 2.718 PI = 3.1415926535

Methods
You have to have "Math." on nearly all of these.

abs(x) = Returns the absolute value of x. acos(x) = Returns the arccosine of x. asin(x) = Returns the arcsine of x. atan(x) = Retunrs the arctangent of x. atan2(x,y) = Returns the angle theta of x and y. ceil(x) = Returns x rounded up to the nearest integer. cos(x) = Returns the cosine of x. exp(x) = Returns ex. floor(x) = Returns x rounded down to the nearest integer. log(x) = Returns log base e of x. max(x,y,...z) = Returns the highest of the numbers. min(x,y,...z) = Returns the lowest of the numbers. pow(x,y) = Returns xy. random = Returns a random number between 0 and 1. sin(x) = Returns the sine of x. sqrt(x) = Returns the square root of x. tan(x) = Returns the tangent of x.

Operators
Assignment x=y Assigns value y to variable x. x+=y Adds value y to variable x. x-=y Subtracts value y from variable x. x*=y Multiplies variable x by value y. x/=y Divides variable x by value y.

x++ Adds 1 to variable x each time it is placed. x-- Subtracts 1 from variable x each time it is placed.

Comparison x==y Returns true if the two variables are equal. x!=y Returns true if the two variables are not equal. x>y Returns true if x is greater than y. x=y Returns true if x is greater than or equal to y. x<=y Returns true if x is less than or equal to y.

Logical (x&&y) Returns true if comparison x and comparison y are true. (x||y) Returns true if x or y are true. !(x) Returns true if x is false.

You can also use operators with string values.

Conditional X=(a)?y:z Assigns value y to variable x if condition a is true, z to x if a is false.