JavaScript Events

 

HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these events.

 

HTML Events

An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:

  • An HTML web page has finished loading
  • An HTML input field was changed
  • An HTML button was clicked

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:

Example

<button onclick='getElementById("demo").innerHTML=Date()'>The time is?</button>


Try it Yourself » 

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): 

Example

<button onclick="this.innerHTML=Date()">The time is?</button>


Try it Yourself » 

 

 

JavaScript code is often several lines long. It is more common to see event attributes calling functions:

 

Example

<button onclick="displayDate()">The time is?</button>


Try it Yourself » 

 

 

Common HTML Events

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.

 

What can JavaScript Do?

Event handlers can be used to handle, and verify, user input, user actions, and browser actions:

  • Things that should be done every time a page loads
  • Things that should be done when the page is closed
  • Action that should be performed when a user clicks a button
  • Content that should be verified when a user input data
  • And more ...

Many different methods can be used to let JavaScript work with events:

  • HTML event attributes can execute JavaScript code directly
  • HTML event attributes can call JavaScript functions
  • You can assign your own event handler functions to HTML elements
  • You can prevent events from being sent or being handled
  • And more ...
 

You will learn a lot more about events and event handlers in the HTML DOM chapters.

 

 

JavaScript Strings

« Previous

Next Chapter »

 

JavaScript strings are used for storing and manipulating text.

 

JavaScript Strings

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:

Example

var carname = "Volvo XC60";
var carname = 'Volvo XC60'; 


Try it yourself » 

You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

Example

var answer = "It's alright";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';


Try it yourself » 

Or you can put quotes inside a string by using the \ escape character:

Example

var answer = 'It\'s alright';
var answer = "He is called \"Johnny\""


Try it yourself » 

 

 

String Length

The length of a string (a string object) is found in the built in property length:

Example

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;


Try it Yourself » 

 

 

Special Characters

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

 

 

Strings Can be Objects

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")

Example

var x = "John";
var y = new String("John");

// type of x will return String
// type of y will return Object


Try it yourself »

 

Don't create String objects. They slow down execution speed, and produce nasty side effects:

Example

var x = "John";             
var y = new String("John");

// (x === y) is now false because x is a string and y is an object. 


Try it yourself » 

 

 

String Properties and Methods

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.

 

String Properties

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

 

 

String Methods

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

 

 

 

JavaScript String Methods

« Previous

Next Chapter »

 

String methods help you to work with strings.

 

Finding a String in a String

The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string:

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate"); 


Try it Yourself » 

The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate"); 


Try it Yourself » 

Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.

 

JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third ...

Both methods accept a second parameter as the starting position for the search.

 

Searching for a String in a String

The search() method searches a string for a specified value and returns the position of the match:

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate"); 


Try it Yourself » 

 

 

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.

 

Extracting String Parts

There are 3 methods for extracting a part of a string:

  • slice(start, end)
  • substring(start, end)
  • substr(start, length)

 

The slice() Method

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: 

Example

var str = "Apple, Banana, Kiwi";
var res = str.slice(7,13); 

The result of res will be:

Banana


Try it yourself » 

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: 

Example

var str = "Apple, Banana, Kiwi";
var res = str.slice(-12,-6); 

The result of res will be:

Banana


Try it yourself » 

If you omit the second parameter, the method will slice out the rest of the string:

Example

var res = str.slice(7); 


Try it yourself » 

or, counting from the end:

Example

var res = str.slice(-12); 


Try it yourself » 

 

Negative positions does not work in Internet Explorer 8 and earlier.

 

The substring() Method

substring() is similar to slice().

The difference is that substring() cannot accept negative indexes.

Example

var str = "Apple, Banana, Kiwi";
var res = str.substring(7,13); 

The result of res will be:

Banana


Try it yourself » 

If you omit the second parameter, substring() will slice out the rest of the string.

 

The substr() Method

substr() is similar to slice().

The difference is that the second parameter specifies the length of the extracted part.

