JavaScript is programming language for the web. It enables the user to make web pages more interactive by changing the behaviour of html elements on the page along with a range of other functions.
Create a new folder with your project name in OneDrive
Open in visual studio - open folder that you just created
Create a index.html file
Create a script.js file
Create a style.css file (for optional styling requirements)
This can be added in the HTML body at the bottom of the page as the last line before </body>. This allows the page to load first then the script.
<script src = "script.js"></script>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<title>My First Web Page</title>
</head>
<body>
<!-- Start body content -->
<!-- Script File is always ths last line of the body-->
<script src ="script.js"></script>
</body>
</html>
In JavaScript we can comment our code by using a two slashes //. The are normally green. Code that have the slashes before it will not be processed on each line.
var age = 0 // This is a comment
// Another Comment
// And another
You can write data to the console log window to test your program. See examples below:
console.log("Hi!");
console.log(varaiable_name + " " + variable_name2);
console.log(1+3);
You will also find errors in the inspector to help you debug your code. It will give you the line number.
The inspector allows you to view console.log outputs and any errors in your script on the right hand side under the console tab.
Variables in JavaScript can have a range of data types including:
Strings - letters & characters
Integers - numbers
Floats - numbers with decimals
Date/Time
Arrays - storing multiple items in an index system like a list
Note: No variable data type needs to be set when declaring the variable for the first time
The first time or instance that a variable is created (declared) needs to begin with the key term var. e.g. var age = 0
Each time after that, you refer to the variable using just its name. age
Remember that variable names can not be duplicated or be the same name as functions.
//declare global variables. These can be seen by all functions
var price1 = 5;
var price2 = 6;
var name = "ted";
var total=0;
var nameArray = [];
//change value of price1 and price2
price1 = 10
price2 = 12
total = price1 + price2;
console.log(total); //total would name be 22
Must begin with a letter - lower case is best
Case sensitive - make sure you spell it the same each time
Cannot have the same name as a function - keep variable and function names different
No spaces - use an underscore _ instead or capital letter for the second word - tennisScore
These are good for storing locations of html elements from the html file.
const gravity = 9.6;
const inputbox = document.getElementById("inputbox");
To enable the html file and JS file to interact we need to tell the JS where the html variables are located.
Each html tag will need an id and unique name.
Here is an example of a html element with an ID called "output" in index.html
<p id="output"></p>
Search for the html document for the id output and store its location in a CONSTANT in script.js
const output = document.getElementById("output");
To write new content to the html element we use the innerHTML property and assign and update the value using the reference stored in the constant created above
output.innerHTML ="Text goes here..";
Extra:
If you want to add additional content to an area that already has content you can append new content to the end by using += symbols.
output.innerHTML += "This is the second line of text";
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css">
<title>My First Web Page</title>
</head>
<body>
<!-- Start body content -->
<b>My First Web page</b>
<p id="output"></p>
<!-- Script File -->
<script src ="script.js"></script>
</body>
</html>
script.js
//get location of html element and store in a constant
const output = document.getElementById("output");
//update the content on the page with a new value
output.innerHTML = "Hello World!"
//append additional output text
output.innerHTML += " An this has been added."
HTML - Here is an example of a html input box from the html file with an id of "ageInput"
<input id = "ageInput" type="number>
Javascript - We then create a reference to ageInput from the HTML using getElementById("ageInput");
Store this element location in a JS constant called ageInput.
const ageInput = document.getElementById('ageInput')
JavaScript - Store or get the value from the form field in a JS variable
var age = age.value;
Index.html
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="mystyle.css">
<title>My First Web Page</title>
</head>
<body>
<!-- Start body content -->
<b>My First Web page with Input</b>
<!-- Input area with a set value-->
<label for "ageInput">Enter Your Age:</label>
<input id="ageInput" type="number" min="1" max="99" value = 6>
<!-- Area to output the age -->
<p id="output"></p>
<!-- Script File -->
<script src ="script.js"></script>
</body>
</html>
script.js
//get location of html element and store in a constant
const ageInput = document.getElementById("ageInput");
const output = document.getElementById("output");
//update the content on the page with a new value
output.innerHTML = "The age in the box = " + ageInput.value;
Concatenation is fancy word to print variables and a string in the same output.
We use a + symbol to join a string and a variable.
The text (string) needs to have double quotes " "
You can reference a variable with the variable name
Example
var studentName = "Fred";
console.log("My name is " + studentName);
Output:
My name is Fred
var studentName = "Gus";
var studentAge = 16;
console.log("My name is " + studentName + " and I am " + age + " years old.");
Output:
Hi my name is Gus and I am 16 years old.
Functions are blocks of code that can reused. They can be triggered by events like clicking on a button or when being used with a timer.
Function blocks are declared using the function keyword, a unique name and following notations of round brackets for parameters/arguments and curly brackets to signal the start and end of function.
function myFunctionName() { //start function
output.innerHTML = "Hello World!";
} //end function
Functions can be run/triggered by simply calling the name of the function with two brackets after.
In JS
myFunctionName(); // this will make the function above start
In HTML with a button on click will run the myFunctionName() when clicked
<button onclick = "functionName()">Label for Button</button
Functions may also have parameters (the names inside the function brackets that can represent values).
They can be called with arguments (values) from the function call:
The return call simply places the result of the function as a value back to the initiation of the call.
function multiply(p1, p2) {
return p1 * p2; // The function returns the product of p1 and p2
}
Example
var x = multiply(2,3); /return x = 6
If statements allows the program to make decisions depending on an action or value inputted by the user. They use true of false conditions to make decisions/
if (condition) {
// block of code to be executed if the condition is true
}
if (5 < 18) {
greeting = "Good day";
}
if (condition) {
// block of code to be executed if the condition is true
} else if (condition) {
// block of code to be executed if the condition is false
}
var hour = 10;
if (hour < 12) {
greeting = "Good day";
} else if (hour > 12){
greeting = "Good evening";
} else{
greeting = "Midday";
}
If statement conditions
== equal to
!= Not equal
> greater
>= greater or equal
< less then
<= less then or equal
For two or more conditions
&& AND
|| OR
for (counter; condition; increment) {
// code block to be executed
}
for (var i = 0; i < 4; i++) {
text += "The number is " + i + "<br>";
}
console.log(text);
Output would be
The number is 0
The number is 1
The number is 2
The number is 3
Statement 1 is executed (one time) before the execution of the code block. Set the count variable to 0
Statement 2 defines the condition for executing the code block. What condition to exit the loop?
Statement 3 is executed (every time) after the code block has been executed. (add or subtract from the counter for each loop of the block of code)
Example
//for loop for array
var arr =["ted","shaun","Tess"];
for(var i = 0; i<arr.length; i++){
console.log(arr[i]); // will print the name of each person in array
}
These are use for pre-tests in an algorithm. For example while a boolean is true or while a value has not changed.
while (condition) {
// code block to be executed
}
while (i < 10) {
text += "The number is " + i;
i++;
}
Make sure you increment your counter variable each iteration (loop) or you may find you end up in an infinity loop that never ends!
Convert string values to an integer - parseInt(variable) //Should be used when getting values from a form
Round a number down to nearest unit - Math.round(variable)
Random Number generation - Math.floor(Math.random() * 10); // returns a random integer from 0 to 9
Events listen out for certain actions happening on the page. These could include:
onchange - An HTML element has been changed
onclick - The user clicks an HTML element like a button
onmouseover - The user moves the mouse over an HTML element
onmouseout -The user moves the mouse away from an HTML element
onkeydown -The user pushes a keyboard key down
onload -The browser has finished loading the page
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the date.</p>
<button onclick="displayDate()">The time is?</button>
// when clicked will run function called displayDate()
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body>
</html>