- Application programming interfaces (APIs) implemented in browsers to extend them with JS functions, z.B. dynamically creating HTML or setting a CSS style, intercepting and manipulating video streams, creating 3D graphics/audio samples, and more.
- Third-party APIs that allow developers to embed features from other sites into their own pages, z.B. from Twitter or Facebook.
- Third-party frameworks and libraries that can be added to HTML, which allow web pages and apps to be created quickly.
A "Hello World!" Example
IMPORTANTIf you haven’t followed the previous course this far, download this code sample and use it as a starter.
- First, go to your test page and create a new file named main.js . Save this file in your scripts folder.
- Then go to the index.html file and add the following element in a new line before the closing</body>- Tag on:
Then we set the value of the property textContent of the variable myHeading (which represents the content of the heading) to "Hello world!".
Hint: Both functions you used are parts of the Document Object Model (DOM) API
Programming crash course
Variables are containers in which values can be stored. First, a variable is declared with the keyword var, followed by some name under which this variable should be addressed:
NoteYou can name a variable almost any way you want, but there are some restrictions to keep in mind (see this article about the rules of naming variables).) If you are unsure, you can check the variable name to check validity.
After a variable is declared, you can give it a value:
Both steps (declaring a variable and assigning a value to it) can be combined in one step:
You can retrieve the value of the variable by calling the variable name:
After a value is given to the variable, it can be changed later:
Note that variables have different data types:
A structure that allows you to store multiple values in a single reference.
Why are variables needed? Well, variables are needed to cover everything interesting in programming. If values couldn’t change, then nothing dynamic could be created, such as personalizing a welcome message or an image displayed in an image gallery.
If the comment does not contain line breaks, then it is often easier to place it after two slashes:
Checks two values for equality and returns true / false (Boolean) as result
Returns the logical opposite as a result; turns a true into a false, etc. In conjunction with the equality operator, it checks whether two values are unequal.
The base expression is true , but the comparison returns false because it was negated:
var myVariable = 3;
!(myVariable === 3);
Here’s how to check if myVariable is not equal to 3. The return value is false because myVariable has the value 3.
var myVariable = 3;
myVariable !== 3;
There are many more operators to discover, but enough for now. A complete list can be found in Expressions and Operators.
NoteMixing data types can give unexpected results in calculations. Be sure to use the variables correctly and check that the expected result is returned. For example, type "35 + "25" in the console and look at the result. Did you expect this? Because of the quotes, the values are treated as strings and thus joined instead of added together. If you type 35 + 25, you get the expected result.
Conditions are code structures that allow you to check whether an expression is true or false and execute different code depending on the result. The most common type of conditions are if . else. For example:
The expression inside the if ( . ) is the test – this uses the equality operator (as described above) to compare the variable eis with the string S chokolade to see if the values are identical. If this comparison returns true , the first block of code will be executed. If not, this code is skipped and the second block after the else command is executed.
Functions (en-US) is a way to pack together functionalities that should be reused. Whenever the functionality is needed, the function is called by its name instead of having to rewrite the same code over and over again. You’ve already seen some uses of functions, for example:
The functions document.querySelector and alert are embedded in the browser to be used whenever it fits.
If you see something that looks like a variable name, but is enclosed in round brackets – () – it might be a function. Functions often take arguments to ensure functionality. These arguments are placed inside the round brackets and separated by commas if more than one argument is passed in.
For example, the alert() function creates a pop-up box inside the browser window. This function must be passed a string as an argument to tell the function what to write in this pop-up box.
The good news is that you can define your own functions. In the next example, we write a simple function that takes two numbers as arguments and multiplies them:
Try running this function in the console, then try calling your new function several times:
Note: The return command tells the browser to return the result variable from the function. So it is possible to use it. This is necessary because variables used inside the function are only valid there. This behavior is called scoping. (Read more about the scope of variables.)
To create real interactivity on a website, events are needed – these are code structures that listen for events happening in the browser and then allow you to execute code to react to these events. The most obvious example is the click event fired by the browser when you click the mouse pointer on something. To show this, type the following code into the console and click on the current web page:
There are many ways to associate an event with an element. Here we select the element HTML and set the property of the onclick handler equal to an anonymous (nameless) function containing the code we want to execute when the event happens.
is equivalent to
It’s just shorter.
Dynamic content for our example website
- First pick a second image for your web page. It should preferably be the same size as the image you already have on the website.
- Save this image in your images folder.
- Change the name of the image to something you can easily remember, we have it ‘firefox2.called ‘png.
We create the variable myImage and store in it a reference to our image element( img ). Next we set the onclick -event of this variable equal to a function without name (aanonymous Function). This function says what should happen each time the image is clicked:
- We get the value of the src attribute from our image.
- We use an if -condition to check if the src -value is the same as the path of our original image:
- If the condition is true, we change the src value to the path of the second image, so that this image is now included in our<image> -element is loaded.
- If the condition is false (i.e. the image has already been clicked and changed), we change the src value back to the path of the first image, so that when the mouse is clicked again, the original image appears again.
A personal welcome
Next, we add a personal welcome to our website, which can be changed by the user when visiting the site for the first time. The change should be preserved even if the user leaves the page and comes back later. We will also have an option to change the user so that the greeting is changed accordingly.
In the index.html -file and insert it directly before the<script> (en-US) element, enter the following line of code:
If you open your page in the browser now, the first time you visit, you will be asked for your name and the welcome will be personalized. You can change the name at any time by pressing the button. The personalized welcome is also displayed again when you leave the page and then return to it, because the name is stored in localStorage , in your browser!
If you followed the instructions in this article, you should now have a website that looks similar to this one (check out our version):
If you don’t have the same result and can’t find a solution (try to get it working yourself first), then you can check out our code on Github.