Example

var str = "Apple, Banana, Kiwi";
var res = str.substr(7,6); 

The result of res will be:

Banana


Try it yourself » 

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.

 

Replacing String Content

The replace() method replaces a specified value with another value in a string:

Example

str = "Please visit Microsoft!";
var n = str.replace("Microsoft","W3Schools");


Try it Yourself » 

The replace() method can also take a regular expression as the search value.

 

Converting to Upper and Lower Case

A string is converted to upper case with toUpperCase():

Example

var text1 = "Hello World!";       // String
var text2 = text1.toUpperCase();  // text2 is text1 converted to upper


Try it Yourself » 

A string is converted to lower case with toLowerCase():

Example

var text1 = "Hello World!";       // String
var text2 = text1.toLowerCase();  // text2 is text1 converted to lower 


Try it Yourself » 

 

 

The concat() Method

concat() joins two or more strings:

Example

var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ",text2); 


Try it Yourself » 

The concat() method can be used instead of the plus operator. These two lines do the same:

Example

var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ","World!");

 

All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced. 

 

Extracting String Characters

There are 2 safe methods for extracting string characters:

  • charAt(position)
  • charCodeAt(position)

 

The charAt() Method

The charAt() method returns the character at a specified index (position) in a string:

Example

var str = "HELLO WORLD";
str.charAt(0);            // returns H 


Try it Yourself » 

 

 

The charCodeAt() Method

The charCodeAt() method returns the unicode of the character at a specified index in a string:

Example

var str = "HELLO WORLD";

str.charCodeAt(0);         // returns 72 


Try it Yourself » 

 

 

Accessing a String as an Array is Unsafe

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: 

  • It does not work in all browsers (not in IE5, IE6, IE7)
  • It makes strings look like arrays (but they are not)
  • str[0] = "H" does not give an error (but does not work) 

If you want to read a string as an array, convert it to an array first.

 

Converting a String to an Array

A string can be converted to an array with the split() method:

Example

var txt = "a,b,c,d,e";   // String
txt.split(",");          // Split on commas
txt.split(" ");          // Split on spaces
txt.split("|");          // Split on pipe 


Try it Yourself » 

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:

Example

var txt = "Hello";       // String
txt.split("");           // Split in characters 

 

 

 

JavaScript Numbers

« Previous

Next Chapter »

 

JavaScript has only one type of number.

Numbers can be written with, or without, decimals.

 

JavaScript Numbers

JavaScript numbers can be written with, or without decimals:

Example

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:

Example

var x = 123e5;    // 12300000
var y = 123e-5;   // 0.00123

 

 

JavaScript Numbers are Always 64-bit Floating Point

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)

 

 

Precision

Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits.

Example

var x = 999999999999999;   // x will be 999999999999999
var y = 9999999999999999;  // y will be 10000000000000000 


Try it yourself » 

The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate:

Example

var x = 0.2 + 0.1;         // x will be 0.30000000000000004


Try it yourself »

To solve the problem above, it helps to multiply and divide:

Example

var x = (0.2 * 10 + 0.1 * 10) / 10;       // x will be 0.3


Try it yourself » 

 

 

Hexadecimal

JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.

Example

var x = 0xFF;             // x will be 255 


Try it Yourself » 

 

 

Never write a number with a leading zero (like 07).
Some JavaScript versions interpret numbers as octal if they are written with a leading zero. 

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).

Example

var myNumber = 128;
myNumber.toString(16);     // returns 80
myNumber.toString(8);      // returns 200
myNumber.toString(2);      // returns 10000000


Try it Yourself » 

 

 

Infinity

Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.

Example

var myNumber = 2;
while (myNumber != Infinity) {          // Execute until Infinity
    myNumber = myNumber * myNumber;


Try it yourself »

Division by 0 (zero) also generates Infinity:

Example

var x =  2 / 0;          // x will be Infinity
var y = -2 / 0;          // y will be -Infinity 


Try it Yourself » 

Infinity is a number: typeOf Infinity returns number.

Example

typeof Infinity;        // returns "number"


Try it Yourself » 

 

 

NaN - Not a 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):

