Internal
Can mix JavaScript and HTML together in the same file. Heck...PHP too!
<!DOCTYPE html> <html> <head> <title>Hello World</title> </head> <body> <h1>First JavaScript</h1> <script> document.write("Hello World!"); </script> </body> </html>
External
You can also put the code in another separate file and link it to your HTML file via a src attribute. Again, if it is not contained in a function - it will simply be called when the page is loaded.
Your HTML file - let's say hello.html - would look like this:
<!DOCTYPE html> <html> <head> <script src="hello.src"></script> </head> <body> <h1>My Header</h1> </body> </html>
Your JavaScript file - called hello.js - would look like this:
alert("Hello, world.");
semicolons
All statements in JavaScript end with a semicolon. If you forget, you will get an error. Don't forget 🙂
alert(" Hi world!");
You can even do multiple statements on one line thought that can get confusing so only do it with simple statements that obviously belong together. When separated by semicolons, multiple statements on one line are allowed:
a = 5; b = 6; c = a + b;
White Space
White space is ignored by JavaScript and is used to improve readability.
Curly Brackets
Code blocks or sets of statements can be grouped together inside curly brackets {…} like for functions or loops.
var sun_shining = true; if (sun_shining){ alert(“Wear some sunscreen!”); }
Comments
Comments are used in coding to explain what your doing. This can be useful both in understanding your own code and in helping the coders who follow after you.
Single line comments start with //. Multi-line comments – start with /* and end with */
//this is a comment var a = 5; //this is another comment
/*
The code below will change
in my web page:
*/
Declare a Variable - create it, state that it exists
var name; var age;
Initialization - give variable a value when you create it
var name = "Kate"; var age = 10;
Assignment - change what value the variable holds
name = "Alice"; age = 11; name = "Lily"; age = 12;
Naming Conventions
These are the rules that you must follow in creating the name of the variable. In JavaScript all variable names...
- Can contain letters, numbers, underscores and dollar signs only.
- must begin with a letter.
- Variable names can also begin with a $ and a _ but the accepted method is with a letter.
- Case sensitive so you must differentiate between uppercase and lowercase letters. Cat and cat are two different variables.
- Do not use reserved JavaScript keywords for span class="proper">variable names such as alert or char.
- No spaces!
Data Types
- Numbers - whole or decimal
- Strings - text
- Boolean - logical value - true or false
- Arrays - lists of items
- Objects - more complex type
View Full Topic
Popping up information
The alert() function will create a popup box to display the string information provided it - either straight text or variables or both.
alert("Hello World"); varname="You"; alert("Hello"+name);
Writing information into web page
The document.write() function will write the string information provided it - either straight text or variables or both - directly into the web page for all to see.
document.write("Hello World"); varname="You"; document.write("Hello"+name);
prompt()
The prompt() function will create a popup box to ask the user a question and provide a space for the user to respond. Values returned are always a string.
varname="prompt(" What is your name?)"; alert("Hello"+name);
confirm()
The confirm() function provides the user with a string value and lets them click the OK button to continue the action or the Cancel button to cancel. If they click OK, the function returns a true value. If they click Cancel it returns a false value.
<!DOCTYPE html> <html> <body> <h1>JavaScript Confirm Box</h1> <p>Do we want to keep going?</p> <script> var KeepGoing = confirm("Do you want to try again?"); if (KeepGoing){ alert("We will keep going"); }else{ alert("We will stop!"); } </script> </body> </html>
| Operator | Description | Example |
|---|---|---|
| + | add | 1 + 1 = 2 |
| - | subtract | 4 -2 = 2 |
| / | divide | 6 / 3 = 2 |
| * | multiply | 2 * 2 = 4 |
| ++ | add one | 3++ = 4 |
| -- | minus one | 5-- = 4 |
Order
If no partheneses, order is multiplication, then division, addition and subtracation. Use () to regroup and change order!
Strings are denoted with either single quotes or double quotes but they must match!
//This string has double quotes at the beginning and end var message1 = “Fiona is in this class”; //This one has single quotes at the beginning and end var message2 = ‘Teo is in the class too’;
Concatenation
To combine strings in one single string - we use what is called Concatenation. Concatenation simply strings them together using the + in between strings. The basic syntax is:
WholeString = string1 + string2+ string3;
Got it? Maybe? Here are some examples:
var txt1 = “hi”; var txt2 = “Claire”; document.write($txt1 + " " + $txt2);
Here are a few useful ones - but here is a full list from W3Schools.
| function | Description | Example | Output |
|---|---|---|---|
| .length | # of characters in string |
var str = "Hi" str.length |
2 |
| concatt() | joins two or more strings |
concat("one", "two","three") |
onetwothree |
| toLowerCase() | Make everything lowercase |
str.toLowerCase() |
hi |
| toUpperCase() | Make everything uppercase |
str.toUpperCase() |
HI |
| indexOf() | Finds the index or position of the first occurrence of the string you are looking for. |
var str = "Where is first first?" varpos=str.indexOf("first") |
9 |
| lastIndexOf() | Finds the index or position of the last occurrence of the string you are looking for. |
var str = "Where is first first?" varpos=str.lastIndexOf("first") |
15 |
| search() | Similar to indexOf(). |
var str = "Where is first first?" varpos=str.search("first") |
9 |
| charAt() | Returns character at a specific position. |
var str = "Where is first first?" varpos=str.charAt(3") |
r |
Convert Numbers to Strings
| function | Description | Example | Output |
|---|---|---|---|
| toString() | converts numbers to string |
var number1 = 11; var str = number1.toString() |
"11" |
| toFixed() | converts number to a string with the specified decimals stored |
var number1 = 11.1234; var str = number1.toFixed(0) var str = number1.toFixed(2) |
"11" "11.12" |
Convert Strings to Numbers
toString() method
Converts a number to a string value. This is the most commonly used method. It's basic syntax is seen below:
var sWidth = width.toString();
How do you use that?
var number1 = 1; var number2 = 3; var sumnumbers = number1 + number2; alert("The sum is " + sumnumbers.toString());
toFixed() method
Returns a string of the number written out to the specified number of decimals.
var x = 12.1234; x.toFixed(0);//returns 12 x.toFixed(2); //returns 12.12
toPrecision() method
Returns a string with the specified length
var x = 12.1234; x.toPrecision(2); //returns 12 x.toPrecision(4); //returns 12.12
Converting Strings to Numbers
There are also three ways to convert strings to numbers in JavaScript.
number() method
Convert numbers
x = true; Number(x) //returns 1 x = “20”; Number (x)//returns 20 x = “45 54” Number(x) //returns NaN
parseInt() method
Returns a whole number. Spaces are allowed.
parseInt(“12”); //returns 12 parseInt(“12.45”); //returns 12.45 parseInt(“12 hours”); //returns 12 parseInt(“hours 12”); //returns NaN
parseFloat() method
Returns a decimal number. Spaces are allowed.
parseFloat(“12”); //returns 12 parseFloat(“12.45”); //returns 12.45 parseFloat(“12 hours”); //returns 12 parseFloat(“hours 12”); //returns NaN
Comparison Operators
| Operator | Description | Example | Return Value |
|---|---|---|---|
| == | equal to | 15 == 15 | true |
| 15 == 10 | false | ||
| --- | |||
| === | equal value and equal type |
15 === 15 | true |
| 15 === "15" | false | ||
| != | not equal | 10 != 15 | true |
| 10 != 10 | false | ||
| !=== | not equal value or equal type |
10 !== 10 | false |
| 10 != "10" | true | ||
| > | greater than | 15 > 10 | true |
| < | less than | 15 < 10 | false |
| >= | greater than or equal to | 15 >= 15 | true |
| <= | less than or equal to | 15 <= 10 | false |
Logical Operators
| Operator | Description | Example | Returns a value of |
|---|---|---|---|
| && | and | (10<15 && 20>15) | true |
| (10<15 && 20>15) | false | ||
| || | or | (5 == 5 || 6 == 5) | true |
| (6 > 5 || 3 == 2) | false | ||
| ! | not | !(3 == 3) | false |
//check to see if the condition is met if (today_temperature > 80){ alert("No coat or jacket needed - you can wear shorts!"); } else if (today_temperature < 80 && today_temperature > 65){ alert("Bring a light jacket or hoodie"); } else if (today_temperature < 65 && today_temperature > 50){ alert("Wear a light jacket and maybe slightly longer pants"); } else { //this is the code that will be run if it is not true alert("Wear your winter coat!"); }
var x = "0"; switch (age) { case 13: message = "You are officially a teenager"; break; case 16: message = "You can drive"; break; case 18: message = "You can vote"; break; default: message = "Meh"; }
View Full Topic
Creating an array
//this creates a blank array var kids = []; //this creates an array with string values in it var kids = ["Teo",Cal",Kate",Zoe"];
Access Item in Array
To access the elements in an array– use the index number. You can store the element in a variable:
var kid1 = kids[0];
Or you can access the elements directly as you would any variable.
document.write("The kids in this class are ", + kids[0] + " " + kids[1] +" "+ kids[2] +" "+ kids[3]; Output: The kids in this class are Teo Cal Zoe Tessa
You can also set any item of the array by doing this:
kids[0] = “Tom”; //kids is now [‘Tom’, ‘Cal’, ‘Zoe’, ‘Tessa’]
Length Property: how many elements are in the array .
var kids = [“Teo”, “Cal”, “Zoe”, “Tessa”]; var len = kids.length; Output 4
Sort Property
kids .sort(); //kids is now [‘Cal’, ‘Kate’, ‘Teo’, ‘Tessa’, ‘Zoe’]
- The reverse property will sort the array the opposite.
kids.reverse(); //kids is now [‘’Zoe’,’Tessa’, ‘Teo’,’Kate’,’Cal’]
Adding or Removing Elements
- The easiest way to add elements to an array is to use the push method.
kids.push(“ Kate ”); //kids is now [‘Teo’, ‘Cal’, ‘Zoe’, ‘Tessa’, ‘Kate’]
- You can also add an element using the length property.
kids [ kids .length] = “ Fiona ”; //kids is now [‘Teo’, ‘Cal’, ‘Zoe’, ‘Tessa’, ‘Kate’, ‘Fiona’]
- You can remove the last item in the array by using the pop method.
kids.pop(); //kids is now [‘Teo’, ‘Cal’, ‘Zoe’, ‘Tessa’, ‘Kate’]
- The shift and unshift methods work the same way but add or remove elements from the beginning of the array .
kids.shift(); //kids is now [‘Cal’, ‘Zoe’, ‘Tessa’, ‘Kate’] kids.unshift("Ben"); //kids is now [‘Cal’, ‘Zoe’, ‘Tessa’, ‘Kate’, 'Ben']
Example of a for loop.
for (var i = 1; i < 5; i++) { document.write(i); } Output: 1234
Decrement example of a for loop.
You can also decrement the step counter by 1 or add different amounts to it. This example subtracts 1 from the counter:
for (var i = 3; i > 0; i--) { document.write(i); } Output: 321
One More Example
In this example, let's increase our counter by sets of 25:
for (var i = 1; i < 100; i=i+25) { document.write(i + " "); } Output: 1 26 51 76
while Loop
while(i < 5) { document.write(i); i++; } Output: 1 2 3 4
do...while Loop
do{ code block to be executed } while(condition);
Here is a simple example of a do...while loop in JavaScript:
do{
document.write(i);
i++;
}
while (i < 5);
Output:
1
2
3
4
Watch out for infinite loops and you can use break to exit - sparingly!
var insects= ["ant", "ladybird", "bee", "grasshopper"]; var len = insects.length; for (var i = 0; i< len; i++) { document.write(insects[i]); }
Output:
ant
ladybird
bee
grasshopper
Arrays and while loops
var insects= ["ant", "ladybird", "bee", "grasshopper"]; var i= 0; while ( insects[i]) { document.write(insects[i]); i++; }
Output:
ant
ladybird
bee
grasshopper
function myFunction (a, b) { return a * b; } var x = myFunction (4,3); alert("the product is " + x);
Calling a Function
If we have this function in JavaScript:
function pop_hello() { alert ("hi"); }
We would use the code below to call the function
pop_hello();
Putting it all together
In the next lesson, we will learn how to call functions directly from our web page - but for right now - they will just be called when the page loads.
Our HTML page would look like this:
<!DOCTYPE html> <html> <head> <script src="first_function.js"></script> </head> <body> <h1>First Function JavaScript</h1> </body> </html>
And our JavaScript file would look like this:
function hello(){ return alert("hi"); } hello();
Find By ID & Change HTML & CSS Values
Access an element by its CSS ID selector using document.getElementById.
<h1 id="topHeader>My First Web Page</h1> <p class="top">A paragraph with a bit of <strong>bold.</strong></p> <p>Here is a simple ordered list</p> <ol> <li>First item</li> <li>second item</li> </ol>
Access the element:
var topHeader = document.getElementById('topHeader'); topHeader.innerHTML = "New Header"; // changes HTML value topHeader.style.color = "FF0000"; // changes the color of the font to red
Few notes about changing style
- If the style is one word - like color; margin; padding - you just use that word.
- If they style has dashes in it - like background-color; font-size - you use the camel case version so backgroundColor or fontSize.
Find By Tag Name
This finds all elements with a given HTML tag such as <p>, <h1> or <table>.
var i = document.getElementByTagName('li');
Find By Class Name
You can also find all HTML elements with the same class name by using getElementsByClassName().
var top= document.getElementsByClassName('top');
There are events in HTML that JavaScripot can react to. These included a web apge loading, clicking a button or other element, submitting a form, mousing over an element and more.
<!DOCTYPE html> <html> <body> <h1 id="header" onclick="document.getElementById('header').innerHTML='New Header'">This is the boring old header</h1> <p id="red" onclick="document.getElementById('red').style.color='#FF0000'"> Why aren't I red? I want to be red!!! </p> </body> </html>
Example Using a Button
<!DOCTYPE html> <html> <body> <h1 id="header">My Header</h1> <p id="red"> Why aren't I red? I want to be red!!! </h1> <button onclick="document.getElementById('header').innerHTML='New Header'"> Change Header!</button> <button onclick="document.getElementById('red').style.color='#FF0000'"> Change Paragraph!</button> </body> </html>
Using JavaScript events
When the user activates a JavaScript event you will want to either
- refresh just the front end or JavaScript bits of code
- or call a PHP function to perform more complicated bits of code or to access the database.
//Refresh the current page without visiting the database onchange="location.reload()" //Redirect the page to itself but pass along parameters onchange="self.location=self.location?param1=parma1value¶m2=param2value" //Submit the form - will perform whatever action is specified - onchange="this.form.submit()"
Passing variables
You can use cookies or session variables but let's look at how do it using assignment.
<!DOCTYPE html> <html> <body> <h1>Passing Variables</h1> <?php $state = "DC"; ?> <script> var state = "<?php echo $state; ?> "; alert("You live in " + state); </script> </body> </html>
Passing an array takes a little extra wrangling.
Passing Arrays via Assignment
Take a look at this example.
<!DOCTYPE html> <html> <body> <h1>Passing An Array</h1> <?php $states = array("DC", "MD", "VA"); ?> <script> var states = <?php echo json_encode($states); ?>; for (var s=0; s < states.length; s++){ document.write("Part of the DMV is " + states[s]); } </script> </body> </html>
