<script src="JavaScriptFile.js"></script>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
</body>
</html>
JavaScript can be placed in the <head> tag or in the <body> tag.
It is best to place JavaScript at the bottom of the <body> because
script interpretation can slow down the page display
<button onclick="window.alert('You clicked me!');">Click me</button>
Copy and paste the following in a .html file
JavaScript can "display" data in different ways:
document.getElementById("id").innerHTML
.document.write()
.window.alert()
.console.log()
.JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo":
document.getElementById("demo").innerHTML = "Hello Dolly.";
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:
var a, b, c; // Declare 3 variables
a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c
Try it Yourself »When separated by semicolons, multiple statements on one line are allowed:
a = 5; b = 6; c = a + b;
Try it Yourself »On the web, you might see examples without semicolons.
Ending statements with semicolon is not required, but highly recommended.
variables are used to store data values.
A variable name can begin with a letter, underscore (_), or a dollar sign ($). Subsequent characters may be letters, digits, underscores, or dollar signs. A variable name cannot start with a number and must not contain minus signs (hyphens/dashes) (-)
JavaScript is case-sensitive.
JavaScript uses the var
keyword to declare variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
var x;
x = 6;
Code after double slashes //
or between /*
and */
is treated as a comment.
Comments are ignored, and will not be executed.
Arithmetic operators perform arithmetic on numbers (literals or variables).
Operator | Description |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
** | Exponentiation (ES2016) |
/ | Division |
% | Modulus (Remainder) |
++ | Increment |
-- | Decrement |
x = undefined
You can use the JavaScript typeof operator to find the type of a JavaScript variable.
The typeof operator can be used with or without brackets ().
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof(true) // Returns "boolean"
typeof false // Returns "boolean"
typeof x // Returns "undefined" (if x has no value)
JavaScript has dynamic types. This means that the same variable can be used to hold different data types:
var x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String
A JavaScript string is zero or more characters written inside single (' ') or double (" ") quotes.
var carName1 = "Volvo XC60"; // Double quotes
var carName2 = 'Volvo XC60'; // Single quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
var answer1 = "It's alright";
var answer2 = "He is called 'Johnny'";
var answer3 = 'He is called "Johnny"';
To use the same quotes in a string use a backslash (\)
Code | Result | Description |
---|---|---|
\' | ' | Single quote |
\" | " | Double quote |
\\ | \ | Backslash |
\n | newline character | starts text on a new line |
\t | tab character | tabs or indents the text |
var x = "We are \"Vikings\" from the north";
Strings can be concatenated with the addition "+" operator:
alert("hello" + "Bob");
var txt1 = "hello";
var txt2 = "Bob";
alert(txt1 + txt2);
Note that trying to do invalid arithmetic on strings will just produce the value Not a Number - NaN
To find how many letters are in a string use the length property:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
console.log(txt.length); //26
Number Method | Description | Example |
---|---|---|
Global JavaScript Methods JavaScript - global methods can be used on all JavaScript data types. | ||
Number() | Returns a number, converted from its argument. If the number cannot be converted, NaN (Not a Number) is returned. |
|
parseFloat() | Parses its argument and returns a floating point number. parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned. If the number cannot be converted, NaN (Not a Number) is returned. |
|
parseInt() | Parses its argument and returns an integer parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned. If the number cannot be converted, NaN (Not a Number) is returned. |
|
Other number methods that you may find useful | ||
isNaN() | You can use the global JavaScript function isNaN() to find out if a value is a number |
x can also be assigned NaN
Note that typeof(NaN) is a number |
toString() | The toString() method returns a number as a string. |
Base 10 is default but other bases can be specified:
|
toExponential() | toExponential() returns a string, with a number rounded and written using exponential notation. An optional parameter defines the number of characters behind the decimal point. If you don't specify a parameter, JavaScript will not round the number. |
|
toFixed() | toFixed() returns a string, with the number written with a specified number of decimals |
|
toPrecision() | toPrecision() returns a string, with a number written with a specified length |
|
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
function name(parameter1 = 5, parameter2 = "hello", parameter3) { //optional parameter variables, some with optional initializations
// code to be executed
arguments.length; //this useful builtin arguments object can be used to find out how many arguments are passed to the function
arguments[i]; // you can even access each argument in an array
//parameters, and variables declared with the var keyword, are local to the function e.g var x = "local";
//variables used without the var keyword are global and are accesible outside the function e.g. x = "global";
return someValue; //optional value can be returned, return can also be used to exit the function.
}
name(argument1, argument2, argument3); //arguments are optional if the parameter has been initialized in the function definition
Functions called without the brackets () will return the function object
This is useful for assigning functions to variables.
var x = mult;
x(5,5); //returns 25
mult(5,5); //also returns 25
function mult(a, b) {
return a * b
};
var x = function (a, b) {return a * b};
var z = x(4, 3); //z is assigned 12
Note the function above is anonymous because it was not declared with a name, only x() can call the function
Function expressions can be made "self-invoking".
A self-invoking expression is invoked (started) automatically, without being called.
Function expressions will execute automatically if the expression is followed by ().
You cannot self-invoke a function declaration.
You have to add parentheses around the function to indicate that it is a function expression:
Example
(function () {
var x = "Hello!!"; // I will invoke myself
})();
The function above is actually an anonymous self-invoking function (function without name).
hello = function() {
return "Hello World!";
}
Same as:
hello = () => {
return "Hello World!";
}
It gets shorter! If the function has only one statement, and the statement returns a value, you can remove the brackets and the return keyword:
hello = () => "Hello World!";
Note: This works only if the function has only one statement.
hello = (val) => "Hello " + val;
In fact, if you have only one parameter, you can skip the parentheses as well:
hello = val => "Hello " + val;
Objects mimic/represent real world objects
Objects are a set of key-value pairs of data that form a kind of description of an object
To declare an object:
var myobject = {key1: "value1", key2: value2,…};
To access value of object:
var x = myobject.key1; //OR
var x = myobject["key1"];
Note that Objects are Passed by Reference in functions.
This means that if you change the value of the object, you change the object everywhere in the program, unlike local variables
Also if you assign an object to another variable, the variable stores a reference to the object, not a copy.
Note that Arrays are (special) objects, this also applies to arrays
var car = {type:"Fiat", model:"500", color:"white"};
var x = car;
x.color= "blue";
document.write(car.color); //writes blue;
The "this" keyword
The 'this' keyword has different values depending on where it is used.
In a method (a function in an object), this refers to the owner object. E.g:
var person = {
firstName: "John",
fullName : function() { return this.firstName }
};
this refers to the person (owner) object, it can be replaced with person.firstName
Alone, this refers to the global object.
In a function, this refers to the global object.
Arrays store multiple variables/data values
To use array you declare it:
var myarray = []; //OR
var myarray = [item1, item2, ...];
To add more values to array:
myarray[0] = 1;
myarray[1] = 'value 2';
myarray.push(item); //- Adds item to end of array
var x = myarray.pop(); //-Removes item from end of array and returns value
var y = myarray.length; //-Returns array size (number of elements in the array)
Note that array indexes start at zero - (0) and NOT one (1).
Here is a list of some common HTML events:
Event | Description |
---|---|
Events useful for forms | |
onchange | An HTML element has been changed |
onblur | The event occurs when an element loses focus |
onfocus | The event occurs when an element gets focus |
onfocusin | The event occurs when an element is about to get focus |
onfocusout | The event occurs when an element is about to lose focus |
oninput | The event occurs when an element gets user input |
oninvalid | The event occurs when an element is invalid |
onsubmit | The event occurs when a form is submitted |
Mouse Events | |
onclick | The user clicks an HTML element |
ondblclick | The event occurs when the user double-clicks on an element |
onmouseover | The user moves the mouse over an HTML element |
onmouseout | The user moves the mouse away from an HTML element |
onmouseenter | The event occurs when the pointer is moved onto an element |
onmouseleave | The event occurs when the pointer is moved out of an element Difference between mouse enter/leave and mouse over/out events |
onmousedown | The event occurs when the user presses a mouse button over an element |
onmouseup | The event occurs when a user releases a mouse button over an element |
onmousemove | The event occurs when the pointer is moving while it is over an element |
onwheel | The event occurs when the mouse wheel rolls up or down over an element |
Keyboard Events | |
onkeydown | The user pushes a keyboard key |
onkeypress | The event occurs when the user presses a key |
onkeyup | The event occurs when the user releases a key |
Useful page Events | |
onload | The browser has finished loading the page |
onpageshow | The event occurs when the user navigates to a webpage |
onpagehide | The event occurs when the user navigates away from a webpage, this may not work as expected based on browser settings |
The list is much longer: W3Schools JavaScript Reference HTML DOM Events.
There are useful event objects that provide useful information (attributes/properties) and operations (methods) about the event that was triggered.
For example when a key on the keyboard is pressed, it will be useful to know which key was pressed as well.
Here is a list of some common useful event properties:
Event Property | Description |
---|---|
Keyboard Event object | |
key | Returns the key value of the key represented by the event |
Mouse Event object | |
button | Returns which mouse button was pressed when the mouse event was triggered |
buttons | Returns which mouse buttons were pressed when the mouse event was triggered |
which | Returns which mouse button was pressed when the mouse event was triggered. The values returned by this property are the same as those returned by the button property plus one |
clientX | Returns the horizontal coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered |
clientY | Returns the vertical coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered |
Mouse Wheel Event object | |
deltaY | Returns the vertical scroll amount of a mouse wheel (y-axis) |
var i = 10;
if (i < 5) {
greeting = "Good day";
}
else if (i < 6) {
greeting = "Good evening";
}
else {
greeting = "Good night";
}
The variable greeting will be assigned "Good night" because i = 10 which causes the first two conditions to evaluate to false
variablename = (condition) ? value1:value2
Examplevar age= 16;
var voteable = (age < 18) ? "Too young":"Old enough";
var i = 10;
switch (i) {
case 1:
greeting = "Hello";
break;
case 5:
greeting = "Good day";
break;
case 8:
greeting = "Good afternoon";
break;
case 10:
greeting = "Good night";
break;
default:
greeting = "bye bye"
}
A neat way of selecting one of many blocks of code to execute. In this case, the variable greeting is assign "Good night".
The default case is optional and is similar to the else statement- if all comparisons are false, the default will execute
Note that Switch cases use strict comparison (===). The values must be of the same type to match.
Comparison operators are used in logical statements to determine equality or difference between variables or values.
Given that x = 5
, the table below explains the comparison operators:
Operator | Description | Comparing | Returns | Try it |
---|---|---|---|---|
== | equal to | x == 8 | false | Try it » |
x == 5 | true | Try it » | ||
x == "5" | true | Try it » | ||
=== | equal value and equal type | x === 5 | true | Try it » |
x === "5" | false | Try it » | ||
!= | not equal | x != 8 | true | Try it » |
!== | not equal value or not equal type | x !== 5 | false | Try it » |
x !== "5" | true | Try it » | ||
x !== 8 | true | Try it » | ||
> | greater than | x > 8 | false | Try it » |
< | less than | x < 8 | true | Try it » |
>= | greater than or equal to | x >= 8 | false | Try it » |
<= | less than or equal to | x <= 8 | true | Try it » |
Logical operators are used to determine the logic between variables or values.
Given that x = 6
and y = 3
, the table below explains the logical operators:
Operator | Description | Example | Try it |
---|---|---|---|
&& | and | (x < 10 && y > 1) is true | Try it » |
|| | or | (x == 5 || y == 5) is false | Try it » |
! | not | !(x == y) is true | Try it » |
Comparing data of different types may give unexpected results.
When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison.
An empty string converts to 0. A non-numeric string converts to NaN
which is always false
.
Case | Value | Try |
---|---|---|
2 < 12 | true | Try it » |
2 < "12" | true | Try it » |
2 < "John" | false | Try it » |
2 > "John" | false | Try it » |
2 == "John" | false | Try it » |
"2" < "12" | false | Try it » |
"2" > "12" | true | Try it » |
"2" == "12" | false | Try it » |
When comparing two strings, "2" will be greater than "12", because (alphabetically) 1 is less than 2.
To secure a proper result, variables should be converted to the proper type before comparison:
Loops can execute a block of code a number of times.
The for loop has the following syntax:
for (initializations; condition; incrementations) {
// code block to be executed
}
Example:
for (var i = 0; i < 5; i++) {
// code block to be executed
}
//The loop will repeat (from i = 0 to i = 4) five (5) times
The while loop loops through a block of code as long as a specified condition is true.
Syntax:
while (condition) {
// code block to be executed
}
Example:
var i = 0;
while (i < 5) {
//code block to be executed
i++; //equivalent to i = i + 1;
}
//The loop will repeat (from i = 0 to i = 4) five (5) times based on the condition (i < 5).
do {
// code block to be executed
}
while (condition);
Example:
var i = 0;
do {
//code block to be executed
i++;
}
while (i < 5);
//The loop will repeat (from i = 0 to i = 4) five (5) times based on the condition (i < 5).
break;
and continue;
You can use the keyword continue, to skip an iteration of the loop.
You can use the keyword break, to jump out of (end) a loop.
These keywords are often used with if-statements.
Using the Document method getElementById() to access the value attribute of the input form element.
<input id ="fname" type="text" name="firstname" value="" placeholder="Enter first name" oninput="getName()" >
<p id = "display"></p>
<script>
var name = "";
function getName(){
name = document.getElementById("fname").value //store entered name
document.getElementById("display").innerHTML = name; //display the name
}
</script>
Using name attributes of a form to access the input element's value docment.forms["myForm"]["fname"].value
See link https://www.w3schools.com/js/tryit.asp?filename=tryjs_validation_js
There are other ways but these are very effective for now
For the javascript form validation Api see https://www.w3schools.com/js/js_validation_api.asp
Attribute | Description |
---|---|
disabled | Specifies that the input element should be disabled |
max | Specifies the maximum value of an input element |
min | Specifies the minimum value of an input element |
pattern | Specifies the value pattern of an input element |
required | Specifies that the input field requires an element |
type | Specifies the type of an input element |
For a full list, go to HTML Input Attributes.
Selector | Description |
---|---|
:disabled | Selects input elements with the "disabled" attribute specified |
:invalid | Selects input elements with invalid values |
:optional | Selects input elements with no "required" attribute specified |
:required | Selects input elements with the "required" attribute specified |
:valid | Selects input elements with valid values |
For a full list, go to CSS Pseudo Classes.
Javascript variables are temporary and their values are all lost when you reload the webpage.
Web storage allows you to store data in the browser.
HTML web storage provides two objects for storing data on the client:
window.localStorage - stores data with no expiration date
window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
var lastname = localStorage.getItem("lastname");
// Store
localStorage.lastname = "Smith";
// Retrieve
var lastname = localStorage.lastname;
localStorage.removeItem("lastname");
The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.
Note: Name/value pairs are always stored as strings. Remember to convert them to another format when needed!
<?php
$myfile = fopen("message.txt", "w") or die("Unable to open file!");
$txt = $_GET["message"];
fwrite($myfile, $txt);
fclose($myfile);
echo "Message Sent";
?>
<html>
<head>
<title>My Form</title>
</head>
<body>
<form action="SaveMessage.php">
Message: <input type="text" name="message" placeholder='Enter message'>
<input type="submit" value='Send Message'>
</form>
</body>
</html>
To test PHP code, you will have to use a webserver/webhost that supports php or download a php server such as WAMP or XAMPP
Functions and variables can be used before they are declared because they are "hoisted" or automatically declared at top of a program.
Variables declared with let or const are NOT hoisted
Initializations (var y=5;) are NOT hoisted, however the declaration (var y;) will be hoisted.
document.write(myNum); //writes undefined
var myNum = 5;
________________
Note: Functions are not hoisted when declared in a variable.
{let num=5} //num is 5 here
document.write(num) //num is undefined here
{var num = 5;} //num is 5 here
document.write(num) //num is 5 here
Using global varibles is bad programming practice because your variable can be changed anywhere in the program unknown to you.
Use global variables sparingly.
var num = 10;
myFunction();
document.write(num); //prints 5
function myFunction() {
num = 5
}