Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

JavaScript basics

Deze vertaling is niet volledig. Help dit artikel te vertalen vanuit het Engels.

Javascript is een programmeertaal die interactiviteit aan je website toevoegt.(bijvoorbeeld: spelletjes, dingen die gebeuren wanneer een knopje wordt ingedrukt, data die via formulieren wordt verwerkt, dynamisch toegepaste stijlen, animaties) Dit artikel helpt je om te beginnen met deze taal en geeft je een idee wat de mogelijkheden zijn.

Wat is JavaScript eigenlijk echt?

JavaScript ("JS" afgekort) is een complete dynamische programmeertaal  die je kan toepassen op een HTML document om interactie mogelijk te maken. Het is bedacht door Brendan Eich, mede-oprichter van het Mozilla project, de Mozilla foundation, en de Mozilla corporation.

Je kan zo'n beetje alles met JavaScript. Je zult beginnen met simpele toevoegingen zoals carousels, plaatjescollecties, veranderende layouts, en reacties op clicks. Wanneer je eenmaal wat meer ervaring hebt met de taal, zul je in staat zijn spelletjes te maken, geanimeerde 2d en 3d graphics, volledige database gestuurde apps, en nog veel meer!

JavaScript zelf is vrij compact maar erg flexibel. Ontwikkelaars hebben veel hulpmiddelen gemaakt bovenop de bestaande kern, waardoor een enorme hoeveelheid extra functionaliteit mogelijk is met relatief weinig moeite. Om er een paar te noemen:

  • Application Programming Interfaces (APIs) gebouwd in webbrowsers die webpagina's kunnen maken en CSS stijlen kunnen genereren. Of een videostream van de gebruikers' webcam onderscheppen en manipuleren, of het genereren van audio samples en 3d graphics.
  •  APIs van tussenpartijen die het ontwikkelaars mogelijk maken om functionaliteit van bijv. Facebook of Twitter toe te voegen.
  •  Frameworks en bibliotheken die je op je HTMl kan toepassen om snel sites en applicaties op te bouwen.

Een "hello world" voorbeeld

Het bovenste klinkt echt opwindend, en dat is het ook - JavaScript is een van de meest opwindende Web technologieën van het moment. Zo gauw je er wat beter in wordt zullen je sites een nieuwe dimensie van kracht en creativiteit krijgen.

Niettemin, JS is wat complexer om mee op je gemak te komen dan HTML en CSS, en je moet klein beginnen en er in kleine regelmatige stapjes aan blijven werken. Om te beginnen laten we zien hoe je wat JS aan je pagina toe kan voegen om ons "hello world" voorbeeld te maken.(het standaard voorbeeld in programmeertalen).

Belangrijk: Wanneer je nog niet de rest van deze cursus gevolgd hebt  download dan deze voorbeeld code  en gebruik het als een beginnetje. Bekijk de pagina in je browser alvorens verder te gaan.

  1. Ga naar de map scripts  van je test site en maak een nieuw bestand dat je main.js. noemt.  
  2. Open nu met een teksteditor index.html en voeg het volgend element toe, op een nieuwe regel net voor de sluitende </body> tag:
    <script src="scripts/main.js"></script>
  3. Dit doet feitelijk hetzelfde als het <link> element voor CSS — het past het JS toe op de pagina, zo dat het een effect kan hebben op de HTML (en CSS, en al het andere op de pagina)
  4. Voeg nu de volgende code toe aan je  main.js file:
    var myHeading = document.querySelector('h1');
    myHeading.textContent = 'Hello world!';
  5. Zorg nu dat je HTML en JavaScript files opgeslagen zijn en laad index.html in de browser. Je zou iets dergelijks moeten zien:

Noot: De reden dat we het <script> element bij de onderkant van HTML file hebben gezet is dat HTML in de browser wordt geladen in de volgorden dat het opgeschreven staat. Als het JS eerst wordt geladen en HTML eronder moet beïnvloeden, zou dat niet kunnen werken. Om deze reden is het vaak de beste strategie om JS bij de onderkant van de HTML te plaatsen.

What happened?

So, your heading text has been changed to "Hello world!" using JavaScript. We did this by first using a function called querySelector() to grab a reference to our heading, and store it in a variable called myHeading. This is very similar to what we did in CSS using selectors. When you want to do something to an element, first you need to select it.

After that, we set the value of the myHeading variable's textContent property (which represents the content of the heading) to "Hello world!".

Language basics crash course

Let's explain just some of the basic features of the JavaScript language, to give you some more understanding of how it all works. Better yet, these features are common to all programming languages. If you can understand these fundamentals, you should be able to start programming just about anything!

Important: In this article, try entering the example code lines into your JavaScript console to see what happens. For more details on JavaScript consoles, see Discover browser developer tools.

Variables

Variables are containers that you can store values in. You start by declaring a variable with the var keyword, followed by any name you want to call it:

var myVariable;

Note: All statements in JavaScript must end with a semi-colon, to indicate that this is where the statement ends. If you don't include these, you can get unexpected results.