Example

var x = 100 / "Apple";  // x will be NaN (Not a Number)


Try it yourself »

However, if the string contains a numeric value , the result will be a number:

Example

var x = 100 / "10";     // x will be 10


Try it yourself » 

You can use the global JavaScript function isNaN() to find out if a value is a number.

Example

var x = 100 / "Apple";
isNaN(x);               // returns true because x is Not a Number 


Try it Yourself » 

Watch out for NaN. If you use NaN in a mathematical operation, the result will also be NaN. 

Example

var x = NaN;
var y = 5;
var z = x + y;         // z will be NaN 


Try it Yourself » 

NaN is a number: typeOf NaN returns number.

Example

typeof NaN;             // returns "number"


Try it Yourself » 

 

 

Numbers Can be Objects

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)

Example

var x = 123;
var y = new Number(123);

typeof x;               // returns number
typeof y;               // returns object 


Try it yourself »

 

Don't create Number objects. They slow down execution speed, and produce nasty side effects:

Example

var x = 123;              
var y = new Number(123);
(x === y) // is false because x is a number and y is an object. 


Try it yourself »

 

 

Number Properties and Methods

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.

 

Number 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)

 

Example

var x = Number.MAX_VALUE; 


Try it yourself » 

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:

Example

var x = 6;
var y = x.MAX_VALUE;    // y becomes undefined 

 

 

 

JavaScript Number Methods

« Previous

Next Chapter »

 

Number methods help you to work with numbers.

 

Global Methods

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

 

 

Number Methods

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.

 

The toString() Method

toString() returns a number as a string.

All number methods can be used on any type of numbers, literals, variables, or expressions:

Example

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 


Try it yourself » 

 

 

The toExponential() Method

toExponential() returns a string, with a number rounded and written using exponential notation.

A parameter defines the number of character behind the decimal point:

Example

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 


Try it yourself » 

The parameter is optional. If you don't specify it, JavaScript will not round the number.

 

The toFixed() Method

toFixed() returns a string, with the number written with a specified number of decimals:

Example

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 


Try it yourself »

 

toFixed(2) is perfect for working with money.

 

The toPrecision() Method

toPrecision() returns a string, with a number written with a specified length:

Example

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 


Try it yourself » 

 

 

Converting Variables to Numbers

There are 3 JavaScript functions that can be used to convert variables to numbers:

  • The Number() method
  • The parseInt() method
  • The parseFloat() method

These methods are not number methods, but global JavaScript methods.

 

The Number() Method

Number(), can be used to convert JavaScript variables to numbers:

Example

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 


Try it yourself » 

 

 

The parseInt() Method

parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned:

Example

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  


Try it yourself »

If the number cannot be converted, NaN (Not a Number) is returned.

 

The parseFloat() Method

parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned:

Example

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 


Try it yourself »

If the number cannot be converted, NaN (Not a Number) is returned.

 

The valueOf() Method

valueOf() returns a number as a number.

Example

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 


Try it yourself » 

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.

 

 

 

JavaScript Operators

« Previous

Next Chapter »

 

= 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.

Example

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:


Try it Yourself » 

 

 

JavaScript Arithmetic Operators

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

Try it »

-

Subtraction

x = y - 2

y = 5

x = 3

Try it »

*

Multiplication

x = y * 2

y = 5

x = 10

Try it »

/

Division

x = y / 2

y = 5

x = 2.5

Try it »

%

Modulus (division remainder)

x = y % 2

y = 5

x = 1

Try it »

++

Increment

x = ++y

y = 6

x = 6

Try it »

x = y++

y = 6

x = 5

Try it »

--

Decrement

x = --y

y = 4

x = 4

Try it »

x = y--

y = 4

x = 5

Try it »

 

 

JavaScript Assignment Operators

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