HTML events are "things" that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can "react" on these events.
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
With single quotes:
<some-HTML-element some-event='some JavaScript'>
With double quotes:
<some-HTML-element some-event="some JavaScript">
In the following example, an onclick attribute (with code), is added to a button element:
<button onclick='getElementById("demo").innerHTML=Date()'>The time is?</button>
In the example above, the JavaScript code changes the content of the element with id="demo".
In the next example, the code changes the content of it's own element (using this.innerHTML):
<button onclick="this.innerHTML=Date()">The time is?</button>
JavaScript code is often several lines long. It is more common to see event attributes calling functions: |
<button onclick="displayDate()">The time is?</button>
Here is a list of some common HTML events:
Event |
Description |
onchange |
An HTML element has been changed |
onclick |
The user clicks an HTML element |
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 |
onload |
The browser has finished loading the page |
The list is much longer: W3Schools JavaScript Reference HTML DOM Events.
Event handlers can be used to handle, and verify, user input, user actions, and browser actions:
Many different methods can be used to let JavaScript work with events:
You will learn a lot more about events and event handlers in the HTML DOM chapters. |
JavaScript strings are used for storing and manipulating text.
A JavaScript string simply stores a series of characters like "John Doe".
A string can be any text inside quotes. You can use single or double quotes:
var carname = "Volvo XC60";
var carname = 'Volvo XC60';
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
var answer = "It's alright";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';
Or you can put quotes inside a string by using the \ escape character:
var answer = 'It\'s alright';
var answer = "He is called \"Johnny\""
The length of a string (a string object) is found in the built in property length:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
In JavaScript, strings are written as characters inside single or double quotes.
Because of this, JavaScript will misunderstand this string:
"We are the so-called "Vikings" from the north."
The string will be chopped to "We are the so-called ".
To solve this problem, you can place a backslash (\) before the double quotes in "Vikings":
"We are the so-called \"Vikings\" from the north."
The backslash is an escape character. Escape characters turns special characters into string characters:
The escape character (\) can be used to insert apostrophes, new lines, quotes, and other special characters into a string.
The table below lists other special characters that can be added to a text string with the backslash sign:
Code |
Outputs |
\' |
single quote |
\" |
double quote |
\\ |
backslash |
\n |
new line |
\r |
carriage return |
\t |
tab |
\b |
backspace |
\f |
form feed |
Normally, JavaScript strings are primitive values, created from literals: var firstName = "John"
But strings can also be defined as objects with the keyword new: var firstName = new String("John")
var x = "John";
var y = new String("John");
// type of x will return String
// type of y will return Object
Don't create String objects. They slow down execution speed, and produce nasty side effects: |
var x = "John";
var y = new String("John");
// (x === y) is now false because x is a string and y is an object.
Primitive values, like "John Doe", cannot have properties or methods (because they are not objects).
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
String methods are covered in next chapter.
Property |
Description |
constructor |
Returns the function that created the String object's prototype |
length |
Returns the length of a string |
prototype |
Allows you to add properties and methods to an object |
Method |
Description |
charAt() |
Returns the character at the specified index (position) |
charCodeAt() |
Returns the Unicode of the character at the specified index |
concat() |
Joins two or more strings, and returns a copy of the joined strings |
fromCharCode() |
Converts Unicode values to characters |
indexOf() |
Returns the position of the first found occurrence of a specified value in a string |
lastIndexOf() |
Returns the position of the last found occurrence of a specified value in a string |
localeCompare() |
Compares two strings in the current locale |
match() |
Searches a string for a match against a regular expression, and returns the matches |
replace() |
Searches a string for a value and returns a new string with the value replaced |
search() |
Searches a string for a value and returns the position of the match |
slice() |
Extracts a part of a string and returns a new string |
split() |
Splits a string into an array of substrings |
substr() |
Extracts a part of a string from a start position through a number of characters |
substring() |
Extracts a part of a string between two specified positions |
toLocaleLowerCase() |
Converts a string to lowercase letters, according to the host's locale |
toLocaleUpperCase() |
Converts a string to uppercase letters, according to the host's locale |
toLowerCase() |
Converts a string to lowercase letters |
toString() |
Returns the value of a String object |
toUpperCase() |
Converts a string to uppercase letters |
trim() |
Removes whitespace from both ends of a string |
valueOf() |
Returns the primitive value of a String object |
String methods help you to work with strings.
The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string:
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");
Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.
JavaScript counts positions from zero. |
Both methods accept a second parameter as the starting position for the search.
The search() method searches a string for a specified value and returns the position of the match:
var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");
Did You Notice? |
The two methods, indexOf() and search(), are equal.
They accept the same arguments (parameters), and they return the same value.
The two methods are equal, but the search() method can take much more powerful search values.
You will learn more about powerful search values in the chapter about regular expressions.
There are 3 methods for extracting a part of a string:
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the starting index (position), and the ending index (position).
This example slices out a portion of a string from position 7 to position 13:
var str = "Apple, Banana, Kiwi";
var res = str.slice(7,13);
The result of res will be:
Banana
If a parameter is negative, the position is counted from the end of the string.
This example slices out a portion of a string from position -12 to position -6:
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12,-6);
The result of res will be:
Banana
If you omit the second parameter, the method will slice out the rest of the string:
var res = str.slice(7);
or, counting from the end:
var res = str.slice(-12);
Negative positions does not work in Internet Explorer 8 and earlier. |
substring() is similar to slice().
The difference is that substring() cannot accept negative indexes.
var str = "Apple, Banana, Kiwi";
var res = str.substring(7,13);
The result of res will be:
Banana
If you omit the second parameter, substring() will slice out the rest of the string.
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
var str = "Apple, Banana, Kiwi";
var res = str.substr(7,6);
The result of res will be:
Banana
If the first parameter is negative, the position counts from the end of the string.
The second parameter can not be negative, because it defines the length.
If you omit the second parameter, substr() will slice out the rest of the string.
The replace() method replaces a specified value with another value in a string:
str = "Please visit Microsoft!";
var n = str.replace("Microsoft","W3Schools");
The replace() method can also take a regular expression as the search value.
A string is converted to upper case with toUpperCase():
var text1 = "Hello World!"; // String
var text2 = text1.toUpperCase(); // text2 is text1 converted to upper
A string is converted to lower case with toLowerCase():
var text1 = "Hello World!"; // String
var text2 = text1.toLowerCase(); // text2 is text1 converted to lower
concat() joins two or more strings:
var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ",text2);
The concat() method can be used instead of the plus operator. These two lines do the same:
var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ","World!");
All string methods return a new string. They don't modify the original string. |
There are 2 safe methods for extracting string characters:
The charAt() method returns the character at a specified index (position) in a string:
var str = "HELLO WORLD";
str.charAt(0); // returns H
The charCodeAt() method returns the unicode of the character at a specified index in a string:
var str = "HELLO WORLD";
str.charCodeAt(0); // returns 72
You might have seen code like this, accessing a string as an array:
var str = "HELLO WORLD";
str[0]; // returns H
This is unsafe and unpredictable:
If you want to read a string as an array, convert it to an array first.
A string can be converted to an array with the split() method:
var txt = "a,b,c,d,e"; // String
txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe
If the separator is omitted, the returned array will contain the whole string in index [0].
If the separator is "", the returned array will be an array of single characters:
var txt = "Hello"; // String
txt.split(""); // Split in characters
JavaScript has only one type of number.
Numbers can be written with, or without, decimals.
JavaScript numbers can be written with, or without decimals:
var x = 34.00; // A number with decimals
var y = 34; // A number without decimals
Extra large or extra small numbers can be written with scientific (exponent) notation:
var x = 123e5; // 12300000
var y = 123e-5; // 0.00123
Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.
JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.
This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63:
Value (aka Fraction/Mantissa) |
Exponent |
Sign |
52 bits (0 - 51) |
11 bits (52 - 62) |
1 bit (63) |
Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits.
var x = 999999999999999; // x will be 999999999999999
var y = 9999999999999999; // y will be 10000000000000000
The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate:
var x = 0.2 + 0.1; // x will be 0.30000000000000004
To solve the problem above, it helps to multiply and divide:
var x = (0.2 * 10 + 0.1 * 10) / 10; // x will be 0.3
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). |
By default, Javascript displays numbers as base 10 decimals.
But you can use the toString() method to output numbers as base 16 (hex), base 8 (octal), or base 2 (binary).
var myNumber = 128;
myNumber.toString(16); // returns 80
myNumber.toString(8); // returns 200
myNumber.toString(2); // returns 10000000
Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.
var myNumber = 2;
while (myNumber != Infinity) { // Execute until Infinity
myNumber = myNumber * myNumber;
}
Division by 0 (zero) also generates Infinity:
var x = 2 / 0; // x will be Infinity
var y = -2 / 0; // y will be -Infinity
Infinity is a number: typeOf Infinity returns number.
typeof Infinity; // returns "number"
NaN is a JavaScript reserved word indicating that a value is not a number.
Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number):
var x = 100 / "Apple"; // x will be NaN (Not a Number)
However, if the string contains a numeric value , the result will be a number:
var x = 100 / "10"; // x will be 10
You can use the global JavaScript function isNaN() to find out if a value is a number.
var x = 100 / "Apple";
isNaN(x); // returns true because x is Not a Number
Watch out for NaN. If you use NaN in a mathematical operation, the result will also be NaN.
var x = NaN;
var y = 5;
var z = x + y; // z will be NaN
NaN is a number: typeOf NaN returns number.
typeof NaN; // returns "number"
Normally JavaScript numbers are primitive values created from literals: var x = 123
But numbers can also be defined as objects with the keyword new: var y = new Number(123)
var x = 123;
var y = new Number(123);
typeof x; // returns number
typeof y; // returns object
Don't create Number objects. They slow down execution speed, and produce nasty side effects: |
var x = 123;
var y = new Number(123);
(x === y) // is false because x is a number and y is an object.
Primitive values (like 3.14 or 2014), cannot have properties and methods (because they are not objects).
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
Property |
Description |
MAX_VALUE |
Returns the largest number possible in JavaScript |
MIN_VALUE |
Returns the smallest number possible in JavaScript |
NEGATIVE_INFINITY |
Represents negative infinity (returned on overflow) |
NaN |
Represents a "Not-a-Number" value |
POSITIVE_INFINITY |
Represents infinity (returned on overflow) |
var x = Number.MAX_VALUE;
Number properties belongs to the JavaScript's number object wrapper called Number.
These properties can only be accessed as Number.MAX_VALUE.
Using myNumber.MAX_VALUE, where myNumber is a variable, expression, or value, will return undefined:
var x = 6;
var y = x.MAX_VALUE; // y becomes undefined
Number methods help you to work with numbers.
JavaScript global functions can be used on all JavaScript data types.
These are the most relevant methods, when working with numbers:
Method |
Description |
Number() |
Returns a number, converted from its argument. |
parseFloat() |
Parses its argument and returns a floating point number |
parseInt() |
Parses its argument and returns an integer |
JavaScript number methods are methods that can be used on numbers:
Method |
Description |
toString() |
Returns a number as a string |
toExponential() |
Returns a string, with a number rounded and written using exponential notation. |
toFixed() |
Returns a string, with a number rounded and written with a specified number of decimals. |
toPrecision() |
Returns a string, with a number written with a specified length |
valueOf() |
Returns a number as a number |
All number methods return a new variable. They do not change the original variable. |
toString() returns a number as a string.
All number methods can be used on any type of numbers, literals, variables, or expressions:
var x = 123;
x.toString(); // returns 123 from variable x
(123).toString(); // returns 123 from literal 123
(100 + 23).toString(); // returns 123 from expression 100 + 23
toExponential() returns a string, with a number rounded and written using exponential notation.
A parameter defines the number of character behind the decimal point:
var x = 9.656;
x.toExponential(2); // returns 9.66e+0
x.toExponential(4); // returns 9.6560e+0
x.toExponential(6); // returns 9.656000e+0
The parameter is optional. If you don't specify it, JavaScript will not round the number.
toFixed() returns a string, with the number written with a specified number of decimals:
var x = 9.656;
x.toFixed(0); // returns 10
x.toFixed(2); // returns 9.66
x.toFixed(4); // returns 9.6560
x.toFixed(6); // returns 9.656000
toFixed(2) is perfect for working with money. |
toPrecision() returns a string, with a number written with a specified length:
var x = 9.656;
x.toPrecision(); // returns 9.656
x.toPrecision(2); // returns 9.7
x.toPrecision(4); // returns 9.656
x.toPrecision(6); // returns 9.65600
There are 3 JavaScript functions that can be used to convert variables to numbers:
These methods are not number methods, but global JavaScript methods.
Number(), can be used to convert JavaScript variables to numbers:
x = true;
Number(x); // returns 1
x = false;
Number(x); // returns 0
x = new Date();
Number(x); // returns 1404568027739
x = "10"
Number(x); // returns 10
x = "10 20"
Number(x); // returns NaN
parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned:
parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("10 20 30"); // returns 10
parseInt("10 years"); // returns 10
parseInt("years 10"); // returns NaN
If the number cannot be converted, NaN (Not a Number) is returned.
parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned:
parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("10 20 30"); // returns 10
parseFloat("10 years"); // returns 10
parseFloat("years 10"); // returns NaN
If the number cannot be converted, NaN (Not a Number) is returned.
valueOf() returns a number as a number.
var x = 123;
x.valueOf(); // returns 123 from variable x
(123).valueOf(); // returns 123 from literal 123
(100 + 23).valueOf(); // returns 123 from expression 100 + 23
In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof = object).
The valueOf() method is used internally in JavaScript to convert Number objects to primitive values.
There is no reason to use it in your code.
In JavaScript, all data types have a valueOf() and a toString() method. |
= is used to assign values, + is used to add values, ++ is used to increment values.
The assignment operator = is used to assign values to JavaScript variables.
The arithmetic operator + is used to add values together.
Assign values to variables and add them together:
y = 5; // assign the value 5 to y
z = 2; // assign the value 2 to z
x = y + z; // assign the value 7 (y + z) to x
The result of x will be:
7
Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y = 5, the table below explains the arithmetic operators:
Operator |
Description |
Example |
Result |
Result |
Try it |
+ |
Addition |
x = y + 2 |
y = 5 |
x = 7 |
|
- |
Subtraction |
x = y - 2 |
y = 5 |
x = 3 |
|
* |
Multiplication |
x = y * 2 |
y = 5 |
x = 10 |
|
/ |
Division |
x = y / 2 |
y = 5 |
x = 2.5 |
|
% |
Modulus (division remainder) |
x = y % 2 |
y = 5 |
x = 1 |
|
++ |
Increment |
x = ++y |
y = 6 |
x = 6 |
|
x = y++ |
y = 6 |
x = 5 |
|||
-- |
Decrement |
x = --y |
y = 4 |
x = 4 |
|
x = y-- |
y = 4 |
x = 5 |
Assignment operators are used to assign values to JavaScript variables.
Given that x = 10 and y = 5, the table below explains the assignment operators:
Operator |
Example |
Same As |
Result |
Try it |