Note: You can name a variable nearly anything, but there are some name restrictions (see this article on variable naming rules.) If you are unsure, you can check your variable name to see if it is valid.

Note: JavaScript is case sensitive — myVariable is a different variable to myvariable. If you are getting problems in your code, check the casing!

After declaring a variable, you can give it a value:

myVariable = 'Bob';

You can do both these operations on the same line if you wish:

var myVariable = 'Bob';

You can retrieve the value by just calling the variable by name:

myVariable;

After giving a variable a value, you can later choose to change it:

var myVariable = 'Bob';
myVariable = 'Steve';

Note that variables have different data types:

Variable Explanation Example
String A string of text. To signify that the variable is a string, you should enclose it in quote marks. var myVariable = 'Bob';
Number A number. Numbers don't have quotes around them. var myVariable = 10;
Boolean A True/False value. The words true and false are special keywords in JS, and don't need quotes. var myVariable = true;
Array A structure that allows you to store multiple values in one single reference. var myVariable = [1,'Bob','Steve',10];
Refer to each member of the array like this:
myVariable[0], myVariable[1], etc.
Object Basically, anything. Everything in JavaScript is an object, and can be stored in a variable. Keep this in mind as you learn. var myVariable = document.querySelector('h1');
All of the above examples too.

So why do we need variables? Well, variables are needed to do anything interesting in programming. If values couldn't change, then you couldn't do anything dynamic, like personalize a greeting message or change the image displayed in an image gallery.

Comments

You can put comments into JavaScript code, just like you can in CSS:

/*
Everything in between is a comment.
*/

If your comment contains no line breaks, it's often easier to put it behind two slashes like this:

// This is a comment

Operators

An operator is a mathematical symbol that produces a result based on two values (or variables). In the following table you can see some of the simplest operators, along with some examples to try out in the JavaScript console.

Operator Explanation Symbol(s) Example
add/concatenation Used to add two numbers together, or glue two strings together. + 6 + 9;
"Hello " + "world!";
subtract, multiply, divide These do what you'd expect them to do in basic math. -, *, / 9 - 3;
8 * 2; // multiply in JS is an asterisk
9 / 3;
assignment operator You've seen this already: it assigns a value to a variable. = var myVariable = 'Bob';
Identity operator Does a test to see if two values are equal to one another, and returns a true/false (Boolean) result. === var myVariable = 3;
myVariable === 4;
Negation, not equal Returns the logically opposite value of what it preceeds; it turns  a true into a false, etc. When it is used alongside the Equality operator, the negation operator tests whether two values are not equal. !, !==

The basic expression is true, but the comparison returns false because we've negated it:

var myVariable = 3;
!(myVariable === 3);

Here we are testing "is myVariable NOT equal to 3". This returns false because myVariable IS equal to 3.

var myVariable = 3;
myVariable !== 3;

There are a lot more operators to explore, but this will do for now. See Expressions and operators for a complete list.

Note: Mixing data types can lead to some strange results when performing calculations, so be careful that you are referring to your variables correctly, and getting the results you expect. For example, enter "35" + "25" into your console. Why don't you get the result you expected? Because the quote marks turn the numbers into strings, so you've ended up concatenating strings rather than adding numbers. If you enter, 35 + 25 you'll get the correct result.

Conditionals

Conditionals are code structures that allow you to test whether an expression returns true or not, and then run different code depending on the result. The most common form of conditional is called if ... else.  So for example:

var iceCream = 'chocolate';
if (iceCream === 'chocolate') {
  alert('Yay, I love chocolate ice cream!');    
} else {
  alert('Awwww, but chocolate is my favorite...');    
}

The expression inside the if ( ... ) is the test — this uses the identity operator (as described above) to compare the variable iceCream with the string chocolate to see if the two are equal. If this comparison returns true, run the first block of code. If not, skip that code and run the second block of code after the else statement.

Functions

Functions are a way of packaging functionality that you want to reuse, so that whenever you want the functionality you can call the function with the function name rather than constantly rewriting the entire code. You have already seen some uses of functions above, for example:

  1. var myVariable = document.querySelector('h1');
  2. alert('hello!');

These functions, document.querySelector and alert, are built into the browser for you to use whenever you like.

If you see something that looks like a variable name, but has brackets — () — after it, it is probably a function. Functions often take arguments — bits of data they need to do their job. These go inside the brackets, separated by commas if there is more than one item.

For example, the alert() function makes a pop-up box appear inside the browser window, but we need to give it a string as an argument to tell the function what to write in the pop-up box.

The good news is that you can define your own functions — in this next example we write a simple function that takes two numbers as arguments and multiplies them:

function multiply(num1,num2) {
  var result = num1 * num2;
  return result;
}

Try running the above function in the console, then try using your new function a few times, e.g.:

multiply(4,7);
multiply(20,20);
multiply(0.5,3);

Note: The return statement tells the browser to return the result variable out of the function so it is available to use. This is necessary because variables defined inside functions are only available inside those functions. This is called variable scoping. (Read more on variable scoping.)

Events

To create real interactivity on a website, you need events — these are code structures that listen out for things happening to the browser, and then allow you to run code in response to those things. The most obvious example is the click event, which is fired by the browser when the mouse clicks on something. To demonstrate this, try entering the following into your console, then clicking on the current webpage:

document.querySelector('html').onclick = function() {
    alert('Ouch! Stop poking me!');
}

There are many ways to attach an event to an element. Here we are selecting the HTML element and setting its onclick handler property equal to an anonymous (i.e. nameless) function that contains the code we want to run when the click event occurs.

Note that

document.querySelector('html').onclick = function() {};

is equivalent to

var myHTML = document.querySelector('html');
myHTML.onclick = function() {};

It's just shorter.

Supercharging our example website

Now that we've gone over a few JavaScript basics, let's add a few cool basic features to our example site to give you some first idea of what is possible.

Adding an image changer

In this section, we'll add another image to our site, and add some simple JavaScript to change between the two when the image is clicked on.

  1. First of all, find another image that you'd like to feature on your site. Make sure it is the same size as your first image, or as close as possible.
  2. Save the image in your images folder.
  3. Go to your main.js file, and enter the following JavaScript. (If your "hello world" JavaScript is still there, delete it.)
    var myImage = document.querySelector('img');
    
    myImage.onclick = function() {
        var mySrc = myImage.getAttribute('src');
        if(mySrc === 'images/firefox-icon.png') {
          myImage.setAttribute ('src','images/firefox2.png');
        } else {
          myImage.setAttribute ('src','images/firefox-icon.png');
        }
    }
  4. Save all files and load index.html in the browser. Now when you click the image, it should change to the other one!

So here, we are storing a reference to our image element in the myImage variable. Next, we make this variable's onclick event handler property equal to a function with no name (an "anonymous" function). Now, every time this image element is clicked:

  1. We retrieve the value of the image's src attribute.
  2. We use a conditional to check whether the src value is equal to the path to the original image:
    1. If it is, we change the src value to the path to the 2nd image, forcing the other image to be loaded inside the <image> element.
    2. If it isn't (meaning it must already have changed), we change the src value back to the original image path, to flip it back to how it was originally.

Adding a personalized welcome message

Next we will add another bit of code, to change the page's title to include a personalized welcome message when the user first navigates to the site. This welcome message will persist when the user leaves the site and then comes back. We will also include an option to change the user and, therefore, the welcome message anytime it is required.

  1. In index.html, add the following line just before the <script> element:
    <button>Change user</button>
  2. In main.js, add the following code at the bottom of the file, exactly as written — this grabs references to the new button we added and the heading, and stores them in variables:
    var myButton = document.querySelector('button');
    var myHeading = document.querySelector('h1');
  3. Now add the following function to set the personalized greeting — this won't do anything yet, but we'll use it later on:
    function setUserName() {
      var myName = prompt('Please enter your name.');
      localStorage.setItem('name', myName);
      myHeading.textContent = 'Mozilla is cool, ' + myName;
    }
    This function contains a prompt() function, which brings up a dialog box, a bit like alert() except that prompt() asks the user to enter some data, and stores that data in a variable after the user presses OK. In this case, we are asking the user to enter their name. Next, we call on an API called localStorage, which allows us to store data in the browser and retrieve it later on. We use localStorage's setItem() function to create and store a data item called 'name', and set its value to the myName variable that contains the name the user entered. Finally, we set the textContent of the heading to a string, plus the user's name.
  4. Next, add this if ... else block — we could call this the initialization code, as it sets up the app when it first loads:
    if(!localStorage.getItem('name')) {
      setUserName();
    } else {
      var storedName = localStorage.getItem('name');
      myHeading.textContent = 'Mozilla is cool, ' + storedName;
    }
    This block first uses the negation operator (logical NOT) to check whether the name data item exists. If not, the setUserName() function is run to create it. If so (that is, the user set it during a previous visit), we retrieve the stored name using getItem() and set the textContent of the heading to a string, plus the user's name, the same as we did inside setUserName().
  5. Finally, put the below onclick event handler on the button, so that when clicked the setUserName() function is run. This allows the user to set a new name whenever they want by pressing the button:
    myButton.onclick = function() {
      setUserName();
    }
    

Now when you first visit the site, it'll ask you for your username then give you a personalized message. You can then change the name any time you like by pressing the button. As an added bonus, because the name is stored inside localStorage, it persists after the site is closed down, so the personalized message will still be there when you open the site up again!

Conclusion

If you have followed all the instructions in this article, you should end up with a page that looks something like this (you can also view our version here):

If you get stuck, you can always compare your work with our finished example code on Github.

Here, we have only really scratched the surface of JavaScript. If you have enjoyed learning about it and want to go deeper with your studies, go to our JavaScript Guide.

Documentlabels en -medewerkers

 Aan deze pagina hebben bijgedragen: apreinders
 Laatst bijgewerkt door: apreinders,