title
stringlengths 2
136
| text
stringlengths 20
75.4k
|
---|---|
Object prototypes - Learn web development | Object prototypes
=================
* Previous
* Overview: Objects
* Next
Prototypes are the mechanism by which JavaScript objects inherit features from one another. In this article, we explain what a prototype is, how prototype chains work, and how a prototype for an object can be set.
| | |
| --- | --- |
| Prerequisites: |
Understanding JavaScript functions, familiarity with JavaScript basics
(see
First steps and
Building blocks), and OOJS basics (see
Introduction to objects).
|
| Objective: |
To understand JavaScript object prototypes, how prototype chains work,
and how to set the prototype of an object.
|
The prototype chain
-------------------
In the browser's console, try creating an object literal:
```js
const myObject = {
city: "Madrid",
greet() {
console.log(`Greetings from ${this.city}`);
},
};
myObject.greet(); // Greetings from Madrid
```
This is an object with one data property, `city`, and one method, `greet()`. If you type the object's name *followed by a period* into the console, like `myObject.`, then the console will pop up a list of all the properties available to this object. You'll see that as well as `city` and `greet`, there are lots of other properties!
```
__defineGetter__
__defineSetter__
__lookupGetter__
__lookupSetter__
__proto__
city
constructor
greet
hasOwnProperty
isPrototypeOf
propertyIsEnumerable
toLocaleString
toString
valueOf
```
Try accessing one of them:
```js
myObject.toString(); // "[object Object]"
```
It works (even if it's not obvious what `toString()` does).
What are these extra properties, and where do they come from?
Every object in JavaScript has a built-in property, which is called its **prototype**. The prototype is itself an object, so the prototype will have its own prototype, making what's called a **prototype chain**. The chain ends when we reach a prototype that has `null` for its own prototype.
**Note:** The property of an object that points to its prototype is **not** called `prototype`. Its name is not standard, but in practice all browsers use `__proto__`. The standard way to access an object's prototype is the `Object.getPrototypeOf()` method.
When you try to access a property of an object: if the property can't be found in the object itself, the prototype is searched for the property. If the property still can't be found, then the prototype's prototype is searched, and so on until either the property is found, or the end of the chain is reached, in which case `undefined` is returned.
So when we call `myObject.toString()`, the browser:
* looks for `toString` in `myObject`
* can't find it there, so looks in the prototype object of `myObject` for `toString`
* finds it there, and calls it.
What is the prototype for `myObject`? To find out, we can use the function `Object.getPrototypeOf()`:
```js
Object.getPrototypeOf(myObject); // Object { }
```
This is an object called `Object.prototype`, and it is the most basic prototype, that all objects have by default. The prototype of `Object.prototype` is `null`, so it's at the end of the prototype chain:
![Prototype chain for myObject](/en-US/docs/Learn/JavaScript/Objects/Object_prototypes/myobject-prototype-chain.svg)
The prototype of an object is not always `Object.prototype`. Try this:
```js
const myDate = new Date();
let object = myDate;
do {
object = Object.getPrototypeOf(object);
console.log(object);
} while (object);
// Date.prototype
// Object { }
// null
```
This code creates a `Date` object, then walks up the prototype chain, logging the prototypes. It shows us that the prototype of `myDate` is a `Date.prototype` object, and the prototype of *that* is `Object.prototype`.
![Prototype chain for myDate](/en-US/docs/Learn/JavaScript/Objects/Object_prototypes/mydate-prototype-chain.svg)
In fact, when you call familiar methods, like `myDate2.getMonth()`,
you are calling a method that's defined on `Date.prototype`.
Shadowing properties
--------------------
What happens if you define a property in an object, when a property with the same name is defined in the object's prototype? Let's see:
```js
const myDate = new Date(1995, 11, 17);
console.log(myDate.getYear()); // 95
myDate.getYear = function () {
console.log("something else!");
};
myDate.getYear(); // 'something else!'
```
This should be predictable, given the description of the prototype chain. When we call `getYear()` the browser first looks in `myDate` for a property with that name, and only checks the prototype if `myDate` does not define it. So when we add `getYear()` to `myDate`, then the version in `myDate` is called.
This is called "shadowing" the property.
Setting a prototype
-------------------
There are various ways of setting an object's prototype in JavaScript, and here we'll describe two: `Object.create()` and constructors.
### Using Object.create
The `Object.create()` method creates a new object and allows you to specify an object that will be used as the new object's prototype.
Here's an example:
```js
const personPrototype = {
greet() {
console.log("hello!");
},
};
const carl = Object.create(personPrototype);
carl.greet(); // hello!
```
Here we create an object `personPrototype`, which has a `greet()` method. We then use `Object.create()` to create a new object with `personPrototype` as its prototype. Now we can call `greet()` on the new object, and the prototype provides its implementation.
### Using a constructor
In JavaScript, all functions have a property named `prototype`. When you call a function as a constructor, this property is set as the prototype of the newly constructed object (by convention, in the property named `__proto__`).
So if we set the `prototype` of a constructor, we can ensure that all objects created with that constructor are given that prototype:
```js
const personPrototype = {
greet() {
console.log(`hello, my name is ${this.name}!`);
},
};
function Person(name) {
this.name = name;
}
Object.assign(Person.prototype, personPrototype);
// or
// Person.prototype.greet = personPrototype.greet;
```
Here we create:
* an object `personPrototype`, which has a `greet()` method
* a `Person()` constructor function which initializes the name of the person to create.
We then put the methods defined in `personPrototype` onto the `Person` function's `prototype` property using Object.assign.
After this code, objects created using `Person()` will get `Person.prototype` as their prototype, which automatically contains the `greet` method.
```js
const reuben = new Person("Reuben");
reuben.greet(); // hello, my name is Reuben!
```
This also explains why we said earlier that the prototype of `myDate` is called `Date.prototype`: it's the `prototype` property of the `Date` constructor.
### Own properties
The objects we create using the `Person` constructor above have two properties:
* a `name` property, which is set in the constructor, so it appears directly on `Person` objects
* a `greet()` method, which is set in the prototype.
It's common to see this pattern, in which methods are defined on the prototype, but data properties are defined in the constructor. That's because methods are usually the same for every object we create, while we often want each object to have its own value for its data properties (just as here where every person has a different name).
Properties that are defined directly in the object, like `name` here, are called **own properties**, and you can check whether a property is an own property using the static `Object.hasOwn()` method:
```js
const irma = new Person("Irma");
console.log(Object.hasOwn(irma, "name")); // true
console.log(Object.hasOwn(irma, "greet")); // false
```
**Note:** You can also use the non-static `Object.hasOwnProperty()` method here, but we recommend that you use `Object.hasOwn()` if you can.
Prototypes and inheritance
--------------------------
Prototypes are a powerful and very flexible feature of JavaScript, making it possible to reuse code and combine objects.
In particular they support a version of **inheritance**. Inheritance is a feature of object-oriented programming languages that lets programmers express the idea that some objects in a system are more specialized versions of other objects.
For example, if we're modeling a school, we might have *professors* and *students*: they are both *people*, so have some features in common (for example, they both have names), but each might add extra features (for example, professors have a subject that they teach), or might implement the same feature in different ways. In an OOP system we might say that professors and students both **inherit from** people.
You can see how in JavaScript, if `Professor` and `Student` objects can have `Person` prototypes, then they can inherit the common properties, while adding and redefining those properties which need to differ.
In the next article we'll discuss inheritance along with the other main features of object-oriented programming languages, and see how JavaScript supports them.
Summary
-------
This article has covered JavaScript object prototypes, including how prototype object chains allow objects to inherit features from one another, the prototype property and how it can be used to add methods to constructors, and other related topics.
In the next article we'll look at the concepts underlying object-oriented programming.
* Previous
* Overview: Objects
* Next |
Object-oriented programming - Learn web development | Object-oriented programming
===========================
* Previous
* Overview: Objects
* Next
Object-oriented programming (OOP) is a programming paradigm fundamental to many programming languages, including Java and C++. In this article, we'll provide an overview of the basic concepts of OOP. We'll describe three main concepts: **classes and instances**, **inheritance**, and **encapsulation**. For now, we'll describe these concepts without reference to JavaScript in particular, so all the examples are given in pseudocode.
**Note:** To be precise, the features described here are of a particular style of OOP called **class-based** or "classical" OOP. When people talk about OOP, this is generally the type that they mean.
After that, in JavaScript, we'll look at how constructors and the prototype chain relate to these OOP concepts, and how they differ. In the next article, we'll look at some additional features of JavaScript that make it easier to implement object-oriented programs.
| | |
| --- | --- |
| Prerequisites: |
Understanding JavaScript functions, familiarity with JavaScript basics
(see
First steps and
Building blocks), and OOJS basics (see
Introduction to objects and Object prototypes).
|
| Objective: | To understand the basic concepts of class-based object-oriented programming. |
Object-oriented programming is about modeling a system as a collection of objects, where each object represents some particular aspect of the system. Objects contain both functions (or methods) and data. An object provides a public interface to other code that wants to use it but maintains its own private, internal state; other parts of the system don't have to care about what is going on inside the object.
Classes and instances
---------------------
When we model a problem in terms of objects in OOP, we create abstract definitions representing the types of objects we want to have in our system. For example, if we were modeling a school, we might want to have objects representing professors. Every professor has some properties in common: they all have a name and a subject that they teach. Additionally, every professor can do certain things: they can all grade a paper and they can introduce themselves to their students at the start of the year, for example.
So `Professor` could be a **class** in our system. The definition of the class lists the data and methods that every professor has.
In pseudocode, a `Professor` class could be written like this:
```
class Professor
properties
name
teaches
methods
grade(paper)
introduceSelf()
```
This defines a `Professor` class with:
* two data properties: `name` and `teaches`
* two methods: `grade()` to grade a paper and `introduceSelf()` to introduce themselves.
On its own, a class doesn't do anything: it's a kind of template for creating concrete objects of that type. Each concrete professor we create is called an **instance** of the `Professor` class. The process of creating an instance is performed by a special function called a **constructor**. We pass values to the constructor for any internal state that we want to initialize in the new instance.
Generally, the constructor is written out as part of the class definition, and it usually has the same name as the class itself:
```
class Professor
properties
name
teaches
constructor
Professor(name, teaches)
methods
grade(paper)
introduceSelf()
```
This constructor takes two parameters, so we can initialize the `name` and `teaches` properties when we create a new concrete professor.
Now that we have a constructor, we can create some professors. Programming languages often use the keyword `new` to signal that a constructor is being called.
```js
walsh = new Professor("Walsh", "Psychology");
lillian = new Professor("Lillian", "Poetry");
walsh.teaches; // 'Psychology'
walsh.introduceSelf(); // 'My name is Professor Walsh and I will be your Psychology professor.'
lillian.teaches; // 'Poetry'
lillian.introduceSelf(); // 'My name is Professor Lillian and I will be your Poetry professor.'
```
This creates two objects, both instances of the `Professor` class.
Inheritance
-----------
Suppose in our school we also want to represent students. Unlike professors, students can't grade papers, don't teach a particular subject, and belong to a particular year.
However, students do have a name and may also want to introduce themselves, so we might write out the definition of a student class like this:
```
class Student
properties
name
year
constructor
Student(name, year)
methods
introduceSelf()
```
It would be helpful if we could represent the fact that students and professors share some properties, or more accurately, the fact that on some level, they are the *same kind of thing*. **Inheritance** lets us do this.
We start by observing that students and professors are both people, and people have names and want to introduce themselves. We can model this by defining a new class `Person`, where we define all the common properties of people. Then, `Professor` and `Student` can both **derive** from `Person`, adding their extra properties:
```
class Person
properties
name
constructor
Person(name)
methods
introduceSelf()
class Professor : extends Person
properties
teaches
constructor
Professor(name, teaches)
methods
grade(paper)
introduceSelf()
class Student : extends Person
properties
year
constructor
Student(name, year)
methods
introduceSelf()
```
In this case, we would say that `Person` is the **superclass** or **parent class** of both `Professor` and `Student`. Conversely, `Professor` and `Student` are **subclasses** or **child classes** of `Person`.
You might notice that `introduceSelf()` is defined in all three classes. The reason for this is that while all people want to introduce themselves, the way they do so is different:
```js
walsh = new Professor("Walsh", "Psychology");
walsh.introduceSelf(); // 'My name is Professor Walsh and I will be your Psychology professor.'
summers = new Student("Summers", 1);
summers.introduceSelf(); // 'My name is Summers and I'm in the first year.'
```
We might have a default implementation of `introduceSelf()` for people who aren't students *or* professors:
```js
pratt = new Person("Pratt");
pratt.introduceSelf(); // 'My name is Pratt.'
```
This feature - when a method has the same name but a different implementation in different classes - is called **polymorphism**. When a method in a subclass replaces the superclass's implementation, we say that the subclass **overrides** the version in the superclass.
Encapsulation
-------------
Objects provide an interface to other code that wants to use them but maintain their own internal state. The object's internal state is kept **private**, meaning that it can only be accessed by the object's own methods, not from other objects. Keeping an object's internal state private, and generally making a clear division between its public interface and its private internal state, is called **encapsulation**.
This is a useful feature because it enables the programmer to change the internal implementation of an object without having to find and update all the code that uses it: it creates a kind of firewall between this object and the rest of the system.
For example, suppose students are allowed to study archery if they are in the second year or above. We could implement this just by exposing the student's `year` property, and other code could examine that to decide whether the student can take the course:
```js
if (student.year > 1) {
// allow the student into the class
}
```
The problem is, if we decide to change the criteria for allowing students to study archery - for example by also requiring the parent or guardian to give their permission - we'd need to update every place in our system that performs this test. It would be better to have a `canStudyArchery()` method on `Student` objects, that implements the logic in one place:
```
class Student : extends Person
properties
year
constructor
Student(name, year)
methods
introduceSelf()
canStudyArchery() { return this.year > 1 }
```
```js
if (student.canStudyArchery()) {
// allow the student into the class
}
```
That way, if we want to change the rules about studying archery, we only have to update the `Student` class, and all the code using it will still work.
In many OOP languages, we can prevent other code from accessing an object's internal state by marking some properties as `private`. This will generate an error if code outside the object tries to access them:
```
class Student : extends Person
properties
private year
constructor
Student(name, year)
methods
introduceSelf()
canStudyArchery() { return this.year > 1 }
student = new Student('Weber', 1)
student.year // error: 'year' is a private property of Student
```
In languages that don't enforce access like this, programmers use naming conventions, such as starting the name with an underscore, to indicate that the property should be considered private.
OOP and JavaScript
------------------
In this article, we've described some of the basic features of class-based object-oriented programming as implemented in languages like Java and C++.
In the two previous articles, we looked at a couple of core JavaScript features: constructors and prototypes. These features certainly have some relation to some of the OOP concepts described above.
* **constructors** in JavaScript provide us with something like a class definition, enabling us to define the "shape" of an object, including any methods it contains, in a single place. But prototypes can be used here, too. For example, if a method is defined on a constructor's `prototype` property, then all objects created using that constructor get that method via their prototype, and we don't need to define it in the constructor.
* **the prototype chain** seems like a natural way to implement inheritance. For example, if we can have a `Student` object whose prototype is `Person`, then it can inherit `name` and override `introduceSelf()`.
But it's worth understanding the differences between these features and the "classical" OOP concepts described above. We'll highlight a couple of them here.
First, in class-based OOP, classes and objects are two separate constructs, and objects are always created as instances of classes. Also, there is a distinction between the feature used to define a class (the class syntax itself) and the feature used to instantiate an object (a constructor). In JavaScript, we can and often do create objects without any separate class definition, either using a function or an object literal. This can make working with objects much more lightweight than it is in classical OOP.
Second, although a prototype chain looks like an inheritance hierarchy and behaves like it in some ways, it's different in others. When a subclass is instantiated, a single object is created which combines properties defined in the subclass with properties defined further up the hierarchy. With prototyping, each level of the hierarchy is represented by a separate object, and they are linked together via the `__proto__` property. The prototype chain's behavior is less like inheritance and more like **delegation**. Delegation is a programming pattern where an object, when asked to perform a task, can perform the task itself or ask another object (its **delegate**) to perform the task on its behalf. In many ways, delegation is a more flexible way of combining objects than inheritance (for one thing, it's possible to change or completely replace the delegate at run time).
That said, constructors and prototypes can be used to implement class-based OOP patterns in JavaScript. But using them directly to implement features like inheritance is tricky, so JavaScript provides extra features, layered on top of the prototype model, that map more directly to the concepts of class-based OOP. These extra features are the subject of the next article.
Summary
-------
This article has described the basic features of class-based object oriented programming, and briefly looked at how JavaScript constructors and prototypes compare with these concepts.
In the next article, we'll look at the features JavaScript provides to support class-based object-oriented programming.
* Previous
* Overview: Objects
* Next |
Test your skills: Object basics - Learn web development | Test your skills: Object basics
===============================
The aim of this skill test is to assess whether you've understood our JavaScript object basics article.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If there is an error in your code, it will be logged into the results panel on this page or in the JavaScript console.
If you get stuck, you can reach out to us in one of our communication channels.
Object basics 1
---------------
In this task you are provided with an object literal, and your tasks are to
* Store the value of the `name` property inside the `catName` variable, using bracket notation.
* Run the `greeting()` method using dot notation (it will log the greeting to the browser's console).
* Update the `color` property value to `black`.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Object basics 2
---------------
In our next task, we want you to have a go at creating your own object literal to represent one of your favorite bands. The required properties are:
* `name`: A string representing the band name.
* `nationality`: A string representing the country the band comes from.
* `genre`: What type of music the band plays.
* `members`: A number representing the number of members the band has.
* `formed`: A number representing the year the band formed.
* `split`: A number representing the year the band split up, or `false` if they are still together.
* `albums`: An array representing the albums released by the band. Each array item should be an object containing the following members:
+ `name`: A string representing the name of the album.
+ `released`: A number representing the year the album was released.
Include at least two albums in the `albums` array.
Once you've done this, you should then write a string to the variable `bandInfo`, which will contain a small biography detailing their name, nationality, years active, and style, and the title and release date of their first album.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Object basics 3
---------------
In this task, we want you to return to the `cat` object literal from Task 1. We want you to rewrite the `greeting()` method so that it logs `"Hello, said Bertie the Cymric."` to the browser's console, but in a way that will work across *any* cat object of the same structure, regardless of its name or breed.
When you are done, write your own object called `cat2`, which has the same structure, exactly the same `greeting()` method, but a different `name`, `breed`, and `color`.
Call both `greeting()` methods to check that they log appropriate greetings to the console.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Object basics 4
---------------
In the code you wrote for Task 3, the `greeting()` method is defined twice, once for each cat. This isn't ideal (specifically, it violates a principle in programming sometimes called DRY or "Don't Repeat Yourself").
In this task we want you to improve the code so `greeting()` is only defined once, and every `cat` instance gets its own `greeting()` method. Hint: you should use a JavaScript constructor to create `cat` instances.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
JavaScript object basics - Learn web development | JavaScript object basics
========================
* Overview: Objects
* Next
In this article, we'll look at fundamental JavaScript object syntax, and revisit some JavaScript features that we've already seen earlier in the course, reiterating the fact that many of the features you've already dealt with are objects.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of HTML and CSS,
familiarity with JavaScript basics (see
First steps and
Building blocks).
|
| Objective: | To understand the basics of working with objects in JavaScript: creating objects, accessing and modifying object properties, and using constructors. |
Object basics
-------------
An object is a collection of related data and/or functionality.
These usually consist of several variables and functions (which are called properties and methods when they are inside objects).
Let's work through an example to understand what they look like.
To begin with, make a local copy of our oojs.html file. This contains very little β a `<script>` element for us to write our source code into. We'll use this as a basis for exploring basic object syntax. While working with this example you should have your developer tools JavaScript console open and ready to type in some commands.
As with many things in JavaScript, creating an object often begins with defining and initializing a variable. Try entering the following line below the JavaScript code that's already in your file, then saving and refreshing:
```js
const person = {};
```
Now open your browser's JavaScript console, enter `person` into it, and press `Enter`/`Return`. You should get a result similar to one of the below lines:
```
[object Object]
Object { }
{ }
```
Congratulations, you've just created your first object. Job done! But this is an empty object, so we can't really do much with it. Let's update the JavaScript object in our file to look like this:
```js
const person = {
name: ["Bob", "Smith"],
age: 32,
bio: function () {
console.log(`${this.name[0]} ${this.name[1]} is ${this.age} years old.`);
},
introduceSelf: function () {
console.log(`Hi! I'm ${this.name[0]}.`);
},
};
```
After saving and refreshing, try entering some of the following into the JavaScript console on your browser devtools:
```js
person.name;
person.name[0];
person.age;
person.bio();
// "Bob Smith is 32 years old."
person.introduceSelf();
// "Hi! I'm Bob."
```
You have now got some data and functionality inside your object, and are now able to access them with some nice simple syntax!
So what is going on here? Well, an object is made up of multiple members, each of which has a name (e.g. `name` and `age` above), and a value (e.g. `['Bob', 'Smith']` and `32`). Each name/value pair must be separated by a comma, and the name and value in each case are separated by a colon. The syntax always follows this pattern:
```js
const objectName = {
member1Name: member1Value,
member2Name: member2Value,
member3Name: member3Value,
};
```
The value of an object member can be pretty much anything β in our person object we've got a number, an array, and two functions. The first two items are data items, and are referred to as the object's **properties**. The last two items are functions that allow the object to do something with that data, and are referred to as the object's **methods**.
When the object's members are functions there's a simpler syntax. Instead of `bio: function ()` we can write `bio()`. Like this:
```js
const person = {
name: ["Bob", "Smith"],
age: 32,
bio() {
console.log(`${this.name[0]} ${this.name[1]} is ${this.age} years old.`);
},
introduceSelf() {
console.log(`Hi! I'm ${this.name[0]}.`);
},
};
```
From now on, we'll use this shorter syntax.
An object like this is referred to as an **object literal** β we've literally written out the object contents as we've come to create it. This is different compared to objects instantiated from classes, which we'll look at later on.
It is very common to create an object using an object literal when you want to transfer a series of structured, related data items in some manner, for example sending a request to the server to be put into a database. Sending a single object is much more efficient than sending several items individually, and it is easier to work with than an array, when you want to identify individual items by name.
Dot notation
------------
Above, you accessed the object's properties and methods using **dot notation**. The object name (person) acts as the **namespace** β it must be entered first to access anything inside the object. Next you write a dot, then the item you want to access β this can be the name of a simple property, an item of an array property, or a call to one of the object's methods, for example:
```js
person.age;
person.bio();
```
### Objects as object properties
An object property can itself be an object. For example, try changing the `name` member from
```js
const person = {
name: ["Bob", "Smith"],
};
```
to
```js
const person = {
name: {
first: "Bob",
last: "Smith",
},
// β¦
};
```
To access these items you just need to chain the extra step onto the end with another dot. Try these in the JS console:
```js
person.name.first;
person.name.last;
```
If you do this, you'll also need to go through your method code and change any instances of
```js
name[0];
name[1];
```
to
```js
name.first;
name.last;
```
Otherwise, your methods will no longer work.
Bracket notation
----------------
Bracket notation provides an alternative way to access object properties.
Instead of using dot notation like this:
```js
person.age;
person.name.first;
```
You can instead use square brackets:
```js
person["age"];
person["name"]["first"];
```
This looks very similar to how you access the items in an array, and it is basically the same thing β instead of using an index number to select an item, you are using the name associated with each member's value.
It is no wonder that objects are sometimes called **associative arrays** β they map strings to values in the same way that arrays map numbers to values.
Dot notation is generally preferred over bracket notation because it is more succinct and easier to read.
However there are some cases where you have to use square brackets.
For example, if an object property name is held in a variable, then you can't use dot notation to access the value, but you can access the value using bracket notation.
In the example below, the `logProperty()` function can use `person[propertyName]` to retrieve the value of the property named in `propertyName`.
```js
const person = {
name: ["Bob", "Smith"],
age: 32,
};
function logProperty(propertyName) {
console.log(person[propertyName]);
}
logProperty("name");
// ["Bob", "Smith"]
logProperty("age");
// 32
```
Setting object members
----------------------
So far we've only looked at retrieving (or **getting**) object members β you can also **set** (update) the value of object members by declaring the member you want to set (using dot or bracket notation), like this:
```js
person.age = 45;
person["name"]["last"] = "Cratchit";
```
Try entering the above lines, and then getting the members again to see how they've changed, like so:
```js
person.age;
person["name"]["last"];
```
Setting members doesn't just stop at updating the values of existing properties and methods; you can also create completely new members. Try these in the JS console:
```js
person["eyes"] = "hazel";
person.farewell = function () {
console.log("Bye everybody!");
};
```
You can now test out your new members:
```js
person["eyes"];
person.farewell();
// "Bye everybody!"
```
One useful aspect of bracket notation is that it can be used to set not only member values dynamically, but member names too. Let's say we wanted users to be able to store custom value types in their people data, by typing the member name and value into two text inputs. We could get those values like this:
```js
const myDataName = nameInput.value;
const myDataValue = nameValue.value;
```
We could then add this new member name and value to the `person` object like this:
```js
person[myDataName] = myDataValue;
```
To test this, try adding the following lines into your code, just below the closing curly brace of the `person` object:
```js
const myDataName = "height";
const myDataValue = "1.75m";
person[myDataName] = myDataValue;
```
Now try saving and refreshing, and entering the following into your text input:
```js
person.height;
```
Adding a property to an object using the method above isn't possible with dot notation, which can only accept a literal member name, not a variable value pointing to a name.
What is "this"?
---------------
You may have noticed something slightly strange in our methods. Look at this one for example:
```js
introduceSelf() {
console.log(`Hi! I'm ${this.name[0]}.`);
}
```
You are probably wondering what "this" is. The `this` keyword refers to the current object the code is being written inside β so in this case `this` is equivalent to `person`. So why not just write `person` instead?
Well, when you only have to create a single object literal, it's not so useful. But if you create more than one, `this` enables you to use the same method definition for every object you create.
Let's illustrate what we mean with a simplified pair of person objects:
```js
const person1 = {
name: "Chris",
introduceSelf() {
console.log(`Hi! I'm ${this.name}.`);
},
};
const person2 = {
name: "Deepti",
introduceSelf() {
console.log(`Hi! I'm ${this.name}.`);
},
};
```
In this case, `person1.introduceSelf()` outputs "Hi! I'm Chris."; `person2.introduceSelf()` on the other hand outputs "Hi! I'm Deepti.", even though the method's code is exactly the same in each case. This isn't hugely useful when you are writing out object literals by hand, but it will be essential when we start using **constructors** to create more than one object from a single object definition, and that's the subject of the next section.
Introducing constructors
------------------------
Using object literals is fine when you only need to create one object, but if you have to create more than one, as in the previous section, they're seriously inadequate. We have to write out the same code for every object we create, and if we want to change some properties of the object - like adding a `height` property - then we have to remember to update every object.
We would like a way to define the "shape" of an object β the set of methods and the properties it can have β and then create as many objects as we like, just updating the values for the properties that are different.
The first version of this is just a function:
```js
function createPerson(name) {
const obj = {};
obj.name = name;
obj.introduceSelf = function () {
console.log(`Hi! I'm ${this.name}.`);
};
return obj;
}
```
This function creates and returns a new object each time we call it. The object will have two members:
* a property `name`
* a method `introduceSelf()`.
Note that `createPerson()` takes a parameter `name` to set the value of the `name` property, but the value of the `introduceSelf()` method will be the same for all objects created using this function. This is a very common pattern for creating objects.
Now we can create as many objects as we like, reusing the definition:
```js
const salva = createPerson("Salva");
salva.name;
salva.introduceSelf();
// "Hi! I'm Salva."
const frankie = createPerson("Frankie");
frankie.name;
frankie.introduceSelf();
// "Hi! I'm Frankie."
```
This works fine but is a bit long-winded: we have to create an empty object, initialize it, and return it. A better way is to use a **constructor**. A constructor is just a function called using the `new` keyword. When you call a constructor, it will:
* create a new object
* bind `this` to the new object, so you can refer to `this` in your constructor code
* run the code in the constructor
* return the new object.
Constructors, by convention, start with a capital letter and are named for the type of object they create. So we could rewrite our example like this:
```js
function Person(name) {
this.name = name;
this.introduceSelf = function () {
console.log(`Hi! I'm ${this.name}.`);
};
}
```
To call `Person()` as a constructor, we use `new`:
```js
const salva = new Person("Salva");
salva.name;
salva.introduceSelf();
// "Hi! I'm Salva."
const frankie = new Person("Frankie");
frankie.name;
frankie.introduceSelf();
// "Hi! I'm Frankie."
```
You've been using objects all along
-----------------------------------
As you've been going through these examples, you have probably been thinking that the dot notation you've been using is very familiar. That's because you've been using it throughout the course! Every time we've been working through an example that uses a built-in browser API or JavaScript object, we've been using objects, because such features are built using exactly the same kind of object structures that we've been looking at here, albeit more complex ones than in our own basic custom examples.
So when you used string methods like:
```js
myString.split(",");
```
You were using a method available on a `String` object. Every time you create a string in your code, that string is automatically created as an instance of `String`, and therefore has several common methods and properties available on it.
When you accessed the document object model using lines like this:
```js
const myDiv = document.createElement("div");
const myVideo = document.querySelector("video");
```
You were using methods available on a `Document` object. For each webpage loaded, an instance of `Document` is created, called `document`, which represents the entire page's structure, content, and other features such as its URL. Again, this means that it has several common methods and properties available on it.
The same is true of pretty much any other built-in object or API you've been using β `Array`, `Math`, and so on.
Note that built in objects and APIs don't always create object instances automatically. As an example, the Notifications API β which allows modern browsers to fire system notifications β requires you to instantiate a new object instance using the constructor for each notification you want to fire. Try entering the following into your JavaScript console:
```js
const myNotification = new Notification("Hello!");
```
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Object basics.
Summary
-------
Congratulations, you've reached the end of our first JS objects article β you should now have a good idea of how to work with objects in JavaScript β including creating your own simple objects. You should also appreciate that objects are very useful as structures for storing related data and functionality β if you tried to keep track of all the properties and methods in our `person` object as separate variables and functions, it would be inefficient and frustrating, and we'd run the risk of clashing with other variables and functions that have the same names. Objects let us keep the information safely locked away in their own package, out of harm's way.
In the next article we'll look at **prototypes**, which is the fundamental way that JavaScript lets an object inherit properties from other objects.
* Overview: Objects
* Next |
Classes in JavaScript - Learn web development | Classes in JavaScript
=====================
* Previous
* Overview: Objects
* Next
In the last article, we introduced some basic concepts of object-oriented programming (OOP), and discussed an example where we used OOP principles to model professors and students in a school.
We also talked about how it's possible to use prototypes and constructors to implement a model like this, and that JavaScript also provides features that map more closely to classical OOP concepts.
In this article, we'll go through these features. It's worth keeping in mind that the features described here are not a new way of combining objects: under the hood, they still use prototypes. They're just a way to make it easier to set up a prototype chain.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of HTML and CSS,
familiarity with JavaScript basics (see
First steps and
Building blocks) and OOJS basics (see
Introduction to objects, Object prototypes, and Object-oriented programming).
|
| Objective: | To understand how to use the features JavaScript provides to implement "classical" object-oriented programs. |
Classes and constructors
------------------------
You can declare a class using the `class` keyword. Here's a class declaration for our `Person` from the previous article:
```js
class Person {
name;
constructor(name) {
this.name = name;
}
introduceSelf() {
console.log(`Hi! I'm ${this.name}`);
}
}
```
This declares a class called `Person`, with:
* a `name` property.
* a constructor that takes a `name` parameter that is used to initialize the new object's `name` property
* an `introduceSelf()` method that can refer to the object's properties using `this`.
The `name;` declaration is optional: you could omit it, and the line `this.name = name;` in the constructor will create the `name` property before initializing it. However, listing properties explicitly in the class declaration might make it easier for people reading your code to see which properties are part of this class.
You could also initialize the property to a default value when you declare it, with a line like `name = '';`.
The constructor is defined using the `constructor` keyword. Just like a constructor outside a class definition, it will:
* create a new object
* bind `this` to the new object, so you can refer to `this` in your constructor code
* run the code in the constructor
* return the new object.
Given the class declaration code above, you can create and use a new `Person` instance like this:
```js
const giles = new Person("Giles");
giles.introduceSelf(); // Hi! I'm Giles
```
Note that we call the constructor using the name of the class, `Person` in this example.
### Omitting constructors
If you don't need to do any special initialization, you can omit the constructor, and a default constructor will be generated for you:
```js
class Animal {
sleep() {
console.log("zzzzzzz");
}
}
const spot = new Animal();
spot.sleep(); // 'zzzzzzz'
```
Inheritance
-----------
Given our `Person` class above, let's define the `Professor` subclass.
```js
class Professor extends Person {
teaches;
constructor(name, teaches) {
super(name);
this.teaches = teaches;
}
introduceSelf() {
console.log(
`My name is ${this.name}, and I will be your ${this.teaches} professor.`,
);
}
grade(paper) {
const grade = Math.floor(Math.random() \* (5 - 1) + 1);
console.log(grade);
}
}
```
We use the `extends` keyword to say that this class inherits from another class.
The `Professor` class adds a new property `teaches`, so we declare that.
Since we want to set `teaches` when a new `Professor` is created, we define a constructor, which takes the `name` and `teaches` as arguments. The first thing this constructor does is call the superclass constructor using `super()`, passing up the `name` parameter. The superclass constructor takes care of setting `name`. After that, the `Professor` constructor sets the `teaches` property.
**Note:** If a subclass has any of its own initialization to do, it **must** first call the superclass constructor using `super()`, passing up any parameters that the superclass constructor is expecting.
We've also overridden the `introduceSelf()` method from the superclass, and added a new method `grade()`, to grade a paper (our professor isn't very good, and just assigns random grades to papers).
With this declaration we can now create and use professors:
```js
const walsh = new Professor("Walsh", "Psychology");
walsh.introduceSelf(); // 'My name is Walsh, and I will be your Psychology professor'
walsh.grade("my paper"); // some random grade
```
Encapsulation
-------------
Finally, let's see how to implement encapsulation in JavaScript. In the last article we discussed how we would like to make the `year` property of `Student` private, so we could change the rules about archery classes without breaking any code that uses the `Student` class.
Here's a declaration of the `Student` class that does just that:
```js
class Student extends Person {
#year;
constructor(name, year) {
super(name);
this.#year = year;
}
introduceSelf() {
console.log(`Hi! I'm ${this.name}, and I'm in year ${this.#year}.`);
}
canStudyArchery() {
return this.#year > 1;
}
}
```
In this class declaration, `#year` is a private data property. We can construct a `Student` object, and it can use `#year` internally, but if code outside the object tries to access `#year` the browser throws an error:
```js
const summers = new Student("Summers", 2);
summers.introduceSelf(); // Hi! I'm Summers, and I'm in year 2.
summers.canStudyArchery(); // true
summers.#year; // SyntaxError
```
**Note:** Code run in the Chrome console can access private properties outside the class. This is a DevTools-only relaxation of the JavaScript syntax restriction.
Private data properties must be declared in the class declaration, and their names start with `#`.
### Private methods
You can have private methods as well as private data properties. Just like private data properties, their names start with `#`, and they can only be called by the object's own methods:
```js
class Example {
somePublicMethod() {
this.#somePrivateMethod();
}
#somePrivateMethod() {
console.log("You called me?");
}
}
const myExample = new Example();
myExample.somePublicMethod(); // 'You called me?'
myExample.#somePrivateMethod(); // SyntaxError
```
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Object-oriented JavaScript.
Summary
-------
In this article, we've gone through the main tools available in JavaScript for writing object-oriented programs. We haven't covered everything here, but this should be enough to get you started. Our article on Classes is a good place to learn more.
* Previous
* Overview: Objects
* Next |
Test your skills: JSON - Learn web development | Test your skills: JSON
======================
The aim of this skill test is to assess whether you've understood our Working with JSON article.
**Note:** You can try solutions by downloading the code and putting it in an online editor such as CodePen, JSFiddle, or Glitch.
If there is an error, it will be logged in the results panel on the page or into the browser's JavaScript console to help you.
If you get stuck, you can reach out to us in one of our communication channels.
JSON 1
------
The one and only task in this article concerns accessing JSON data and using it in your page. JSON data about some mother cats and their kittens is available in sample.json. The JSON is loaded into the page as a text string and made available in the `catString` parameter of the `displayCatInfo()` function. Your task is to fill in the missing parts of the `displayCatInfo()` function to store:
* The names of the three mother cats, separated by commas, in the `motherInfo` variable.
* The total number of kittens, and how many are male and female, in the `kittenInfo` variable.
The values of these variables are then printed to the screen inside paragraphs.
Some hints/questions:
* The JSON data is provided as text inside the `displayCatInfo()` function. You'll need to parse it into JSON before you can get any data out of it.
* You'll probably want to use an outer loop to loop through the cats and add their names to the `motherInfo` variable string, and an inner loop to loop through all the kittens, add up the total of all/male/female kittens, and add those details to the `kittenInfo` variable string.
* The last mother cat name should have an "and" before it, and a full stop after it. How do you make sure this can work, no matter how many cats are in the JSON?
* Why are the `para1.textContent = motherInfo;` and `para2.textContent = kittenInfo;` lines inside the `displayCatInfo()` function, and not at the end of the script? This has something to do with async code.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
Object building practice - Learn web development | Object building practice
========================
* Previous
* Overview: Objects
* Next
In previous articles we looked at all the essential JavaScript object theory and syntax details, giving you a solid base to start from. In this article we dive into a practical exercise, giving you some more practice in building custom JavaScript objects, with a fun and colorful result.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of HTML and CSS,
familiarity with JavaScript basics (see
First steps and
Building blocks) and OOJS basics (see
Introduction to objects).
|
| Objective: |
To get some practice with using objects and object-oriented techniques
in a real-world context.
|
Let's bounce some balls
-----------------------
In this article we will write a classic "bouncing balls" demo, to show you how useful objects can be in JavaScript. Our little balls will bounce around on the screen, and change color when they touch each other. The finished example will look a little something like this:
![Screenshot of a webpage titled "Bouncing balls". 23 balls of various pastel colors and sizes are visible across a black screen with long trails behind them indicating motion.](/en-US/docs/Learn/JavaScript/Objects/Object_building_practice/bouncing-balls.png)
This example will make use of the Canvas API for drawing the balls to the screen, and the `requestAnimationFrame` API for animating the whole display β you don't need to have any previous knowledge of these APIs, and we hope that by the time you've finished this article you'll be interested in exploring them more. Along the way, we'll make use of some nifty objects, and show you a couple of nice techniques like bouncing balls off walls, and checking whether they have hit each other (otherwise known as *collision detection*).
Getting started
---------------
To begin with, make local copies of our `index.html`, `style.css`, and `main.js` files. These contain the following, respectively:
1. A very simple HTML document featuring an h1 element, a `<canvas>` element to draw our balls on, and elements to apply our CSS and JavaScript to our HTML.
2. Some very simple styles, which mainly serve to style and position the `<h1>`, and get rid of any scrollbars or margin around the edge of the page (so that it looks nice and neat).
3. Some JavaScript that serves to set up the `<canvas>` element and provide a general function that we're going to use.
The first part of the script looks like so:
```js
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const width = (canvas.width = window.innerWidth);
const height = (canvas.height = window.innerHeight);
```
This script gets a reference to the `<canvas>` element, then calls the `getContext()` method on it to give us a context on which we can start to draw. The resulting constant (`ctx`) is the object that directly represents the drawing area of the canvas and allows us to draw 2D shapes on it.
Next, we set constants called `width` and `height`, and the width and height of the canvas element (represented by the `canvas.width` and `canvas.height` properties) to equal the width and height of the browser viewport (the area which the webpage appears on β this can be gotten from the `Window.innerWidth` and `Window.innerHeight` properties).
Note that we are chaining multiple assignments together, to get the variables all set quicker β this is perfectly OK.
Then we have two helper functions:
```js
function random(min, max) {
return Math.floor(Math.random() \* (max - min + 1)) + min;
}
function randomRGB() {
return `rgb(${random(0, 255)} ${random(0, 255)} ${random(0, 255)})`;
}
```
The `random()` function takes two numbers as arguments, and returns a random number in the range between the two. The `randomRGB()` function generates a random color represented as an `rgb()` string.
Modeling a ball in our program
------------------------------
Our program will feature lots of balls bouncing around the screen. Since these balls will all behave in the same way, it makes sense to represent them with an object. Let's start by adding the following class definition to the bottom of our code.
```js
class Ball {
constructor(x, y, velX, velY, color, size) {
this.x = x;
this.y = y;
this.velX = velX;
this.velY = velY;
this.color = color;
this.size = size;
}
}
```
So far this class only contains a constructor, in which we can initialize the properties each ball needs in order to function in our program:
* `x` and `y` coordinates β the horizontal and vertical coordinates where the ball starts on the screen. This can range between 0 (top left hand corner) to the width and height of the browser viewport (bottom right-hand corner).
* horizontal and vertical velocity (`velX` and `velY`) β each ball is given a horizontal and vertical velocity; in real terms these values are regularly added to the `x`/`y` coordinate values when we animate the balls, to move them by this much on each frame.
* `color` β each ball gets a color.
* `size` β each ball gets a size β this is its radius, in pixels.
This handles the properties, but what about the methods? We want to get our balls to actually do something in our program.
### Drawing the ball
First add the following `draw()` method to the `Ball` class:
```js
draw() {
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc(this.x, this.y, this.size, 0, 2 \* Math.PI);
ctx.fill();
}
```
Using this function, we can tell the ball to draw itself onto the screen, by calling a series of members of the 2D canvas context we defined earlier (`ctx`). The context is like the paper, and now we want to command our pen to draw something on it:
* First, we use `beginPath()` to state that we want to draw a shape on the paper.
* Next, we use `fillStyle` to define what color we want the shape to be β we set it to our ball's `color` property.
* Next, we use the `arc()` method to trace an arc shape on the paper. Its parameters are:
+ The `x` and `y` position of the arc's center β we are specifying the ball's `x` and `y` properties.
+ The radius of the arc β in this case, the ball's `size` property.
+ The last two parameters specify the start and end number of degrees around the circle that the arc is drawn between. Here we specify 0 degrees, and `2 * PI`, which is the equivalent of 360 degrees in radians (annoyingly, you have to specify this in radians). That gives us a complete circle. If you had specified only `1 * PI`, you'd get a semi-circle (180 degrees).
* Last of all, we use the `fill()` method, which basically states "finish drawing the path we started with `beginPath()`, and fill the area it takes up with the color we specified earlier in `fillStyle`."
You can start testing your object out already.
1. Save the code so far, and load the HTML file in a browser.
2. Open the browser's JavaScript console, and then refresh the page so that the canvas size changes to the smaller visible viewport that remains when the console opens.
3. Type in the following to create a new ball instance:
```js
const testBall = new Ball(50, 100, 4, 4, "blue", 10);
```
4. Try calling its members:
```js
testBall.x;
testBall.size;
testBall.color;
testBall.draw();
```
5. When you enter the last line, you should see the ball draw itself somewhere on the canvas.
### Updating the ball's data
We can draw the ball in position, but to actually move the ball, we need an update function of some kind. Add the following code inside the class definition for `Ball`:
```js
update() {
if ((this.x + this.size) >= width) {
this.velX = -(this.velX);
}
if ((this.x - this.size) <= 0) {
this.velX = -(this.velX);
}
if ((this.y + this.size) >= height) {
this.velY = -(this.velY);
}
if ((this.y - this.size) <= 0) {
this.velY = -(this.velY);
}
this.x += this.velX;
this.y += this.velY;
}
```
The first four parts of the function check whether the ball has reached the edge of the canvas. If it has, we reverse the polarity of the relevant velocity to make the ball travel in the opposite direction. So for example, if the ball was traveling upwards (negative `velY`), then the vertical velocity is changed so that it starts to travel downwards instead (positive `velY`).
In the four cases, we are checking to see:
* if the `x` coordinate is greater than the width of the canvas (the ball is going off the right edge).
* if the `x` coordinate is smaller than 0 (the ball is going off the left edge).
* if the `y` coordinate is greater than the height of the canvas (the ball is going off the bottom edge).
* if the `y` coordinate is smaller than 0 (the ball is going off the top edge).
In each case, we include the `size` of the ball in the calculation because the `x`/`y` coordinates are in the center of the ball, but we want the edge of the ball to bounce off the perimeter β we don't want the ball to go halfway off the screen before it starts to bounce back.
The last two lines add the `velX` value to the `x` coordinate, and the `velY` value to the `y` coordinate β the ball is in effect moved each time this method is called.
This will do for now; let's get on with some animation!
Animating the ball
------------------
Now let's make this fun. We are now going to start adding balls to the canvas, and animating them.
First, we need to create somewhere to store all our balls and then populate it. The following will do this job β add it to the bottom of your code now:
```js
const balls = [];
while (balls.length < 25) {
const size = random(10, 20);
const ball = new Ball(
// ball position always drawn at least one ball width
// away from the edge of the canvas, to avoid drawing errors
random(0 + size, width - size),
random(0 + size, height - size),
random(-7, 7),
random(-7, 7),
randomRGB(),
size,
);
balls.push(ball);
}
```
The `while` loop creates a new instance of our `Ball()` using random values generated with our `random()` and `randomRGB()` functions, then `push()`es it onto the end of our balls array, but only while the number of balls in the array is less than 25. So when we have 25 balls in the array, no more balls will be pushed. You can try varying the number in `balls.length < 25` to get more or fewer balls in the array. Depending on how much processing power your computer/browser has, specifying several thousand balls might slow down the animation rather a lot!
Next, add the following to the bottom of your code:
```js
function loop() {
ctx.fillStyle = "rgb(0 0 0 / 25%)";
ctx.fillRect(0, 0, width, height);
for (const ball of balls) {
ball.draw();
ball.update();
}
requestAnimationFrame(loop);
}
```
All programs that animate things generally involve an animation loop, which serves to update the information in the program and then render the resulting view on each frame of the animation; this is the basis for most games and other such programs. Our `loop()` function does the following:
* Sets the canvas fill color to semi-transparent black, then draws a rectangle of the color across the whole width and height of the canvas, using `fillRect()` (the four parameters provide a start coordinate, and a width and height for the rectangle drawn). This serves to cover up the previous frame's drawing before the next one is drawn. If you don't do this, you'll just see long snakes worming their way around the canvas instead of balls moving! The color of the fill is set to semi-transparent, `rgb(0 0 0 / 25%)`, to allow the previous few frames to shine through slightly, producing the little trails behind the balls as they move. If you changed 0.25 to 1, you won't see them at all any more. Try varying this number to see the effect it has.
* Loops through all the balls in the `balls` array, and runs each ball's `draw()` and `update()` function to draw each one on the screen, then do the necessary updates to position and velocity in time for the next frame.
* Runs the function again using the `requestAnimationFrame()` method β when this method is repeatedly run and passed the same function name, it runs that function a set number of times per second to create a smooth animation. This is generally done recursively β which means that the function is calling itself every time it runs, so it runs over and over again.
Finally, add the following line to the bottom of your code β we need to call the function once to get the animation started.
```js
loop();
```
That's it for the basics β try saving and refreshing to test your bouncing balls out!
Adding collision detection
--------------------------
Now for a bit of fun, let's add some collision detection to our program, so our balls know when they have hit another ball.
First, add the following method definition to your `Ball` class.
```js
collisionDetect() {
for (const ball of balls) {
if (this !== ball) {
const dx = this.x - ball.x;
const dy = this.y - ball.y;
const distance = Math.sqrt(dx \* dx + dy \* dy);
if (distance < this.size + ball.size) {
ball.color = this.color = randomRGB();
}
}
}
}
```
This method is a little complex, so don't worry if you don't understand exactly how it works for now. An explanation follows:
* For each ball, we need to check every other ball to see if it has collided with the current ball. To do this, we start another `for...of` loop to loop through all the balls in the `balls[]` array.
* Immediately inside the for loop, we use an `if` statement to check whether the current ball being looped through is the same ball as the one we are currently checking. We don't want to check whether a ball has collided with itself! To do this, we check whether the current ball (i.e., the ball whose collisionDetect method is being invoked) is the same as the loop ball (i.e., the ball that is being referred to by the current iteration of the for loop in the collisionDetect method). We then use `!` to negate the check, so that the code inside the `if` statement only runs if they are **not** the same.
* We then use a common algorithm to check the collision of two circles. We are basically checking whether any of the two circle's areas overlap. This is explained further in 2D collision detection.
* If a collision is detected, the code inside the inner `if` statement is run. In this case, we only set the `color` property of both the circles to a new random color. We could have done something far more complex, like get the balls to bounce off each other realistically, but that would have been far more complex to implement. For such physics simulations, developers tend to use a games or physics libraries such as PhysicsJS, matter.js, Phaser, etc.
You also need to call this method in each frame of the animation. Update your `loop()` function to call `ball.collisionDetect()` after `ball.update()`:
```js
function loop() {
ctx.fillStyle = "rgb(0 0 0 / 25%)";
ctx.fillRect(0, 0, width, height);
for (const ball of balls) {
ball.draw();
ball.update();
ball.collisionDetect();
}
requestAnimationFrame(loop);
}
```
Save and refresh the demo again, and you'll see your balls change color when they collide!
**Note:** If you have trouble getting this example to work, try comparing your JavaScript code against our finished version (also see it running live).
Summary
-------
We hope you had fun writing your own real-world random bouncing balls example, using various object and object-oriented techniques from throughout the module! This should have given you some useful practice in using objects, and good real-world context.
That's it for object articles β all that remains now is for you to test your skills in the object assessment.
See also
--------
* Canvas tutorial β a beginner's guide to using 2D canvas.
* requestAnimationFrame()
* 2D collision detection
* 3D collision detection
* 2D breakout game using pure JavaScript β a great beginner's tutorial showing how to build a 2D game.
* 2D breakout game using Phaser β explains the basics of building a 2D game using a JavaScript game library.
* Previous
* Overview: Objects
* Next |
Test your skills: Object-oriented JavaScript - Learn web development | Test your skills: Object-oriented JavaScript
============================================
The aim of this skill test is to assess whether you've understood our Classes in JavaScript article.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If there is an error in your code, it will be logged into the results panel on this page or in the JavaScript console.
If you get stuck, you can reach out to us in one of our communication channels.
OOJS 1
------
In this task we provide you with the start of a definition for a `Shape` class. It has three properties: `name`, `sides`, and `sideLength`. This class only models shapes for which all sides are the same length, like a square or an equilateral triangle.
We'd like you to:
* Add a constructor to this class. The constructor takes arguments for the `name`, `sides`, and `sideLength` properties, and initializes them.
* Add a new method `calcPerimeter()` method to the class, which calculates its perimeter (the length of the shape's outer edge) and logs the result to the console.
* Create a new instance of the `Shape` class called `square`. Give it a `name` of `square`, `4` `sides`, and a `sideLength` of `5`.
* Call your `calcPerimeter()` method on the instance, to see whether it logs the calculation result to the browser's console as expected.
* Create a new instance of `Shape` called `triangle`, with a `name` of `triangle`, `3` `sides` and a `sideLength` of `3`.
* Call `triangle.calcPerimeter()` to check that it works OK.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
OOJS 2
------
Next we'd like you to create a `Square` class that inherits from `Shape`, and adds a `calcArea()` method that calculates the square's area. Also set up the constructor so that the `name` property of `Square` object instances is automatically set to `square`, and the `sides` property is automatically set to `4`. When invoking the constructor, you should therefore just need to provide the `sideLength` property.
Create an instance of the `Square` class called `square` with appropriate property values, and call its `calcPerimeter()` and `calcArea()` methods to show that it works OK.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
Working with JSON - Learn web development | Working with JSON
=================
* Previous
* Overview: Objects
* Next
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa). You'll come across it quite often, so in this article, we give you all you need to work with JSON using JavaScript, including parsing JSON so you can access data within it, and creating JSON.
| | |
| --- | --- |
| Prerequisites: | A basic understanding of HTML and CSS, familiarity with JavaScript basics (see First steps and Building blocks) and OOJS basics (see Introduction to objects). |
| Objective: | To understand how to work with data stored in JSON, and create your own JSON strings. |
No, really, what is JSON?
-------------------------
JSON is a text-based data format following JavaScript object syntax, which was popularized by Douglas Crockford.
Even though it closely resembles JavaScript object literal syntax, it can be used independently from JavaScript, and many programming environments feature the ability to read (parse) and generate JSON.
JSON exists as a string β useful when you want to transmit data across a network.
It needs to be converted to a native JavaScript object when you want to access the data.
This is not a big issue β JavaScript provides a global JSON object that has methods available for converting between the two.
**Note:** Converting a string to a native object is called *deserialization*, while converting a native object to a string so it can be transmitted across the network is called *serialization*.
A JSON string can be stored in its own file, which is basically just a text file with an extension of `.json`, and a MIME type of `application/json`.
### JSON structure
As described above, JSON is a string whose format very much resembles JavaScript object literal format.
You can include the same basic data types inside JSON as you can in a standard JavaScript object β strings, numbers, arrays, booleans, and other object literals.
This allows you to construct a data hierarchy, like so:
```json
{
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": ["Radiation resistance", "Turning tiny", "Radiation blast"]
},
{
"name": "Madame Uppercut",
"age": 39,
"secretIdentity": "Jane Wilson",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
},
{
"name": "Eternal Flame",
"age": 1000000,
"secretIdentity": "Unknown",
"powers": [
"Immortality",
"Heat Immunity",
"Inferno",
"Teleportation",
"Interdimensional travel"
]
}
]
}
```
If we loaded this string into a JavaScript program and parsed it into a variable called `superHeroes` for example, we could then access the data inside it using the same dot/bracket notation we looked at in the JavaScript object basics article.
For example:
```js
superHeroes.homeTown;
superHeroes["active"];
```
To access data further down the hierarchy, you have to chain the required property names and array indexes together. For example, to access the third superpower of the second hero listed in the members list, you'd do this:
```js
superHeroes["members"][1]["powers"][2];
```
1. First, we have the variable name β `superHeroes`.
2. Inside that, we want to access the `members` property, so we use `["members"]`.
3. `members` contains an array populated by objects. We want to access the second object inside the array, so we use `[1]`.
4. Inside this object, we want to access the `powers` property, so we use `["powers"]`.
5. Inside the `powers` property is an array containing the selected hero's superpowers. We want the third one, so we use `[2]`.
**Note:** We've made the JSON seen above available inside a variable in our JSONTest.html example (see the source code).
Try loading this up and then accessing data inside the variable via your browser's JavaScript console.
### Arrays as JSON
Above we mentioned that JSON text basically looks like a JavaScript object inside a string.
We can also convert arrays to/from JSON. Below is also valid JSON, for example:
```json
[
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": ["Radiation resistance", "Turning tiny", "Radiation blast"]
},
{
"name": "Madame Uppercut",
"age": 39,
"secretIdentity": "Jane Wilson",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
}
]
```
The above is perfectly valid JSON. You'd just have to access array items (in its parsed version) by starting with an array index, for example `[0]["powers"][0]`.
### Other notes
* JSON is purely a string with a specified data format β it contains only properties, no methods.
* JSON requires double quotes to be used around strings and property names.
Single quotes are not valid other than surrounding the entire JSON string.
* Even a single misplaced comma or colon can cause a JSON file to go wrong, and not work.
You should be careful to validate any data you are attempting to use (although computer-generated JSON is less likely to include errors, as long as the generator program is working correctly).
You can validate JSON using an application like JSONLint.
* JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects.
So for example, a single string or number would be valid JSON.
* Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings may be used as properties.
Active learning: Working through a JSON example
-----------------------------------------------
So, let's work through an example to show how we could make use of some JSON formatted data on a website.
### Getting started
To begin with, make local copies of our heroes.html and style.css files.
The latter contains some simple CSS to style our page, while the former contains some very simple body HTML, plus a `<script>` element to contain the JavaScript code we will be writing in this exercise:
```html
<header>
...
</header>
<section>
...
</section>
<script>
...
</script>
```
We have made our JSON data available on our GitHub, at https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json.
We are going to load the JSON into our script, and use some nifty DOM manipulation to display it, like this:
![Image of a document titled "Super hero squad" (in a fancy font) and subtitled "Hometown: Metro City // Formed: 2016". Three columns below the heading are titled "Molecule Man", "Madame Uppercut", and "Eternal Flame", respectively. Each column lists the hero's secret identity name, age, and superpowers.](/en-US/docs/Learn/JavaScript/Objects/JSON/json-superheroes.png)
### Top-level function
The top-level function looks like this:
```js
async function populate() {
const requestURL =
"https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json";
const request = new Request(requestURL);
const response = await fetch(request);
const superHeroes = await response.json();
populateHeader(superHeroes);
populateHeroes(superHeroes);
}
```
To obtain the JSON, we use an API called Fetch.
This API allows us to make network requests to retrieve resources from a server via JavaScript (e.g. images, text, JSON, even HTML snippets), meaning that we can update small sections of content without having to reload the entire page.
In our function, the first four lines use the Fetch API to fetch the JSON from the server:
* we declare the `requestURL` variable to store the GitHub URL
* we use the URL to initialize a new `Request` object.
* we make the network request using the `fetch()` function, and this returns a `Response` object
* we retrieve the response as JSON using the `json()` function of the `Response` object.
**Note:** The `fetch()` API is **asynchronous**. We'll learn a lot about asynchronous functions in the next module, but for now, we'll just say that we need to add the keyword `async` before the name of the function that uses the fetch API, and add the keyword `await` before the calls to any asynchronous functions.
After all that, the `superHeroes` variable will contain the JavaScript object based on the JSON. We are then passing that object to two function calls β the first one fills the `<header>` with the correct data, while the second one creates an information card for each hero on the team, and inserts it into the `<section>`.
### Populating the header
Now that we've retrieved the JSON data and converted it into a JavaScript object, let's make use of it by writing the two functions we referenced above. First of all, add the following function definition below the previous code:
```js
function populateHeader(obj) {
const header = document.querySelector("header");
const myH1 = document.createElement("h1");
myH1.textContent = obj.squadName;
header.appendChild(myH1);
const myPara = document.createElement("p");
myPara.textContent = `Hometown: ${obj.homeTown} // Formed: ${obj.formed}`;
header.appendChild(myPara);
}
```
Here we first create an h1 element with `createElement()`, set its `textContent` to equal the `squadName` property of the object, then append it to the header using `appendChild()`. We then do a very similar operation with a paragraph: create it, set its text content and append it to the header. The only difference is that its text is set to a template literal containing both the `homeTown` and `formed` properties of the object.
### Creating the hero information cards
Next, add the following function at the bottom of the code, which creates and displays the superhero cards:
```js
function populateHeroes(obj) {
const section = document.querySelector("section");
const heroes = obj.members;
for (const hero of heroes) {
const myArticle = document.createElement("article");
const myH2 = document.createElement("h2");
const myPara1 = document.createElement("p");
const myPara2 = document.createElement("p");
const myPara3 = document.createElement("p");
const myList = document.createElement("ul");
myH2.textContent = hero.name;
myPara1.textContent = `Secret identity: ${hero.secretIdentity}`;
myPara2.textContent = `Age: ${hero.age}`;
myPara3.textContent = "Superpowers:";
const superPowers = hero.powers;
for (const power of superPowers) {
const listItem = document.createElement("li");
listItem.textContent = power;
myList.appendChild(listItem);
}
myArticle.appendChild(myH2);
myArticle.appendChild(myPara1);
myArticle.appendChild(myPara2);
myArticle.appendChild(myPara3);
myArticle.appendChild(myList);
section.appendChild(myArticle);
}
}
```
To start with, we store the `members` property of the JavaScript object in a new variable. This array contains multiple objects that contain the information for each hero.
Next, we use a for...of loop to loop through each object in the array. For each one, we:
1. Create several new elements: an `<article>`, an `<h2>`, three `<p>`s, and a `<ul>`.
2. Set the `<h2>` to contain the current hero's `name`.
3. Fill the three paragraphs with their `secretIdentity`, `age`, and a line saying "Superpowers:" to introduce the information in the list.
4. Store the `powers` property in another new constant called `superPowers` β this contains an array that lists the current hero's superpowers.
5. Use another `for...of` loop to loop through the current hero's superpowers β for each one we create an `<li>` element, put the superpower inside it, then put the `listItem` inside the `<ul>` element (`myList`) using `appendChild()`.
6. The very last thing we do is to append the `<h2>`, `<p>`s, and `<ul>` inside the `<article>` (`myArticle`), then append the `<article>` inside the `<section>`. The order in which things are appended is important, as this is the order they will be displayed inside the HTML.
**Note:** If you are having trouble getting the example to work, try referring to our heroes-finished.html source code (see it running live also.)
**Note:** If you are having trouble following the dot/bracket notation we are using to access the JavaScript object, it can help to have the superheroes.json file open in another tab or your text editor, and refer to it as you look at our JavaScript.
You should also refer back to our JavaScript object basics article for more information on dot and bracket notation.
### Calling the top-level function
Finally, we need to call our top-level `populate()` function:
```js
populate();
```
Converting between objects and text
-----------------------------------
The above example was simple in terms of accessing the JavaScript object, because we converted the network response directly into a JavaScript object using `response.json()`.
But sometimes we aren't so lucky β sometimes we receive a raw JSON string, and we need to convert it to an object ourselves. And when we want to send a JavaScript object across the network, we need to convert it to JSON (a string) before sending it. Luckily, these two problems are so common in web development that a built-in JSON object is available in browsers, which contains the following two methods:
* `parse()`: Accepts a JSON string as a parameter, and returns the corresponding JavaScript object.
* `stringify()`: Accepts an object as a parameter, and returns the equivalent JSON string.
You can see the first one in action in our heroes-finished-json-parse.html example (see the source code) β this does exactly the same thing as the example we built up earlier, except that:
* we retrieve the response as text rather than JSON, by calling the `text()` method of the response
* we then use `parse()` to convert the text to a JavaScript object.
The key snippet of code is here:
```js
async function populate() {
const requestURL =
"https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json";
const request = new Request(requestURL);
const response = await fetch(request);
const superHeroesText = await response.text();
const superHeroes = JSON.parse(superHeroesText);
populateHeader(superHeroes);
populateHeroes(superHeroes);
}
```
As you might guess, `stringify()` works the opposite way. Try entering the following lines into your browser's JavaScript console one by one to see it in action:
```js
let myObj = { name: "Chris", age: 38 };
myObj;
let myString = JSON.stringify(myObj);
myString;
```
Here we're creating a JavaScript object, then checking what it contains, then converting it to a JSON string using `stringify()` β saving the return value in a new variable β then checking it again.
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: JSON.
Summary
-------
In this article, we've given you a simple guide to using JSON in your programs, including how to create and parse JSON, and how to access data locked inside it. In the next article, we'll begin looking at object-oriented JavaScript.
See also
--------
* JSON reference
* Fetch API overview
* Using Fetch
* HTTP request methods
* Official JSON website with link to ECMA standard
* Previous
* Overview: Objects
* Next |
Arrays - Learn web development | Arrays
======
* Previous
* Overview: First steps
* Next
In the final article of this module, we'll look at arrays β a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of HTML and CSS, an
understanding of what JavaScript is.
|
| Objective: | To understand what arrays are and how to manipulate them in JavaScript. |
What is an array?
-----------------
Arrays are generally described as "list-like objects"; they are basically single objects that contain multiple values stored in a list. Array objects can be stored in variables and dealt with in much the same way as any other type of value, the difference being that we can access each value inside the list individually, and do super useful and efficient things with the list, like loop through it and do the same thing to every value. Maybe we've got a series of product items and their prices stored in an array, and we want to loop through them all and print them out on an invoice, while totaling all the prices together and printing out the total price at the bottom.
If we didn't have arrays, we'd have to store every item in a separate variable, then call the code that does the printing and adding separately for each item. This would be much longer to write out, less efficient, and more error-prone. If we had 10 items to add to the invoice it would already be annoying, but what about 100 items, or 1000? We'll return to this example later on in the article.
As in previous articles, let's learn about the real basics of arrays by entering some examples into browser developer console.
Creating arrays
---------------
Arrays consist of square brackets and items that are separated by commas.
1. Suppose we want to store a shopping list in an array. Paste the following code into the console:
```js
const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
console.log(shopping);
```
2. In the above example, each item is a string, but in an array we can store various data types β strings, numbers, objects, and even other arrays. We can also mix data types in a single array β we do not have to limit ourselves to storing only numbers in one array, and in another only strings. For example:
```js
const sequence = [1, 1, 2, 3, 5, 8, 13];
const random = ["tree", 795, [0, 1, 2]];
```
3. Before proceeding, create a few example arrays.
Finding the length of an array
------------------------------
You can find out the length of an array (how many items are in it) in exactly the same way as you find out the length (in characters) of a string β by using the `length` property. Try the following:
```js
const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
console.log(shopping.length); // 5
```
Accessing and modifying array items
-----------------------------------
Items in an array are numbered, starting from zero. This number is called the item's *index*. So the first item has index 0, the second has index 1, and so on. You can access individual items in the array using bracket notation and supplying the item's index, in the same way that you accessed the letters in a string.
1. Enter the following into your console:
```js
const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
console.log(shopping[0]);
// returns "bread"
```
2. You can also modify an item in an array by giving a single array item a new value. Try this:
```js
const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
shopping[0] = "tahini";
console.log(shopping);
// shopping will now return [ "tahini", "milk", "cheese", "hummus", "noodles" ]
```
**Note:** We've said it before, but just as a reminder β computers start counting from 0!
3. Note that an array inside an array is called a multidimensional array. You can access an item inside an array that is itself inside another array by chaining two sets of square brackets together. For example, to access one of the items inside the array that is the third item inside the `random` array (see previous section), we could do something like this:
```js
const random = ["tree", 795, [0, 1, 2]];
random[2][2];
```
4. Try making some more modifications to your array examples before moving on. Play around a bit, and see what works and what doesn't.
Finding the index of items in an array
--------------------------------------
If you don't know the index of an item, you can use the `indexOf()` method.
The `indexOf()` method takes an item as an argument and will either return the item's index or `-1` if the item is not in the array:
```js
const birds = ["Parrot", "Falcon", "Owl"];
console.log(birds.indexOf("Owl")); // 2
console.log(birds.indexOf("Rabbit")); // -1
```
Adding items
------------
To add one or more items to the end of an array we can use `push()`. Note that you need to include one or more items that you want to add to the end of your array.
```js
const cities = ["Manchester", "Liverpool"];
cities.push("Cardiff");
console.log(cities); // [ "Manchester", "Liverpool", "Cardiff" ]
cities.push("Bradford", "Brighton");
console.log(cities); // [ "Manchester", "Liverpool", "Cardiff", "Bradford", "Brighton" ]
```
The new length of the array is returned when the method call completes. If you wanted to store the new array length in a variable, you could do something like this:
```js
const cities = ["Manchester", "Liverpool"];
const newLength = cities.push("Bristol");
console.log(cities); // [ "Manchester", "Liverpool", "Bristol" ]
console.log(newLength); // 3
```
To add an item to the start of the array, use `unshift()`:
```js
const cities = ["Manchester", "Liverpool"];
cities.unshift("Edinburgh");
console.log(cities); // [ "Edinburgh", "Manchester", "Liverpool" ]
```
Removing items
--------------
To remove the last item from the array, use `pop()`.
```js
const cities = ["Manchester", "Liverpool"];
cities.pop();
console.log(cities); // [ "Manchester" ]
```
The `pop()` method returns the item that was removed. To save that item in a new variable, you could do this:
```js
const cities = ["Manchester", "Liverpool"];
const removedCity = cities.pop();
console.log(removedCity); // "Liverpool"
```
To remove the first item from an array, use `shift()`:
```js
const cities = ["Manchester", "Liverpool"];
cities.shift();
console.log(cities); // [ "Liverpool" ]
```
If you know the index of an item, you can remove it from the array using `splice()`:
```js
const cities = ["Manchester", "Liverpool", "Edinburgh", "Carlisle"];
const index = cities.indexOf("Liverpool");
if (index !== -1) {
cities.splice(index, 1);
}
console.log(cities); // [ "Manchester", "Edinburgh", "Carlisle" ]
```
In this call to `splice()`, the first argument says where to start removing items, and the second argument says how many items should be removed. So you can remove more than one item:
```js
const cities = ["Manchester", "Liverpool", "Edinburgh", "Carlisle"];
const index = cities.indexOf("Liverpool");
if (index !== -1) {
cities.splice(index, 2);
}
console.log(cities); // [ "Manchester", "Carlisle" ]
```
Accessing every item
--------------------
Very often you will want to access every item in the array. You can do this using the `for...of` statement:
```js
const birds = ["Parrot", "Falcon", "Owl"];
for (const bird of birds) {
console.log(bird);
}
```
Sometimes you will want to do the same thing to each item in an array, leaving you with an array containing the changed items. You can do this using `map()`. The code below takes an array of numbers and doubles each number:
```js
function double(number) {
return number \* 2;
}
const numbers = [5, 2, 7, 6];
const doubled = numbers.map(double);
console.log(doubled); // [ 10, 4, 14, 12 ]
```
We give a function to the `map()`, and `map()` calls the function once for each item in the array, passing in the item. It then adds the return value from each function call to a new array, and finally returns the new array.
Sometimes you'll want to create a new array containing only the items in the original array that match some test. You can do that using `filter()`. The code below takes an array of strings and returns an array containing just the strings that are greater than 8 characters long:
```js
function isLong(city) {
return city.length > 8;
}
const cities = ["London", "Liverpool", "Totnes", "Edinburgh"];
const longer = cities.filter(isLong);
console.log(longer); // [ "Liverpool", "Edinburgh" ]
```
Like `map()`, we give a function to the `filter()` method, and `filter()` calls this function for every item in the array, passing in the item. If the function returns `true`, then the item is added to a new array. Finally it returns the new array.
Converting between strings and arrays
-------------------------------------
Often you'll be presented with some raw data contained in a big long string, and you might want to separate the useful items out into a more useful form and then do things to them, like display them in a data table. To do this, we can use the `split()` method. In its simplest form, this takes a single parameter, the character you want to separate the string at, and returns the substrings between the separator as items in an array.
**Note:** Okay, this is technically a string method, not an array method, but we've put it in with arrays as it goes well here.
1. Let's play with this, to see how it works. First, create a string in your console:
```js
const data = "Manchester,London,Liverpool,Birmingham,Leeds,Carlisle";
```
2. Now let's split it at each comma:
```js
const cities = data.split(",");
cities;
```
3. Finally, try finding the length of your new array, and retrieving some items from it:
```js
cities.length;
cities[0]; // the first item in the array
cities[1]; // the second item in the array
cities[cities.length - 1]; // the last item in the array
```
4. You can also go the opposite way using the `join()` method. Try the following:
```js
const commaSeparated = cities.join(",");
commaSeparated;
```
5. Another way of converting an array to a string is to use the `toString()` method. `toString()` is arguably simpler than `join()` as it doesn't take a parameter, but more limiting. With `join()` you can specify different separators, whereas `toString()` always uses a comma. (Try running Step 4 with a different character than a comma.)
```js
const dogNames = ["Rocket", "Flash", "Bella", "Slugger"];
dogNames.toString(); // Rocket,Flash,Bella,Slugger
```
Active learning: Printing those products
----------------------------------------
Let's return to the example we described earlier β printing out product names and prices on an invoice, then totaling the prices and printing them at the bottom. In the editable example below there are comments containing numbers β each of these marks a place where you have to add something to the code. They are as follows:
1. Below the `// number 1` comment are a number of strings, each one containing a product name and price separated by a colon. We'd like you to turn this into an array and store it in an array called `products`.
2. Below the `// number 2` comment, start a `for...of()` loop to go through every item in the `products` array.
3. Below the `// number 3` comment we want you to write a line of code that splits the current array item (`name:price`) into two separate items, one containing just the name and one containing just the price. If you are not sure how to do this, consult the Useful string methods article for some help, or even better, look at the Converting between strings and arrays section of this article.
4. As part of the above line of code, you'll also want to convert the price from a string to a number. If you can't remember how to do this, check out the first strings article.
5. There is a variable called `total` that is created and given a value of 0 at the top of the code. Inside the loop (below `// number 4`) we want you to add a line that adds the current item price to that total in each iteration of the loop, so that at the end of the code the correct total is printed onto the invoice. You might need an assignment operator to do this.
6. We want you to change the line just below `// number 5` so that the `itemText` variable is made equal to "current item name β $current item price", for example "Shoes β $23.99" in each case, so the correct information for each item is printed on the invoice. This is just simple string concatenation, which should be familiar to you.
7. Finally, below the `// number 6` comment, you'll need to add a `}` to mark the end of the `for...of()` loop.
```
<h2>Live output</h2>
<div class="output" style="min-height: 150px;">
<ul></ul>
<p></p>
</div>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 410px;width: 95%">
const list = document.querySelector('.output ul');
const totalBox = document.querySelector('.output p');
let total = 0;
list.innerHTML = '';
totalBox.textContent = '';
// number 1
'Underpants:6.99'
'Socks:5.99'
'T-shirt:14.99'
'Trousers:31.99'
'Shoes:23.99';
// number 2
// number 3
// number 4
// number 5
let itemText = 0;
const listItem = document.createElement('li');
listItem.textContent = itemText;
list.appendChild(listItem);
// number 6
totalBox.textContent = 'Total: $' + total.toFixed(2);
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = "Show solution";
updateCode();
});
solution.addEventListener("click", () => {
if (solution.value === "Show solution") {
textarea.value = solutionEntry;
solution.value = "Hide solution";
} else {
textarea.value = userEntry;
solution.value = "Show solution";
}
updateCode();
});
const jsSolution = `const list = document.querySelector('.output ul');
const totalBox = document.querySelector('.output p');
let total = 0;
list.innerHTML = '';
totalBox.textContent = '';
const products = [
'Underpants:6.99',
'Socks:5.99',
'T-shirt:14.99',
'Trousers:31.99',
'Shoes:23.99',
];
for (const product of products) {
const subArray = product.split(':');
const name = subArray[0];
const price = Number(subArray[1]);
total += price;
const itemText = \`\${name} β $\${price}\`;
const listItem = document.createElement('li');
listItem.textContent = itemText;
list.appendChild(listItem);
}
totalBox.textContent = \`Total: $\${total.toFixed(2)}\`;`;
let solutionEntry = jsSolution;
textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
const KEY\_TAB = 9;
const KEY\_ESC = 27;
textarea.onkeydown = (event) => {
if (event.keyCode === KEY\_TAB) {
event.preventDefault();
insertAtCaret("\t");
}
if (event.keyCode === KEY\_ESC) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = () => {
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if (solution.value === "Show solution") {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
```
```
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background-color: #f5f9fa;
}
```
Active learning: Top 5 searches
-------------------------------
A good use for array methods like `push()` and `pop()` is when you are maintaining a record of currently active items in a web app. In an animated scene for example, you might have an array of objects representing the background graphics currently displayed, and you might only want 50 displayed at once, for performance or clutter reasons. As new objects are created and added to the array, older ones can be deleted from the array to maintain the desired number.
In this example we're going to show a much simpler use β here we're giving you a fake search site, with a search box. The idea is that when terms are entered in the search box, the top 5 previous search terms are displayed in the list. When the number of terms goes over 5, the last term starts being deleted each time a new term is added to the top, so the 5 previous terms are always displayed.
**Note:** In a real search app, you'd probably be able to click the previous search terms to return to previous searches, and it would display actual search results! We are just keeping it simple for now.
To complete the app, we need you to:
1. Add a line below the `// number 1` comment that adds the current value entered into the search input to the start of the array. This can be retrieved using `searchInput.value`.
2. Add a line below the `// number 2` comment that removes the value currently at the end of the array.
```
<h2>Live output</h2>
<div class="output" style="min-height: 150px;">
<input type="text" /><button>Search</button>
<ul></ul>
</div>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 370px; width: 95%">
const list = document.querySelector('.output ul');
const searchInput = document.querySelector('.output input');
const searchBtn = document.querySelector('.output button');
list.innerHTML = '';
const myHistory = [];
const MAX_HISTORY = 5;
searchBtn.onclick = () => {
// we will only allow a term to be entered if the search input isn't empty
if (searchInput.value !== '') {
// number 1
// empty the list so that we don't display duplicate entries
// the display is regenerated every time a search term is entered.
list.innerHTML = '';
// loop through the array, and display all the search terms in the list
for (const itemText of myHistory) {
const listItem = document.createElement('li');
listItem.textContent = itemText;
list.appendChild(listItem);
}
// If the array length is 5 or more, remove the oldest search term
if (myHistory.length >= MAX_HISTORY) {
// number 2
}
// empty the search input and focus it, ready for the next term to be entered
searchInput.value = '';
searchInput.focus();
}
}
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = "Show solution";
updateCode();
});
solution.addEventListener("click", () => {
if (solution.value === "Show solution") {
textarea.value = solutionEntry;
solution.value = "Hide solution";
} else {
textarea.value = userEntry;
solution.value = "Show solution";
}
updateCode();
});
const jsSolution = `const list = document.querySelector('.output ul');
const searchInput = document.querySelector('.output input');
const searchBtn = document.querySelector('.output button');
list.innerHTML = '';
const myHistory = [];
const MAX\_HISTORY = 5;
searchBtn.onclick = () => {
// we will only allow a term to be entered if the search input isn't empty
if (searchInput.value !== '') {
myHistory.unshift(searchInput.value);
// empty the list so that we don't display duplicate entries
// the display is regenerated every time a search term is entered.
list.innerHTML = '';
// loop through the array, and display all the search terms in the list
for (const itemText of myHistory) {
const listItem = document.createElement('li');
listItem.textContent = itemText;
list.appendChild(listItem);
}
// If the array length is 5 or more, remove the oldest search term
if (myHistory.length >= MAX\_HISTORY) {
myHistory.pop();
}
// empty the search input and focus it, ready for the next term to be entered
searchInput.value = '';
searchInput.focus();
}
}`;
let solutionEntry = jsSolution;
textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
const KEY\_TAB = 9;
const KEY\_ESC = 27;
textarea.onkeydown = (event) => {
if (event.keyCode === KEY\_TAB) {
event.preventDefault();
insertAtCaret("\t");
}
if (event.keyCode === KEY\_ESC) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = () => {
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if (solution.value === "Show solution") {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
```
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Arrays.
Conclusion
----------
After reading through this article, we are sure you will agree that arrays seem pretty darn useful; you'll see them crop up everywhere in JavaScript, often in association with loops in order to do the same thing to every item in an array. We'll be teaching you all the useful basics there are to know about loops in the next module, but for now you should give yourself a clap and take a well-deserved break; you've worked through all the articles in this module!
The only thing left to do is work through this module's assessment, which will test your understanding of the articles that came before it.
See also
--------
* Indexed collections β an advanced level guide to arrays and their cousins, typed arrays.
* `Array` β the `Array` object reference page β for a detailed reference guide to the features discussed in this page, and many more.
* Previous
* Overview: First steps
* Next |
Silly story generator - Learn web development | Silly story generator
=====================
* Previous
* Overview: First steps
In this assessment you'll be tasked with taking some of the knowledge you've picked up in this module's articles and applying it to creating a fun app that generates random silly stories. Have fun!
| | |
| --- | --- |
| Prerequisites: |
Before attempting this assessment you should have already worked through
all the articles in this module.
|
| Objective: |
To test comprehension of JavaScript fundamentals, such as variables,
numbers, operators, strings, and arrays.
|
Starting point
--------------
To get this assessment started, you should:
* Go and grab the HTML file for the example, save a local copy of it as `index.html` in a new directory somewhere on your computer, and do the assessment locally to begin with. This also has the CSS to style the example contained within it.
* Go to the page containing the raw text and keep this open in a separate browser tab somewhere. You'll need it later.
Alternatively, you could use an online editor such as CodePen, JSFiddle, or Glitch. You could paste the HTML, CSS and JavaScript into one of these online editors. If the online editor you are using doesn't have a separate JavaScript panel, feel free to put it inline in a `<script>` element inside the HTML page.
**Note:** If you get stuck, you can reach out to us in one of our communication channels.
Project brief
-------------
You have been provided with some raw HTML/CSS and a few text strings and JavaScript functions; you need to write the necessary JavaScript to turn this into a working program, which does the following:
* Generates a silly story when the "Generate random story" button is pressed.
* Replaces the default name "Bob" in the story with a custom name, only if a custom name is entered into the "Enter custom name" text field before the generate button is pressed.
* Converts the default US weight and temperature quantities and units in the story into UK equivalents if the UK radio button is checked before the generate button is pressed.
* Generates a new random silly story every time the button is pressed.
The following screenshot shows an example of what the finished program should output:
![The silly story generator app consists of a text field, two radio buttons, and a button to generate a random story.](/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator/screen_shot_2018-09-19_at_10.01.38_am.png)
To give you more of an idea, have a look at the finished example (no peeking at the source code!)
Steps to complete
-----------------
The following sections describe what you need to do.
Basic setup:
1. Create a new file called `main.js`, in the same directory as your `index.html` file.
2. Apply the external JavaScript file to your HTML by inserting a `<script>` element into your HTML referencing `main.js`. Put it just before the closing `</body>` tag.
Initial variables and functions:
1. In the raw text file, copy all of the code underneath the heading "1. COMPLETE VARIABLE AND FUNCTION DEFINITIONS" and paste it into the top of the `main.js` file. This gives you three variables that store references to the "Enter custom name" text field (`customName`), the "Generate random story" button (`randomize`), and the `<p>` element at the bottom of the HTML body that the story will be copied into (`story`), respectively. In addition you've got a function called `randomValueFromArray()` that takes an array, and returns one of the items stored inside the array at random.
2. Now look at the second section of the raw text file β "2. RAW TEXT STRINGS". This contains text strings that will act as input into our program. We'd like you to contain these inside variables inside `main.js`:
1. Store the first, big long, string of text inside a variable called `storyText`.
2. Store the first set of three strings inside an array called `insertX`.
3. Store the second set of three strings inside an array called `insertY`.
4. Store the third set of three strings inside an array called `insertZ`.
Placing the event handler and incomplete function:
1. Now return to the raw text file.
2. Copy the code found underneath the heading "3. EVENT LISTENER AND PARTIAL FUNCTION DEFINITION" and paste it into the bottom of your `main.js` file. This:
* Adds a click event listener to the `randomize` variable so that when the button it represents is clicked, the `result()` function is run.
* Adds a partially-completed `result()` function definition to your code. For the remainder of the assessment, you'll be filling in lines inside this function to complete it and make it work properly.
Completing the `result()` function:
1. Create a new variable called `newStory`, and set its value to equal `storyText`. This is needed so we can create a new random story each time the button is pressed and the function is run. If we made changes directly to `storyText`, we'd only be able to generate a new story once.
2. Create three new variables called `xItem`, `yItem`, and `zItem`, and make them equal to the result of calling `randomValueFromArray()` on your three arrays (the result in each case will be a random item out of each array it is called on). For example you can call the function and get it to return one random string out of `insertX` by writing `randomValueFromArray(insertX)`.
3. Next we want to replace the three placeholders in the `newStory` string β `:insertx:`, `:inserty:`, and `:insertz:` β with the strings stored in `xItem`, `yItem`, and `zItem`. There are two possible string methods that will help you here β in each case, make the call to the method equal to `newStory`, so each time it is called, `newStory` is made equal to itself, but with substitutions made. So each time the button is pressed, these placeholders are each replaced with a random silly string. As a further hint, depending on the method you choose, you might need to make one of the calls twice.
4. Inside the first `if` block, add another string replacement method call to replace the name 'Bob' found in the `newStory` string with the `name` variable. In this block we are saying "If a value has been entered into the `customName` text input, replace Bob in the story with that custom name."
5. Inside the second `if` block, we are checking to see if the `uk` radio button has been selected. If so, we want to convert the weight and temperature values in the story from pounds and Fahrenheit into stones and centigrade. What you need to do is as follows:
1. Look up the formulas for converting pounds to stone, and Fahrenheit to centigrade.
2. Inside the line that defines the `weight` variable, replace 300 with a calculation that converts 300 pounds into stones. Concatenate `' stone'` onto the end of the result of the overall `Math.round()` call.
3. Inside the line that defines the `temperature` variable, replace 94 with a calculation that converts 94 Fahrenheit into centigrade. Concatenate `' centigrade'` onto the end of the result of the overall `Math.round()` call.
4. Just under the two variable definitions, add two more string replacement lines that replace '94 fahrenheit' with the contents of the `temperature` variable, and '300 pounds' with the contents of the `weight` variable.
6. Finally, in the second-to-last line of the function, make the `textContent` property of the `story` variable (which references the paragraph) equal to `newStory`.
Hints and tips
--------------
* You don't need to edit the HTML in any way, except to apply the JavaScript to your HTML.
* If you are unsure whether the JavaScript is applied to your HTML properly, try removing everything else from the JavaScript file temporarily, adding in a simple bit of JavaScript that you know will create an obvious effect, then saving and refreshing. The following for example turns the background of the `<html>` element red β so the entire browser window should go red if the JavaScript is applied properly:
```js
document.querySelector("html").style.backgroundColor = "red";
```
* `Math.round()` is a built-in JavaScript method that rounds the result of a calculation to the nearest whole number.
* There are three instances of strings that need to be replaced. You may repeat the `replace()` method multiple times, or you can use `replaceAll()`. Remember, Strings are immutable!
* Previous
* Overview: First steps |
What went wrong? Troubleshooting JavaScript - Learn web development | What went wrong? Troubleshooting JavaScript
===========================================
* Previous
* Overview: First steps
* Next
When you built up the "Guess the number" game in the previous article, you may have found that it didn't work. Never fear β this article aims to save you from tearing your hair out over such problems by providing you with some tips on how to find and fix errors in JavaScript programs.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of HTML and CSS, an
understanding of what JavaScript is.
|
| Objective: |
To gain the ability and confidence to start fixing problems in your own
code.
|
Types of error
--------------
Generally speaking, when you do something wrong in code, there are two main types of error that you'll come across:
* **Syntax errors**: These are spelling errors in your code that actually cause the program not to run at all, or stop working part way through β you will usually be provided with some error messages too. These are usually okay to fix, as long as you are familiar with the right tools and know what the error messages mean!
* **Logic errors**: These are errors where the syntax is actually correct but the code is not what you intended it to be, meaning that program runs successfully but gives incorrect results. These are often harder to fix than syntax errors, as there usually isn't an error message to direct you to the source of the error.
Okay, so it's not quite *that* simple β there are some other differentiators as you drill down deeper. But the above classifications will do at this early stage in your career. We'll look at both of these types going forward.
An erroneous example
--------------------
To get started, let's return to our number guessing game β except this time we'll be exploring a version that has some deliberate errors introduced. Go to GitHub and make yourself a local copy of number-game-errors.html (see it running live here).
1. To get started, open the local copy inside your favorite text editor, and your browser.
2. Try playing the game β you'll notice that when you press the "Submit guess" button, it doesn't work!
**Note:** You might well have your own version of the game example that doesn't work, which you might want to fix! We'd still like you to work through the article with our version, so that you can learn the techniques we are teaching here. Then you can go back and try to fix your example.
At this point, let's consult the developer console to see if it reports any syntax errors, then try to fix them. You'll learn how below.
Fixing syntax errors
--------------------
Earlier on in the course we got you to type some simple JavaScript commands into the developer tools JavaScript console (if you can't remember how to open this in your browser, follow the previous link to find out how). What's even more useful is that the console gives you error messages whenever a syntax error exists inside the JavaScript being fed into the browser's JavaScript engine. Now let's go hunting.
1. Go to the tab that you've got `number-game-errors.html` open in, and open your JavaScript console. You should see an error message along the following lines:
!["Number guessing game" demo page in Firefox. One error is visible in the JavaScript console: "X TypeError: guessSubmit.addeventListener is not a function [Learn More] (number-game-errors.html:86:3)".](/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong/not-a-function.png)
2. The first line of the error message is:
```
Uncaught TypeError: guessSubmit.addeventListener is not a function
number-game-errors.html:86:15
```
* The first part, `Uncaught TypeError: guessSubmit.addeventListener is not a function`, is telling us something about what went wrong.
* The second part, `number-game-errors.html:86:15`, is telling us where in the code the error came from: line 86, character 15 of the file "number-game-errors.html".
3. If we look at line 86 in our code editor, we'll find this line:
**Warning:** Error message may not be on line 86.
If you are using any code editor with an extension that launches a live server on your local machine, this will cause extra code to be injected. Because of this, the developer tools will list the error as occurring on a line that is not 86.
```js
guessSubmit.addeventListener("click", checkGuess);
```
4. The error message says "guessSubmit.addeventListener is not a function", which means that the function we're calling is not recognized by the JavaScript interpreter. Often, this error message actually means that we've spelled something wrong. If you are not sure of the correct spelling of a piece of syntax, it is often good to look up the feature on MDN. The best way to do this currently is to search for "mdn *name-of-feature*" with your favorite search engine. Here's a shortcut to save you some time in this instance: `addEventListener()`.
5. So, looking at this page, the error appears to be that we've spelled the function name wrong! Remember that JavaScript is case-sensitive, so any slight difference in spelling or casing will cause an error. Changing `addeventListener` to `addEventListener` should fix this. Do this now.
**Note:** See our TypeError: "x" is not a function reference page for more details about this error.
### Syntax errors round two
1. Save your page and refresh, and you should see the error has gone.
2. Now if you try to enter a guess and press the Submit guess button, you'll see another error!
![Screenshot of the same "Number guessing game" demo. This time, a different error is visible in the console, reading "X TypeError: lowOrHi is null".](/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong/variable-is-null.png)
3. This time the error being reported is:
```
Uncaught TypeError: can't access property "textContent", lowOrHi is null
```
Depending on the browser you are using, you might see a different message here. The message above is what Firefox will show you, but Chrome, for example, will show you this:
```
Uncaught TypeError: Cannot set properties of null (setting 'textContent')
```
It's the same error, but different browsers describe it in a different way.
**Note:** This error didn't come up as soon as the page was loaded because this error occurred inside a function (inside the `checkGuess() { }` block). As you'll learn in more detail in our later functions article, code inside functions runs in a separate scope than code outside functions. In this case, the code was not run and the error was not thrown until the `checkGuess()` function was run by line 86.
4. The line number given in the error is 80. Have a look at line 80, and you'll see the following code:
```js
lowOrHi.textContent = "Last guess was too high!";
```
5. This line is trying to set the `textContent` property of the `lowOrHi` variable to a text string, but it's not working because `lowOrHi` does not contain what it's supposed to. Let's see why this is β try searching for other instances of `lowOrHi` in the code. The earliest instance you'll find is on line 49:
```js
const lowOrHi = document.querySelector("lowOrHi");
```
6. At this point we are trying to make the variable contain a reference to an element in the document's HTML. Let's see what the variable contains after this line has been run. Add the following code on line 50:
```js
console.log(lowOrHi);
```
This code will print the value of `lowOrHi` to the console after we tried to set it in line 49. See `console.log()` for more information.
7. Save and refresh, and you should now see the `console.log()` result in your console.
![Screenshot of the same demo. One log statement is visible in the console, reading simply "null".](/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong/console-log-output.png) Sure enough, `lowOrHi`'s value is `null` at this point, and this matches up with the Firefox error message `lowOrHi is null`. So there is definitely a problem with line 49. The `null` value means "nothing", or "no value". So our code to set `lowOrHi` to an element is going wrong.
8. Let's think about what the problem could be. Line 49 is using a `document.querySelector()` method to get a reference to an element by selecting it with a CSS selector. Looking further up our file, we can find the paragraph in question:
```html
<p class="lowOrHi"></p>
```
9. So we need a class selector here, which begins with a dot (`.`), but the selector being passed into the `querySelector()` method in line 49 has no dot. This could be the problem! Try changing `lowOrHi` to `.lowOrHi` in line 49.
10. Try saving and refreshing again, and your `console.log()` statement should return the `<p>` element we want. Phew! Another error fixed! You can delete your `console.log()` line now, or keep it to reference later on β your choice.
**Note:** See our TypeError: "x" is (not) "y" reference page for more details about this error.
### Syntax errors round three
1. Now if you try playing the game through again, you should get more success β the game should play through absolutely fine, until you end the game, either by guessing the right number, or by running out of guesses.
2. At that point, the game fails again, and the same error is spat out that we got at the beginning β "TypeError: resetButton.addeventListener is not a function"! However, this time it's listed as coming from line 94.
3. Looking at line number 94, it is easy to see that we've made the same mistake here. We again just need to change `addeventListener` to `addEventListener`. Do this now.
A logic error
-------------
At this point, the game should play through fine, however after playing through a few times you'll undoubtedly notice that the game always chooses 1 as the "random" number you've got to guess. Definitely not quite how we want the game to play out!
There's definitely a problem in the game logic somewhere β the game is not returning an error; it just isn't playing right.
1. Search for the `randomNumber` variable, and the lines where the random number is first set. The instance that stores the random number that we want to guess at the start of the game should be around line number 45:
```js
let randomNumber = Math.floor(Math.random()) + 1;
```
2. And the one that generates the random number before each subsequent game is around line 113:
```js
randomNumber = Math.floor(Math.random()) + 1;
```
3. To check whether these lines are indeed the problem, let's turn to our friend `console.log()` again β insert the following line directly below each of the above two lines:
```js
console.log(randomNumber);
```
4. Save and refresh, then play a few games β you'll see that `randomNumber` is equal to 1 at each point where it is logged to the console.
### Working through the logic
To fix this, let's consider how this line is working. First, we invoke `Math.random()`, which generates a random decimal number between 0 and 1, e.g. 0.5675493843.
```js
Math.random();
```
Next, we pass the result of invoking `Math.random()` through `Math.floor()`, which rounds the number passed to it down to the nearest whole number. We then add 1 to that result:
```js
Math.floor(Math.random()) + 1;
```
Rounding a random decimal number between 0 and 1 down will always return 0, so adding 1 to it will always return 1. We need to multiply the random number by 100 before we round it down. The following would give us a random number between 0 and 99:
```js
Math.floor(Math.random() \* 100);
```
Hence us wanting to add 1, to give us a random number between 1 and 100:
```js
Math.floor(Math.random() \* 100) + 1;
```
Try updating both lines like this, then save and refresh β the game should now play like we are intending it to!
Other common errors
-------------------
There are other common errors you'll come across in your code. This section highlights most of them.
### SyntaxError: missing ; before statement
This error generally means that you have missed a semicolon at the end of one of your lines of code, but it can sometimes be more cryptic. For example, if we change this line inside the `checkGuess()` function:
```js
const userGuess = Number(guessField.value);
```
to
```js
const userGuess === Number(guessField.value);
```
It throws this error because it thinks you are trying to do something different. You should make sure that you don't mix up the assignment operator (`=`) β which sets a variable to be equal to a value β with the strict equality operator (`===`), which tests whether one value is equal to another, and returns a `true`/`false` result.
**Note:** See our SyntaxError: missing ; before statement reference page for more details about this error.
### The program always says you've won, regardless of the guess you enter
This could be another symptom of mixing up the assignment and strict equality operators. For example, if we were to change this line inside `checkGuess()`:
```js
if (userGuess === randomNumber) {
```
to
```js
if (userGuess = randomNumber) {
```
the test would always return `true`, causing the program to report that the game has been won. Be careful!
### SyntaxError: missing ) after argument list
This one is pretty simple β it generally means that you've missed the closing parenthesis at the end of a function/method call.
**Note:** See our SyntaxError: missing ) after argument list reference page for more details about this error.
### SyntaxError: missing : after property id
This error usually relates to an incorrectly formed JavaScript object, but in this case we managed to get it by changing
```js
function checkGuess() {
```
to
```js
function checkGuess( {
```
This has caused the browser to think that we are trying to pass the contents of the function into the function as an argument. Be careful with those parentheses!
### SyntaxError: missing } after function body
This is easy β it generally means that you've missed one of your curly braces from a function or conditional structure. We got this error by deleting one of the closing curly braces near the bottom of the `checkGuess()` function.
### SyntaxError: expected expression, got '*string*' or SyntaxError: unterminated string literal
These errors generally mean that you've left off a string value's opening or closing quote mark. In the first error above, *string* would be replaced with the unexpected character(s) that the browser found instead of a quote mark at the start of a string. The second error means that the string has not been ended with a quote mark.
For all of these errors, think about how we tackled the examples we looked at in the walkthrough. When an error arises, look at the line number you are given, go to that line and see if you can spot what's wrong. Bear in mind that the error is not necessarily going to be on that line, and also that the error might not be caused by the exact same problem we cited above!
**Note:** See our SyntaxError: Unexpected token and SyntaxError: unterminated string literal reference pages for more details about these errors.
Summary
-------
So there we have it, the basics of figuring out errors in simple JavaScript programs. It won't always be that simple to work out what's wrong in your code, but at least this will save you a few hours of sleep and allow you to progress a bit faster when things don't turn out right, especially in the earlier stages of your learning journey.
See also
--------
* There are many other types of errors that aren't listed here; we are compiling a reference that explains what they mean in detail β see the JavaScript error reference.
* If you come across any errors in your code that you aren't sure how to fix after reading this article, you can get help! Ask for help on the communication channels. Tell us what your error is, and we'll try to help you. A listing of your code would be useful as well.
* Previous
* Overview: First steps
* Next |
Test your skills: Strings - Learn web development | Test your skills: Strings
=========================
The aim of this skill test is to assess whether you've understood our Handling text β strings in JavaScript and Useful string methods articles.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
**Note:** In the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version).
Strings 1
---------
In our first strings task, we start off small. You already have half of a famous quote inside a variable called `quoteStart`; we would like you to:
1. Look up the other half of the quote, and add it to the example inside a variable called `quoteEnd`.
2. Concatenate the two strings together to make a single string containing the complete quote. Save the result inside a variable called `finalQuote`.
You'll find that you get an error at this point. Can you fix the problem with `quoteStart`, so that the full quote displays correctly?
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Strings 2
---------
In this task you are provided with two variables, `quote` and `substring`, which contain two strings. We would like you to:
1. Retrieve the length of the quote, and store it in a variable called `quoteLength`.
2. Find the index position where `substring` appears in `quote`, and store that value in a variable called `index`.
3. Use a combination of the variables you have and available string properties/methods to trim down the original quote to "I do not like green eggs and ham.", and store it in a variable called `revisedQuote`.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Strings 3
---------
In the next string task, you are given the same quote that you ended up with in the previous task, but it is somewhat broken! We want you to fix and update it, like so:
1. Change the casing to correct sentence case (all lowercase, except for upper case first letter). Store the new quote in a variable called `fixedQuote`.
2. In `fixedQuote`, replace "green eggs and ham" with another food that you really don't like.
3. There is one more small fix to do β add a full stop onto the end of the quote, and save the final version in a variable called `finalQuote`.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Strings 4
---------
In the final string task, we have given you the name of a theorem, two numeric values, and an incomplete string (the bits that need adding are marked with asterisks (`*`)). We want you to change the value of the string as follows:
1. Change it from a regular string literal into a template literal.
2. Replace the four asterisks with four template literal placeholders. These should be:
1. The name of the theorem.
2. The two number values we have.
3. The length of the hypotenuse of a right-angled triangle, given that the two other side lengths are the same as the two values we have. You'll need to look up how to calculate this from what you have. Do the calculation inside the placeholder.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
Test your skills: variables - Learn web development | Test your skills: variables
===========================
The aim of this skill test is to assess whether you've understood our Storing the information you need β Variables article.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If there is an error in your code, it will be logged into the results panel on this page or in the JavaScript console.
If you get stuck, you can reach out to us in one of our communication channels.
Variables 1
-----------
In this task we want you to:
* Declare a variable called `myName`.
* Initialize `myName` with a suitable value, on a separate line (you can use your actual name, or something else).
* Declare a variable called `myAge` and initialize it with a value, on the same line.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Variables 2
-----------
In this task you need to add a new line to correct the value stored in the existing `myName` variable to your own name.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Variables 3
-----------
The final task for now β in this case you are provided with some existing code, which has two errors present in it. The results panel should be outputting the name `Chris`, and a statement about how old Chris will be in 20 years' time. How can you fix the problem and correct the output?
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
Basic math in JavaScript β numbers and operators - Learn web development | Basic math in JavaScript β numbers and operators
================================================
* Previous
* Overview: First steps
* Next
At this point in the course, we discuss math in JavaScript β how we can use operators and other features to successfully manipulate numbers to do our bidding.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of HTML and CSS, an
understanding of what JavaScript is.
|
| Objective: | To gain familiarity with the basics of math in JavaScript. |
Everybody loves math
--------------------
Okay, maybe not. Some of us like math, some of us have hated math ever since we had to learn multiplication tables and long division in school, and some of us sit somewhere in between the two. But none of us can deny that math is a fundamental part of life that we can't get very far without. This is especially true when we are learning to program JavaScript (or any other language for that matter) β so much of what we do relies on processing numerical data, calculating new values, and so on, that you won't be surprised to learn that JavaScript has a full-featured set of math functions available.
This article discusses only the basic parts that you need to know now.
### Types of numbers
In programming, even the humble decimal number system that we all know so well is more complicated than you might think. We use different terms to describe different types of decimal numbers, for example:
* **Integers** are floating-point numbers without a fraction. They can either be positive or negative, e.g. 10, 400, or -5.
* **Floating point numbers** (floats) have decimal points and decimal places, for example 12.5, and 56.7786543.
* **Doubles** are a specific type of floating point number that have greater precision than standard floating point numbers (meaning that they are accurate to a greater number of decimal places).
We even have different types of number systems! Decimal is base 10 (meaning it uses 0β9 in each column), but we also have things like:
* **Binary** β The lowest level language of computers; 0s and 1s.
* **Octal** β Base 8, uses 0β7 in each column.
* **Hexadecimal** β Base 16, uses 0β9 and then aβf in each column. You may have encountered these numbers before when setting colors in CSS.
**Before you start to get worried about your brain melting, stop right there!** For a start, we are just going to stick to decimal numbers throughout this course; you'll rarely come across a need to start thinking about other types, if ever.
The second bit of good news is that unlike some other programming languages, JavaScript only has one data type for numbers, both integers and decimals β you guessed it, `Number`. This means that whatever type of numbers you are dealing with in JavaScript, you handle them in exactly the same way.
**Note:** Actually, JavaScript has a second number type, BigInt, used for very, very large integers. But for the purposes of this course, we'll just worry about `Number` values.
### It's all numbers to me
Let's quickly play with some numbers to reacquaint ourselves with the basic syntax we need. Enter the commands listed below into your developer tools JavaScript console.
1. First of all, let's declare a couple of variables and initialize them with an integer and a float, respectively, then type the variable names back in to check that everything is in order:
```js
const myInt = 5;
const myFloat = 6.667;
myInt;
myFloat;
```
2. Number values are typed in without quote marks β try declaring and initializing a couple more variables containing numbers before you move on.
3. Now let's check that both our original variables are of the same datatype. There is an operator called `typeof` in JavaScript that does this. Enter the below two lines as shown:
```js
typeof myInt;
typeof myFloat;
```
You should get `"number"` returned in both cases β this makes things a lot easier for us than if different numbers had different data types, and we had to deal with them in different ways. Phew!
### Useful Number methods
The `Number` object, an instance of which represents all standard numbers you'll use in your JavaScript, has a number of useful methods available on it for you to manipulate numbers. We don't cover these in detail in this article because we wanted to keep it as a simple introduction and only cover the real basic essentials for now; however, once you've read through this module a couple of times it is worth going to the object reference pages and learning more about what's available.
For example, to round your number to a fixed number of decimal places, use the `toFixed()` method. Type the following lines into your browser's console:
```js
const lotsOfDecimal = 1.766584958675746364;
lotsOfDecimal;
const twoDecimalPlaces = lotsOfDecimal.toFixed(2);
twoDecimalPlaces;
```
### Converting to number data types
Sometimes you might end up with a number that is stored as a string type, which makes it difficult to perform calculations with it. This most commonly happens when data is entered into a form input, and the input type is text. There is a way to solve this problem β passing the string value into the `Number()` constructor to return a number version of the same value.
For example, try typing these lines into your console:
```js
let myNumber = "74";
myNumber += 3;
```
You end up with the result 743, not 77, because `myNumber` is actually defined as a string. You can test this by typing in the following:
```js
typeof myNumber;
```
To fix the calculation, you can do this:
```js
let myNumber = "74";
myNumber = Number(myNumber) + 3;
```
The result is then 77, as initially expected.
Arithmetic operators
--------------------
Arithmetic operators are used for performing mathematical calculations in JavaScript:
| Operator | Name | Purpose | Example |
| --- | --- | --- | --- |
| `+` | Addition | Adds two numbers together. | `6 + 9` |
| `-` | Subtraction | Subtracts the right number from the left. | `20 - 15` |
| `*` | Multiplication | Multiplies two numbers together. | `3 * 7` |
| `/` | Division | Divides the left number by the right. | `10 / 5` |
| `%` | Remainder (sometimes called modulo) |
Returns the remainder left over after you've divided the left number
into a number of integer portions equal to the right number.
|
`8 % 3` (returns 2, as three goes into 8 twice, leaving 2
left over).
|
| `**` | Exponent |
Raises a `base` number to the `exponent` power,
that is, the `base` number multiplied by itself,
`exponent` times.
| `5 ** 2` (returns `25`, which is the same as
`5 * 5`).
|
**Note:** You'll sometimes see numbers involved in arithmetic referred to as operands.
**Note:** You may sometimes see exponents expressed using the older `Math.pow()` method, which works in a very similar way. For example, in `Math.pow(7, 3)`, `7` is the base and `3` is the exponent, so the result of the expression is `343`. `Math.pow(7, 3)` is equivalent to `7**3`.
We probably don't need to teach you how to do basic math, but we would like to test your understanding of the syntax involved. Try entering the examples below into your developer tools JavaScript console to familiarize yourself with the syntax.
1. First try entering some simple examples of your own, such as
```js
10 + 7;
9 \* 8;
60 % 3;
```
2. You can also try declaring and initializing some numbers inside variables, and try using those in the sums β the variables will behave exactly like the values they hold for the purposes of the sum. For example:
```js
const num1 = 10;
const num2 = 50;
9 \* num1;
num1 \*\* 3;
num2 / num1;
```
3. Last for this section, try entering some more complex expressions, such as:
```js
5 + 10 \* 3;
(num2 % 9) \* num1;
num2 + num1 / 8 + 2;
```
Parts of this last set of calculations might not give you quite the result you were expecting; the section below might well give the answer as to why.
### Operator precedence
Let's look at the last example from above, assuming that `num2` holds the value 50 and `num1` holds the value 10 (as originally stated above):
```js
num2 + num1 / 8 + 2;
```
As a human being, you may read this as *"50 plus 10 equals 60"*, then *"8 plus 2 equals 10"*, and finally *"60 divided by 10 equals 6"*.
But the browser does *"10 divided by 8 equals 1.25"*, then *"50 plus 1.25 plus 2 equals 53.25"*.
This is because of **operator precedence** β some operators are applied before others when calculating the result of a calculation (referred to as an *expression*, in programming). Operator precedence in JavaScript is the same as is taught in math classes in school β multiply and divide are always done first, then add and subtract (the calculation is always evaluated from left to right).
If you want to override operator precedence, you can put parentheses around the parts that you want to be explicitly dealt with first. So to get a result of 6, we could do this:
```js
(num2 + num1) / (8 + 2);
```
Try it and see.
**Note:** A full list of all JavaScript operators and their precedence can be found in Operator precedence.
Increment and decrement operators
---------------------------------
Sometimes you'll want to repeatedly add or subtract one to or from a numeric variable value. This can be conveniently done using the increment (`++`) and decrement (`--`) operators. We used `++` in our "Guess the number" game back in our first splash into JavaScript article, when we added 1 to our `guessCount` variable to keep track of how many guesses the user has left after each turn.
```js
guessCount++;
```
Let's try playing with these in your console. For a start, note that you can't apply these directly to a number, which might seem strange, but we are assigning a variable a new updated value, not operating on the value itself. The following will return an error:
```js
3++;
```
So, you can only increment an existing variable. Try this:
```js
let num1 = 4;
num1++;
```
Okay, strangeness number 2! When you do this, you'll see a value of 4 returned β this is because the browser returns the current value, *then* increments the variable. You can see that it's been incremented if you return the variable value again:
```js
num1;
```
The same is true of `--` : try the following
```js
let num2 = 6;
num2--;
num2;
```
**Note:** You can make the browser do it the other way round β increment/decrement the variable *then* return the value β by putting the operator at the start of the variable instead of the end. Try the above examples again, but this time use `++num1` and `--num2`.
Assignment operators
--------------------
Assignment operators are operators that assign a value to a variable. We have already used the most basic one, `=`, loads of times β it assigns the variable on the left the value stated on the right:
```js
let x = 3; // x contains the value 3
let y = 4; // y contains the value 4
x = y; // x now contains the same value y contains, 4
```
But there are some more complex types, which provide useful shortcuts to keep your code neater and more efficient. The most common are listed below:
| Operator | Name | Purpose | Example | Shortcut for |
| --- | --- | --- | --- | --- |
| `+=` | Addition assignment |
Adds the value on the right to the variable value on the left, then
returns the new variable value
| `x += 4;` | `x = x + 4;` |
| `-=` | Subtraction assignment |
Subtracts the value on the right from the variable value on the left,
and returns the new variable value
| `x -= 3;` | `x = x - 3;` |
| `*=` | Multiplication assignment |
Multiplies the variable value on the left by the value on the right, and
returns the new variable value
| `x *= 3;` | `x = x * 3;` |
| `/=` | Division assignment |
Divides the variable value on the left by the value on the right, and
returns the new variable value
| `x /= 5;` | `x = x / 5;` |
Try typing some of the above examples into your console, to get an idea of how they work. In each case, see if you can guess what the value is before you type in the second line.
Note that you can quite happily use other variables on the right-hand side of each expression, for example:
```js
let x = 3; // x contains the value 3
let y = 4; // y contains the value 4
x \*= y; // x now contains the value 12
```
**Note:** There are lots of other assignment operators available, but these are the basic ones you should learn now.
Active learning: sizing a canvas box
------------------------------------
In this exercise, you will manipulate some numbers and operators to change the size of a box. The box is drawn using a browser API called the Canvas API. There is no need to worry about how this works β just concentrate on the math for now. The width and height of the box (in pixels) are defined by the variables `x` and `y`, which are initially both given a value of 50.
**Open in new window**
In the editable code box above, there are two lines marked with a comment that we'd like you to update to make the box grow/shrink to certain sizes, using certain operators and/or values in each case. Let's try the following:
* Change the line that calculates x so the box is still 50px wide, but the 50 is calculated using the numbers 43 and 7 and an arithmetic operator.
* Change the line that calculates y so the box is 75px high, but the 75 is calculated using the numbers 25 and 3 and an arithmetic operator.
* Change the line that calculates x so the box is 250px wide, but the 250 is calculated using two numbers and the remainder (modulo) operator.
* Change the line that calculates y so the box is 150px high, but the 150 is calculated using three numbers and the subtraction and division operators.
* Change the line that calculates x so the box is 200px wide, but the 200 is calculated using the number 4 and an assignment operator.
* Change the line that calculates y so the box is 200px high, but the 200 is calculated using the numbers 50 and 3, the multiplication operator, and the addition assignment operator.
Don't worry if you totally mess the code up. You can always press the Reset button to get things working again. After you've answered all the above questions correctly, feel free to play with the code some more or create your own challenges.
Comparison operators
--------------------
Sometimes we will want to run true/false tests, then act accordingly depending on the result of that test β to do this we use **comparison operators**.
| Operator | Name | Purpose | Example |
| --- | --- | --- | --- |
| `===` | Strict equality | Tests whether the left and right values are identical to one another | `5 === 2 + 4` |
| `!==` | Strict-non-equality | Tests whether the left and right values are **not** identical to one another | `5 !== 2 + 3` |
| `<` | Less than | Tests whether the left value is smaller than the right one. | `10 < 6` |
| `>` | Greater than | Tests whether the left value is greater than the right one. | `10 > 20` |
| `<=` | Less than or equal to | Tests whether the left value is smaller than or equal to the right one. | `3 <= 2` |
| `>=` | Greater than or equal to | Tests whether the left value is greater than or equal to the right one. | `5 >= 4` |
**Note:** You may see some people using `==` and `!=` in their tests for equality and non-equality. These are valid operators in JavaScript, but they differ from `===`/`!==`. The former versions test whether the values are the same but not whether the values' datatypes are the same. The latter, strict versions test the equality of both the values and their datatypes. The strict versions tend to result in fewer errors, so we recommend you use them.
If you try entering some of these values in a console, you'll see that they all return `true`/`false` values β those booleans we mentioned in the last article. These are very useful, as they allow us to make decisions in our code, and they are used every time we want to make a choice of some kind. For example, booleans can be used to:
* Display the correct text label on a button depending on whether a feature is turned on or off
* Display a game over message if a game is over or a victory message if the game has been won
* Display the correct seasonal greeting depending on what holiday season it is
* Zoom a map in or out depending on what zoom level is selected
We'll look at how to code such logic when we look at conditional statements in a future article. For now, let's look at a quick example:
```html
<button>Start machine</button>
<p>The machine is stopped.</p>
```
```js
const btn = document.querySelector("button");
const txt = document.querySelector("p");
btn.addEventListener("click", updateBtn);
function updateBtn() {
if (btn.textContent === "Start machine") {
btn.textContent = "Stop machine";
txt.textContent = "The machine has started!";
} else {
btn.textContent = "Start machine";
txt.textContent = "The machine is stopped.";
}
}
```
**Open in new window**
You can see the equality operator being used just inside the `updateBtn()` function. In this case, we are not testing if two mathematical expressions have the same value β we are testing whether the text content of a button contains a certain string β but it is still the same principle at work. If the button is currently saying "Start machine" when it is pressed, we change its label to "Stop machine", and update the label as appropriate. If the button is currently saying "Stop machine" when it is pressed, we swap the display back again.
**Note:** Such a control that swaps between two states is generally referred to as a **toggle**. It toggles between one state and another β light on, light off, etc.
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Math.
Summary
-------
In this article, we have covered the fundamental information you need to know about numbers in JavaScript, for now. You'll see numbers used again and again, all the way through your JavaScript learning, so it's a good idea to get this out of the way now. If you are one of those people that doesn't enjoy math, you can take comfort in the fact that this chapter was pretty short.
In the next article, we'll explore text and how JavaScript allows us to manipulate it.
**Note:** If you do enjoy math and want to read more about how it is implemented in JavaScript, you can find a lot more detail in MDN's main JavaScript section. Great places to start are our Numbers and dates and Expressions and operators articles.
* Previous
* Overview: First steps
* Next |
Handling text β strings in JavaScript - Learn web development | Handling text β strings in JavaScript
=====================================
* Previous
* Overview: First steps
* Next
Next, we'll turn our attention to strings β this is what pieces of text are called in programming. In this article, we'll look at all the common things that you really ought to know about strings when learning JavaScript, such as creating strings, escaping quotes in strings, and joining strings together.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of HTML and CSS, an
understanding of what JavaScript is.
|
| Objective: | To gain familiarity with the basics of strings in JavaScript. |
The power of words
------------------
Words are very important to humans β they are a large part of how we communicate. Since the Web is a largely text-based medium designed to allow humans to communicate and share information, it is useful for us to have control over the words that appear on it. HTML provides structure and meaning to our text, CSS allows us to precisely style it, and JavaScript contains a number of features for manipulating strings, creating custom welcome messages and prompts, showing the right text labels when needed, sorting terms into the desired order, and much more.
Pretty much all of the programs we've shown you so far in the course have involved some string manipulation.
Declaring strings
-----------------
Strings are dealt with similarly to numbers at first glance, but when you dig deeper you'll start to see some notable differences. Let's start by entering some basic lines into the browser developer console to familiarize ourselves.
To start with, enter the following lines:
```js
const string = "The revolution will not be televised.";
console.log(string);
```
Just like we did with numbers, we are declaring a variable, initializing it with a string value, and then returning the value. The only difference here is that when writing a string, you need to surround the value with quotes.
If you don't do this, or miss one of the quotes, you'll get an error. Try entering the following lines:
```js
const badString1 = This is a test;
const badString2 = 'This is a test;
const badString3 = This is a test';
```
These lines don't work because any text without quotes around it is assumed to be a variable name, property name, a reserved word, or similar. If the browser can't find it, then an error is raised (e.g. "missing; before statement"). If the browser can see where a string starts, but can't find the end of the string, as indicated by the 2nd quote, it complains with an error (with "unterminated string literal"). If your program is raising such errors, then go back and check all your strings to make sure you have no missing quote marks.
The following will work if you previously defined the variable `string` β try it now:
```js
const badString = string;
console.log(badString);
```
`badString` is now set to have the same value as `string`.
### Single quotes, double quotes, and backticks
In JavaScript, you can choose single quotes (`'`), double quotes (`"`), or backticks (```) to wrap your strings in. All of the following will work:
```js
const single = 'Single quotes';
const double = "Double quotes";
const backtick = `Backtick`;
console.log(single);
console.log(double);
console.log(backtick);
```
You must use the same character for the start and end of a string, or you will get an error:
```js
const badQuotes = 'This is not allowed!";
```
Strings declared using single quotes and strings declared using double quotes are the same, and which you use is down to personal preference β although it is good practice to choose one style and use it consistently in your code.
Strings declared using backticks are a special kind of string called a *template literal*. In most ways, template literals are like normal strings, but they have some special properties:
* you can embed JavaScript in them
* you can declare template literals over multiple lines
Embedding JavaScript
--------------------
Inside a template literal, you can wrap JavaScript variables or expressions inside `${ }`, and the result will be included in the string:
```js
const name = "Chris";
const greeting = `Hello, ${name}`;
console.log(greeting); // "Hello, Chris"
```
You can use the same technique to join together two variables:
```js
const one = "Hello, ";
const two = "how are you?";
const joined = `${one}${two}`;
console.log(joined); // "Hello, how are you?"
```
Joining strings together like this is called *concatenation*.
### Concatenation in context
Let's have a look at concatenation being used in action:
```html
<button>Press me</button>
<div id="greeting"></div>
```
```js
const button = document.querySelector("button");
function greet() {
const name = prompt("What is your name?");
const greeting = document.querySelector("#greeting");
greeting.textContent = `Hello ${name}, nice to see you!`;
}
button.addEventListener("click", greet);
```
Here we're using the `window.prompt()` function, which asks the user to answer a question via a popup dialog box then stores the text they enter inside a given variable β in this case `name`. We then display a string which inserts the name into a generic greeting message.
### Concatenation using "+"
You can only use `${}` with template literals, not with normal strings. You can concatenate normal strings using the `+` operator:
```js
const greeting = "Hello";
const name = "Chris";
console.log(greeting + ", " + name); // "Hello, Chris"
```
However, template literals usually give you more readable code:
```js
const greeting = "Hello";
const name = "Chris";
console.log(`${greeting}, ${name}`); // "Hello, Chris"
```
### Including expressions in strings
You can include JavaScript expressions in template literals, as well as just variables, and the results will be included in the result:
```js
const song = "Fight the Youth";
const score = 9;
const highestScore = 10;
const output = `I like the song ${song}. I gave it a score of ${
(score / highestScore) \* 100
}%.`;
console.log(output); // "I like the song Fight the Youth. I gave it a score of 90%."
```
Multiline strings
-----------------
Template literals respect the line breaks in the source code, so you can write strings that span multiple lines like this:
```js
const newline = `One day you finally knew
what you had to do, and began,`;
console.log(newline);
/\*
One day you finally knew
what you had to do, and began,
\*/
```
To have the equivalent output using a normal string you'd have to include line break characters (`\n`) in the string:
```js
const newline = "One day you finally knew\nwhat you had to do, and began,";
console.log(newline);
/\*
One day you finally knew
what you had to do, and began,
\*/
```
See our Template literals reference page for more examples and details of advanced features.
Including quotes in strings
---------------------------
Since we use quotes to indicate the start and end of strings, how can we include actual quotes in strings? We know that this won't work:
```js
const badQuotes = "She said "I think so!"";
```
One common option is to use one of the other characters to declare the string:
```js
const goodQuotes1 = 'She said "I think so!"';
const goodQuotes2 = `She said "I'm not going in there!"`;
```
Another option is to *escape* the problem quotation mark. Escaping characters means that we do something to them to make sure they are recognized as text, not part of the code. In JavaScript, we do this by putting a backslash just before the character. Try this:
```js
const bigmouth = 'I\'ve got no right to take my placeβ¦';
console.log(bigmouth);
```
You can use the same technique to insert other special characters. See Escape sequences for more details.
Numbers vs. strings
-------------------
What happens when we try to concatenate a string and a number? Let's try it in our console:
```js
const name = "Front ";
const number = 242;
console.log(name + number); // "Front 242"
```
You might expect this to return an error, but it works just fine. How numbers should be displayed as strings is fairly well-defined, so the browser automatically converts the number to a string and concatenates the two strings.
If you have a numeric variable that you want to convert to a string, or a string variable that you want to convert to a number, you can use the following two constructs:
* The `Number()` function converts anything passed to it into a number, if it can. Try the following:
```js
const myString = "123";
const myNum = Number(myString);
console.log(typeof myNum);
// number
```
* Conversely, the `String()` function converts its argument to a string. Try this:
```js
const myNum2 = 123;
const myString2 = String(myNum2);
console.log(typeof myString2);
// string
```
These constructs can be really useful in some situations. For example, if a user enters a number into a form's text field, it's a string. However, if you want to add this number to something, you'll need it to be a number, so you could pass it through `Number()` to handle this. We did exactly this in our Number Guessing Game, in line 59.
Conclusion
----------
So that's the very basics of strings covered in JavaScript. In the next article, we'll build on this, looking at some of the built-in methods available to strings in JavaScript and how we can use them to manipulate our strings into just the form we want.
* Previous
* Overview: First steps
* Next |
What is JavaScript? - Learn web development | What is JavaScript?
===================
* Overview: First steps
* Next
Welcome to the MDN beginner's JavaScript course!
In this article we will look at JavaScript from a high level, answering questions such as "What is it?" and "What can you do with it?", and making sure you are comfortable with JavaScript's purpose.
| | |
| --- | --- |
| Prerequisites: | A basic understanding of HTML and CSS. |
| Objective: |
To gain familiarity with what JavaScript is, what it can do, and how it
fits into a website.
|
A high-level definition
-----------------------
JavaScript is a scripting or programming language that allows you to implement complex features on web pages β every time a web page does more than just sit there and display static information for you to look at β displaying timely content updates, interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, etc. β you can bet that JavaScript is probably involved.
It is the third layer of the layer cake of standard web technologies, two of which (HTML and CSS) we have covered in much more detail in other parts of the Learning Area.
![The three layers of standard web technologies; HTML, CSS and JavaScript](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript/cake.png)
* HTML is the markup language that we use to structure and give meaning to our web content, for example defining paragraphs, headings, and data tables, or embedding images and videos in the page.
* CSS is a language of style rules that we use to apply styling to our HTML content, for example setting background colors and fonts, and laying out our content in multiple columns.
* JavaScript is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else. (Okay, not everything, but it is amazing what you can achieve with a few lines of JavaScript code.)
The three layers build on top of one another nicely. Let's take a button as an example. We can mark it up using HTML to give it structure and purpose:
```html
<button type="button">Player 1: Chris</button>
```
![Button showing Player 1: Chris with no styling](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript/just-html.png)
Then we can add some CSS into the mix to get it looking nice:
```css
button {
font-family: "helvetica neue", helvetica, sans-serif;
letter-spacing: 1px;
text-transform: uppercase;
border: 2px solid rgb(200 200 0 / 60%);
background-color: rgb(0 217 217 / 60%);
color: rgb(100 0 0 / 100%);
box-shadow: 1px 1px 2px rgb(0 0 200 / 40%);
border-radius: 10px;
padding: 3px 10px;
cursor: pointer;
}
```
![Button showing Player 1: Chris with styling](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript/html-and-css.png)
And finally, we can add some JavaScript to implement dynamic behavior:
```js
const button = document.querySelector("button");
button.addEventListener("click", updateName);
function updateName() {
const name = prompt("Enter a new name");
button.textContent = `Player 1: ${name}`;
}
```
Try clicking on this last version of the text label to see what happens (note also that you can find this demo on GitHub β see the source code, or run it live)!
JavaScript can do a lot more than that β let's explore what in more detail.
So what can it really do?
-------------------------
The core client-side JavaScript language consists of some common programming features that allow you to do things like:
* Store useful values inside variables. In the above example for instance, we ask for a new name to be entered then store that name in a variable called `name`.
* Operations on pieces of text (known as "strings" in programming). In the above example we take the string "Player 1: " and join it to the `name` variable to create the complete text label, e.g. "Player 1: Chris".
* Running code in response to certain events occurring on a web page. We used a `click` event in our example above to detect when the label is clicked and then run the code that updates the text label.
* And much more!
What is even more exciting however is the functionality built on top of the client-side JavaScript language. So-called **Application Programming Interfaces** (**APIs**) provide you with extra superpowers to use in your JavaScript code.
APIs are ready-made sets of code building blocks that allow a developer to implement programs that would otherwise be hard or impossible to implement.
They do the same thing for programming that ready-made furniture kits do for home building β it is much easier to take ready-cut panels and screw them together to make a bookshelf than it is to work out the design yourself, go and find the correct wood, cut all the panels to the right size and shape, find the correct-sized screws, and *then* put them together to make a bookshelf.
They generally fall into two categories.
![Two categories of API; 3rd party APIs are shown to the side of the browser and browser APIs are in the browser](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript/browser.png)
**Browser APIs** are built into your web browser, and are able to expose data from the surrounding computer environment, or do useful complex things. For example:
* The `DOM (Document Object Model) API` allows you to manipulate HTML and CSS, creating, removing and changing HTML, dynamically applying new styles to your page, etc.
Every time you see a popup window appear on a page, or some new content displayed (as we saw above in our simple demo) for example, that's the DOM in action.
* The `Geolocation API` retrieves geographical information.
This is how Google Maps is able to find your location and plot it on a map.
* The `Canvas` and `WebGL` APIs allow you to create animated 2D and 3D graphics.
People are doing some amazing things using these web technologies β see Chrome Experiments and webglsamples.
* Audio and Video APIs like `HTMLMediaElement` and `WebRTC` allow you to do really interesting things with multimedia, such as play audio and video right in a web page, or grab video from your web camera and display it on someone else's computer (try our simple Snapshot demo to get the idea).
**Note:** Many of the above demos won't work in an older browser β when experimenting, it's a good idea to use a modern browser like Firefox, Chrome, Edge or Opera to run your code in.
You will need to consider cross browser testing in more detail when you get closer to delivering production code (i.e. real code that real customers will use).
**Third party APIs** are not built into the browser by default, and you generally have to grab their code and information from somewhere on the Web. For example:
* The Twitter API allows you to do things like displaying your latest tweets on your website.
* The Google Maps API and OpenStreetMap API allows you to embed custom maps into your website, and other such functionality.
**Note:** These APIs are advanced, and we'll not be covering any of these in this module. You can find out much more about these in our Client-side web APIs module.
There's a lot more available, too! However, don't get over excited just yet. You won't be able to build the next Facebook, Google Maps, or Instagram after studying JavaScript for 24 hours β there are a lot of basics to cover first. And that's why you're here β let's move on!
What is JavaScript doing on your page?
--------------------------------------
Here we'll actually start looking at some code, and while doing so, explore what actually happens when you run some JavaScript in your page.
Let's briefly recap the story of what happens when you load a web page in a browser (first talked about in our How CSS works article). When you load a web page in your browser, you are running your code (the HTML, CSS, and JavaScript) inside an execution environment (the browser tab). This is like a factory that takes in raw materials (the code) and outputs a product (the web page).
![HTML, CSS and JavaScript code come together to create the content in the browser tab when the page is loaded](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript/execution.png)
A very common use of JavaScript is to dynamically modify HTML and CSS to update a user interface, via the Document Object Model API (as mentioned above).
Note that the code in your web documents is generally loaded and executed in the order it appears on the page.
Errors may occur if JavaScript is loaded and run before the HTML and CSS that it is intended to modify.
You will learn ways around this later in the article, in the Script loading strategies section.
### Browser security
Each browser tab has its own separate bucket for running code in (these buckets are called "execution environments" in technical terms) β this means that in most cases the code in each tab is run completely separately, and the code in one tab cannot directly affect the code in another tab β or on another website.
This is a good security measure β if this were not the case, then pirates could start writing code to steal information from other websites, and other such bad things.
**Note:** There are ways to send code and data between different websites/tabs in a safe manner, but these are advanced techniques that we won't cover in this course.
### JavaScript running order
When the browser encounters a block of JavaScript, it generally runs it in order, from top to bottom.
This means that you need to be careful what order you put things in.
For example, let's return to the block of JavaScript we saw in our first example:
```js
const button = document.querySelector("button");
button.addEventListener("click", updateName);
function updateName() {
const name = prompt("Enter a new name");
button.textContent = `Player 1: ${name}`;
}
```
Here we are selecting a button (line 1), then attaching an event listener to it (line 3) so that when the button is clicked, the `updateName()` code block (lines 5β8) is run. The `updateName()` code block (these types of reusable code blocks are called "functions") asks the user for a new name, and then inserts that name into the button text to update the display.
If you swapped the order of the first two lines of code, it would no longer work β instead, you'd get an error returned in the browser developer console β `Uncaught ReferenceError: Cannot access 'button' before initialization`.
This means that the `button` object has not been initialized yet, so we can't add an event listener to it.
**Note:** This is a very common error β you need to be careful that the objects referenced in your code exist before you try to do stuff to them.
### Interpreted versus compiled code
You might hear the terms **interpreted** and **compiled** in the context of programming.
In interpreted languages, the code is run from top to bottom and the result of running the code is immediately returned.
You don't have to transform the code into a different form before the browser runs it.
The code is received in its programmer-friendly text form and processed directly from that.
Compiled languages on the other hand are transformed (compiled) into another form before they are run by the computer.
For example, C/C++ are compiled into machine code that is then run by the computer.
The program is executed from a binary format, which was generated from the original program source code.
JavaScript is a lightweight interpreted programming language.
The web browser receives the JavaScript code in its original text form and runs the script from that.
From a technical standpoint, most modern JavaScript interpreters actually use a technique called **just-in-time compiling** to improve performance; the JavaScript source code gets compiled into a faster, binary format while the script is being used, so that it can be run as quickly as possible.
However, JavaScript is still considered an interpreted language, since the compilation is handled at run time, rather than ahead of time.
There are advantages to both types of language, but we won't discuss them right now.
### Server-side versus client-side code
You might also hear the terms **server-side** and **client-side** code, especially in the context of web development.
Client-side code is code that is run on the user's computer β when a web page is viewed, the page's client-side code is downloaded, then run and displayed by the browser.
In this module we are explicitly talking about **client-side JavaScript**.
Server-side code on the other hand is run on the server, then its results are downloaded and displayed in the browser.
Examples of popular server-side web languages include PHP, Python, Ruby, ASP.NET, and even JavaScript!
JavaScript can also be used as a server-side language, for example in the popular Node.js environment β you can find out more about server-side JavaScript in our Dynamic Websites β Server-side programming topic.
### Dynamic versus static code
The word **dynamic** is used to describe both client-side JavaScript, and server-side languages β it refers to the ability to update the display of a web page/app to show different things in different circumstances, generating new content as required.
Server-side code dynamically generates new content on the server, e.g. pulling data from a database, whereas client-side JavaScript dynamically generates new content inside the browser on the client, e.g. creating a new HTML table, filling it with data requested from the server, then displaying the table in a web page shown to the user.
The meaning is slightly different in the two contexts, but related, and both approaches (server-side and client-side) usually work together.
A web page with no dynamically updating content is referred to as **static** β it just shows the same content all the time.
How do you add JavaScript to your page?
---------------------------------------
JavaScript is applied to your HTML page in a similar manner to CSS.
Whereas CSS uses `<link>` elements to apply external stylesheets and `<style>` elements to apply internal stylesheets to HTML, JavaScript only needs one friend in the world of HTML β the `<script>` element. Let's learn how this works.
### Internal JavaScript
1. First of all, make a local copy of our example file apply-javascript.html. Save it in a directory somewhere sensible.
2. Open the file in your web browser and in your text editor. You'll see that the HTML creates a simple web page containing a clickable button.
3. Next, go to your text editor and add the following in your head β just before your closing `</head>` tag:
```html
<script>
// JavaScript goes here
</script>
```
4. Now we'll add some JavaScript inside our `<script>` element to make the page do something more interesting β add the following code just below the "// JavaScript goes here" line:
```js
document.addEventListener("DOMContentLoaded", () => {
function createParagraph() {
const para = document.createElement("p");
para.textContent = "You clicked the button!";
document.body.appendChild(para);
}
const buttons = document.querySelectorAll("button");
for (const button of buttons) {
button.addEventListener("click", createParagraph);
}
});
```
5. Save your file and refresh the browser β now you should see that when you click the button, a new paragraph is generated and placed below.
**Note:** If your example doesn't seem to work, go through the steps again and check that you did everything right.
Did you save your local copy of the starting code as a `.html` file?
Did you add your `<script>` element just before the `</head>` tag?
Did you enter the JavaScript exactly as shown? **JavaScript is case sensitive, and very fussy, so you need to enter the syntax exactly as shown, otherwise it may not work.**
**Note:** You can see this version on GitHub as apply-javascript-internal.html (see it live too).
### External JavaScript
This works great, but what if we wanted to put our JavaScript in an external file? Let's explore this now.
1. First, create a new file in the same directory as your sample HTML file. Call it `script.js` β make sure it has that .js filename extension, as that's how it is recognized as JavaScript.
2. Replace your current `<script>` element with the following:
```html
<script src="script.js" defer></script>
```
3. Inside `script.js`, add the following script:
```js
function createParagraph() {
const para = document.createElement("p");
para.textContent = "You clicked the button!";
document.body.appendChild(para);
}
const buttons = document.querySelectorAll("button");
for (const button of buttons) {
button.addEventListener("click", createParagraph);
}
```
4. Save and refresh your browser, and you should see the same thing!
It works just the same, but now we've got our JavaScript in an external file.
This is generally a good thing in terms of organizing your code and making it reusable across multiple HTML files.
Plus, the HTML is easier to read without huge chunks of script dumped in it.
**Note:** You can see this version on GitHub as apply-javascript-external.html and script.js (see it live too).
### Inline JavaScript handlers
Note that sometimes you'll come across bits of actual JavaScript code living inside HTML.
It might look something like this:
```js
function createParagraph() {
const para = document.createElement("p");
para.textContent = "You clicked the button!";
document.body.appendChild(para);
}
```
```html
<button onclick="createParagraph()">Click me!</button>
```
You can try this version of our demo below.
This demo has exactly the same functionality as in the previous two sections, except that the `<button>` element includes an inline `onclick` handler to make the function run when the button is pressed.
**Please don't do this, however.** It is bad practice to pollute your HTML with JavaScript, and it is inefficient β you'd have to include the `onclick="createParagraph()"` attribute on every button you want the JavaScript to apply to.
### Using addEventListener instead
Instead of including JavaScript in your HTML, use a pure JavaScript construct.
The `querySelectorAll()` function allows you to select all the buttons on a page.
You can then loop through the buttons, assigning a handler for each using `addEventListener()`.
The code for this is shown below:
```js
const buttons = document.querySelectorAll("button");
for (const button of buttons) {
button.addEventListener("click", createParagraph);
}
```
This might be a bit longer than the `onclick` attribute, but it will work for all buttons β no matter how many are on the page, nor how many are added or removed.
The JavaScript does not need to be changed.
**Note:** Try editing your version of `apply-javascript.html` and add a few more buttons into the file.
When you reload, you should find that all of the buttons when clicked will create a paragraph.
Neat, huh?
### Script loading strategies
There are a number of issues involved with getting scripts to load at the right time. Nothing is as simple as it seems!
A common problem is that all the HTML on a page is loaded in the order in which it appears.
If you are using JavaScript to manipulate elements on the page (or more accurately, the Document Object Model), your code won't work if the JavaScript is loaded and parsed before the HTML you are trying to do something to.
In the above code examples, in the internal and external examples the JavaScript is loaded and run in the head of the document, before the HTML body is parsed.
This could cause an error, so we've used some constructs to get around it.
In the internal example, you can see this structure around the code:
```js
document.addEventListener("DOMContentLoaded", () => {
// β¦
});
```
This is an event listener, which listens for the browser's `DOMContentLoaded` event, which signifies that the HTML body is completely loaded and parsed.
The JavaScript inside this block will not run until after that event is fired, therefore the error is avoided (you'll learn about events later in the course).
In the external example, we use a more modern JavaScript feature to solve the problem, the `defer` attribute, which tells the browser to continue downloading the HTML content once the `<script>` tag element has been reached.
```html
<script src="script.js" defer></script>
```
In this case both the script and the HTML will load simultaneously and the code will work.
**Note:** In the external case, we did not need to use the `DOMContentLoaded` event because the `defer` attribute solved the problem for us.
We didn't use the `defer` solution for the internal JavaScript example because `defer` only works for external scripts.
An old-fashioned solution to this problem used to be to put your script element right at the bottom of the body (e.g. just before the `</body>` tag), so that it would load after all the HTML has been parsed.
The problem with this solution is that loading/parsing of the script is completely blocked until the HTML DOM has been loaded.
On larger sites with lots of JavaScript, this can cause a major performance issue, slowing down your site.
#### async and defer
There are actually two modern features we can use to bypass the problem of the blocking script β `async` and `defer` (which we saw above).
Let's look at the difference between these two.
Scripts loaded using the `async` attribute will download the script without blocking the page while the script is being fetched.
However, once the download is complete, the script will execute, which blocks the page from rendering. This means that the rest of the content on the web page is prevented from being processed and displayed to the user until the script finishes executing.
You get no guarantee that scripts will run in any specific order.
It is best to use `async` when the scripts in the page run independently from each other and depend on no other script on the page.
Scripts loaded with the `defer` attribute will load in the order they appear on the page.
They won't run until the page content has all loaded, which is useful if your scripts depend on the DOM being in place (e.g. they modify one or more elements on the page).
Here is a visual representation of the different script loading methods and what that means for your page:
![How the three script loading method work: default has parsing blocked while JavaScript is fetched and executed. With async, the parsing pauses for execution only. With defer, parsing isn't paused, but execution on happens after everything is else is parsed.](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript/async-defer.jpg)
*This image is from the HTML spec, copied and cropped to a reduced version, under CC BY 4.0 license terms.*
For example, if you have the following script elements:
```html
<script async src="js/vendor/jquery.js"></script>
<script async src="js/script2.js"></script>
<script async src="js/script3.js"></script>
```
You can't rely on the order the scripts will load in.
`jquery.js` may load before or after `script2.js` and `script3.js` and if this is the case, any functions in those scripts depending on `jquery` will produce an error because `jquery` will not be defined at the time the script runs.
`async` should be used when you have a bunch of background scripts to load in, and you just want to get them in place as soon as possible.
For example, maybe you have some game data files to load, which will be needed when the game actually begins, but for now you just want to get on with showing the game intro, titles, and lobby, without them being blocked by script loading.
Scripts loaded using the `defer` attribute (see below) will run in the order they appear in the page and execute them as soon as the script and content are downloaded:
```html
<script defer src="js/vendor/jquery.js"></script>
<script defer src="js/script2.js"></script>
<script defer src="js/script3.js"></script>
```
In the second example, we can be sure that `jquery.js` will load before `script2.js` and `script3.js` and that `script2.js` will load before `script3.js`.
They won't run until the page content has all loaded, which is useful if your scripts depend on the DOM being in place (e.g. they modify one or more elements on the page).
To summarize:
* `async` and `defer` both instruct the browser to download the script(s) in a separate thread, while the rest of the page (the DOM, etc.) is downloading, so the page loading is not blocked during the fetch process.
* scripts with an `async` attribute will execute as soon as the download is complete.
This blocks the page and does not guarantee any specific execution order.
* scripts with a `defer` attribute will load in the order they are in and will only execute once everything has finished loading.
* If your scripts should be run immediately and they don't have any dependencies, then use `async`.
* If your scripts need to wait for parsing and depend on other scripts and/or the DOM being in place, load them using `defer` and put their corresponding `<script>` elements in the order you want the browser to execute them.
Comments
--------
As with HTML and CSS, it is possible to write comments into your JavaScript code that will be ignored by the browser, and exist to provide instructions to your fellow developers on how the code works (and you, if you come back to your code after six months and can't remember what you did).
Comments are very useful, and you should use them often, particularly for larger applications.
There are two types:
* A single line comment is written after a double forward slash (//), e.g.
```js
// I am a comment
```
* A multi-line comment is written between the strings /\* and \*/, e.g.
```js
/\*
I am also
a comment
\*/
```
So for example, we could annotate our last demo's JavaScript with comments like so:
```js
// Function: creates a new paragraph and appends it to the bottom of the HTML body.
function createParagraph() {
const para = document.createElement("p");
para.textContent = "You clicked the button!";
document.body.appendChild(para);
}
/\*
1. Get references to all the buttons on the page in an array format.
2. Loop through all the buttons and add a click event listener to each one.
When any button is pressed, the createParagraph() function will be run.
\*/
const buttons = document.querySelectorAll("button");
for (const button of buttons) {
button.addEventListener("click", createParagraph);
}
```
**Note:** In general more comments are usually better than less, but you should be careful if you find yourself adding lots of comments to explain what variables are (your variable names perhaps should be more intuitive), or to explain very simple operations (maybe your code is overcomplicated).
Summary
-------
So there you go, your first step into the world of JavaScript.
We've begun with just theory, to start getting you used to why you'd use JavaScript and what kind of things you can do with it.
Along the way, you saw a few code examples and learned how JavaScript fits in with the rest of the code on your website, amongst other things.
JavaScript may seem a bit daunting right now, but don't worry β in this course, we will take you through it in simple steps that will make sense going forward.
In the next article, we will plunge straight into the practical, getting you to jump straight in and build your own JavaScript examples.
* Overview: First steps
* Next |
A first splash into JavaScript - Learn web development | A first splash into JavaScript
==============================
* Previous
* Overview: First steps
* Next
Now you've learned something about the theory of JavaScript and what you can do with it, we are going to give you an idea of what the process of creating a simple JavaScript program is like, by guiding you through a practical tutorial. Here you'll build up a simple "Guess the number" game, step by step.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of HTML and CSS, an
understanding of what JavaScript is.
|
| Objective: |
To have a first bit of experience at writing some JavaScript, and gain
at least a basic understanding of what writing a JavaScript program
involves.
|
We want to set really clear expectations here: You won't be expected to learn JavaScript by the end of this article, or even understand all the code we are asking you to write. Instead, we want to give you an idea of how JavaScript's features work together, and what writing JavaScript feels like. In subsequent articles you'll revisit all the features shown here in a lot more detail, so don't worry if you don't understand it all immediately!
**Note:** Many of the code features you'll see in JavaScript are the same as in other programming languages β functions, loops, etc. The code syntax looks different, but the concepts are still largely the same.
Thinking like a programmer
--------------------------
One of the hardest things to learn in programming is not the syntax you need to learn, but how to apply it to solve real-world problems. You need to start thinking like a programmer β this generally involves looking at descriptions of what your program needs to do, working out what code features are needed to achieve those things, and how to make them work together.
This requires a mixture of hard work, experience with the programming syntax, and practice β plus a bit of creativity. The more you code, the better you'll get at it. We can't promise that you'll develop "programmer brain" in five minutes, but we will give you plenty of opportunities to practice thinking like a programmer throughout the course.
With that in mind, let's look at the example we'll be building up in this article, and review the general process of dissecting it into tangible tasks.
Example β Guess the number game
-------------------------------
In this article we'll show you how to build up the simple game you can see below:
Have a go at playing it β familiarize yourself with the game before you move on.
Let's imagine your boss has given you the following brief for creating this game:
>
> I want you to create a simple guess the number type game. It should choose a random number between 1 and 100, then challenge the player to guess the number in 10 turns. After each turn, the player should be told if they are right or wrong, and if they are wrong, whether the guess was too low or too high. It should also tell the player what numbers they previously guessed. The game will end once the player guesses correctly, or once they run out of turns. When the game ends, the player should be given an option to start playing again.
>
>
>
Upon looking at this brief, the first thing we can do is to start breaking it down into simple actionable tasks, in as much of a programmer mindset as possible:
1. Generate a random number between 1 and 100.
2. Record the turn number the player is on. Start it on 1.
3. Provide the player with a way to guess what the number is.
4. Once a guess has been submitted first record it somewhere so the user can see their previous guesses.
5. Next, check whether it is the correct number.
6. If it is correct:
1. Display congratulations message.
2. Stop the player from being able to enter more guesses (this would mess the game up).
3. Display control allowing the player to restart the game.
7. If it is wrong and the player has turns left:
1. Tell the player they are wrong and whether their guess was too high or too low.
2. Allow them to enter another guess.
3. Increment the turn number by 1.
8. If it is wrong and the player has no turns left:
1. Tell the player it is game over.
2. Stop the player from being able to enter more guesses (this would mess the game up).
3. Display control allowing the player to restart the game.
9. Once the game restarts, make sure the game logic and UI are completely reset, then go back to step 1.
Let's now move forward, looking at how we can turn these steps into code, building up the example, and exploring JavaScript features as we go.
### Initial setup
To begin this tutorial, we'd like you to make a local copy of the number-guessing-game-start.html file (see it live here). Open it in both your text editor and your web browser. At the moment you'll see a simple heading, paragraph of instructions and form for entering a guess, but the form won't currently do anything.
The place where we'll be adding all our code is inside the `<script>` element at the bottom of the HTML:
```html
<script>
// Your JavaScript goes here
</script>
```
### Adding variables to store our data
Let's get started. First of all, add the following lines inside your `<script>` element:
```js
let randomNumber = Math.floor(Math.random() \* 100) + 1;
const guesses = document.querySelector(".guesses");
const lastResult = document.querySelector(".lastResult");
const lowOrHi = document.querySelector(".lowOrHi");
const guessSubmit = document.querySelector(".guessSubmit");
const guessField = document.querySelector(".guessField");
let guessCount = 1;
let resetButton;
```
This section of the code sets up the variables and constants we need to store the data our program will use.
Variables are basically names for values (such as numbers, or strings of text). You create a variable with the keyword `let` followed by a name for your variable.
Constants are also used to name values, but unlike variables, you can't change the value once set. In this case, we are using constants to store references to parts of our user interface. The text inside some of these elements might change, but each constant always references the same HTML element that it was initialized with. You create a constant with the keyword `const` followed by a name for the constant.
You can assign a value to your variable or constant with an equals sign (`=`) followed by the value you want to give it.
In our example:
* The first variable β `randomNumber` β is assigned a random number between 1 and 100, calculated using a mathematical algorithm.
* The first three constants are each made to store a reference to the results paragraphs in our HTML, and are used to insert values into the paragraphs later on in the code (note how they are inside a `<div>` element, which is itself used to select all three later on for resetting, when we restart the game):
```html
<div class="resultParas">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
```
* The next two constants store references to the form text input and submit button and are used to control submitting the guess later on.
```html
<label for="guessField">Enter a guess: </label>
<input type="number" id="guessField" class="guessField" />
<input type="submit" value="Submit guess" class="guessSubmit" />
```
* Our final two variables store a guess count of 1 (used to keep track of how many guesses the player has had), and a reference to a reset button that doesn't exist yet (but will later).
**Note:** You'll learn a lot more about variables and constants later on in the course, starting with the article Storing the information you need β Variables.
### Functions
Next, add the following below your previous JavaScript:
```js
function checkGuess() {
alert("I am a placeholder");
}
```
Functions are reusable blocks of code that you can write once and run again and again, saving the need to keep repeating code all the time. This is really useful. There are a number of ways to define functions, but for now we'll concentrate on one simple type. Here we have defined a function by using the keyword `function`, followed by a name, with parentheses put after it. After that, we put two curly braces (`{ }`). Inside the curly braces goes all the code that we want to run whenever we call the function.
When we want to run the code, we type the name of the function followed by the parentheses.
Let's try that now. Save your code and refresh the page in your browser. Then go into the developer tools JavaScript console, and enter the following line:
```js
checkGuess();
```
After pressing `Return`/`Enter`, you should see an alert come up that says `I am a placeholder`; we have defined a function in our code that creates an alert whenever we call it.
**Note:** You'll learn a lot more about functions later on in the article Functions β reusable blocks of code.
### Operators
JavaScript operators allow us to perform tests, do math, join strings together, and other such things.
If you haven't already done so, save your code, refresh the page in your browser, and open the developer tools JavaScript console. Then we can try typing in the examples shown below β type in each one from the "Example" columns exactly as shown, pressing `Return`/`Enter` after each one, and see what results they return.
First let's look at arithmetic operators, for example:
| Operator | Name | Example |
| --- | --- | --- |
| `+` | Addition | `6 + 9` |
| `-` | Subtraction | `20 - 15` |
| `*` | Multiplication | `3 * 7` |
| `/` | Division | `10 / 5` |
There are also some shortcut operators available, called compound assignment operators. For example, if you want to add a new number to an existing one and return the result, you could do this:
```js
let number1 = 1;
number1 += 2;
```
This is equivalent to
```js
let number2 = 1;
number2 = number2 + 2;
```
When we are running true/false tests (for example inside conditionals β see below) we use comparison operators. For example:
| Operator | Name | Example |
| --- | --- | --- |
| `===` | Strict equality (is it exactly the same?) |
```js
5 === 2 + 4 // false
'Chris' === 'Bob' // false
5 === 2 + 3 // true
2 === '2' // false; number versus string
```
|
| `!==` | Non-equality (is it not the same?) |
```js
5 !== 2 + 4 // true
'Chris' !== 'Bob' // true
5 !== 2 + 3 // false
2 !== '2' // true; number versus string
```
|
| `<` | Less than |
```js
6 < 10 // true
20 < 10 // false
```
|
| `>` | Greater than |
```js
6 > 10 // false
20 > 10 // true
```
|
### Text strings
Strings are used for representing text. We've already seen a string variable: in the following code, `"I am a placeholder"` is a string:
```js
function checkGuess() {
alert("I am a placeholder");
}
```
You can declare strings using double quotes (`"`) or single quotes (`'`), but you must use the same form for the start and end of a single string declaration: you can't write `"I am a placeholder'`.
You can also declare strings using backticks (```). Strings declared like this are called *template literals* and have some special properties. In particular, you can embed other variables or even expressions in them:
```js
const name = "Mahalia";
const greeting = `Hello ${name}`;
```
This gives you a mechanism to join strings together.
### Conditionals
Returning to our `checkGuess()` function, I think it's safe to say that we don't want it to just spit out a placeholder message. We want it to check whether a player's guess is correct or not, and respond appropriately.
At this point, replace your current `checkGuess()` function with this version instead:
```js
function checkGuess() {
const userGuess = Number(guessField.value);
if (guessCount === 1) {
guesses.textContent = "Previous guesses:";
}
guesses.textContent = `${guesses.textContent} ${userGuess}`;
if (userGuess === randomNumber) {
lastResult.textContent = "Congratulations! You got it right!";
lastResult.style.backgroundColor = "green";
lowOrHi.textContent = "";
setGameOver();
} else if (guessCount === 10) {
lastResult.textContent = "!!!GAME OVER!!!";
lowOrHi.textContent = "";
setGameOver();
} else {
lastResult.textContent = "Wrong!";
lastResult.style.backgroundColor = "red";
if (userGuess < randomNumber) {
lowOrHi.textContent = "Last guess was too low!";
} else if (userGuess > randomNumber) {
lowOrHi.textContent = "Last guess was too high!";
}
}
guessCount++;
guessField.value = "";
guessField.focus();
}
```
This is a lot of code β phew! Let's go through each section and explain what it does.
* The first line declares a variable called `userGuess` and sets its value to the current value entered inside the text field. We also run this value through the built-in `Number()` constructor, just to make sure the value is definitely a number. Since we're not changing this variable, we'll declare it using `const`.
* Next, we encounter our first conditional code block. A conditional code block allows you to run code selectively, depending on whether a certain condition is true or not. It looks a bit like a function, but it isn't. The simplest form of conditional block starts with the keyword `if`, then some parentheses, then some curly braces. Inside the parentheses, we include a test. If the test returns `true`, we run the code inside the curly braces. If not, we don't, and move on to the next bit of code. In this case, the test is testing whether the `guessCount` variable is equal to `1` (i.e. whether this is the player's first go or not):
```js
guessCount === 1;
```
If it is, we make the guesses paragraph's text content equal to `Previous guesses:`. If not, we don't.
* Next, we use a template literal to append the current `userGuess` value onto the end of the `guesses` paragraph, with a blank space in between.
* The next block does a few checks:
+ The first `if (){ }` checks whether the user's guess is equal to the `randomNumber` set at the top of our JavaScript. If it is, the player has guessed correctly and the game is won, so we show the player a congratulations message with a nice green color, clear the contents of the Low/High guess information box, and run a function called `setGameOver()`, which we'll discuss later.
+ Now we've chained another test onto the end of the last one using an `else if (){ }` structure. This one checks whether this turn is the user's last turn. If it is, the program does the same thing as in the previous block, except with a game over message instead of a congratulations message.
+ The final block chained onto the end of this code (the `else { }`) contains code that is only run if neither of the other two tests returns true (i.e. the player didn't guess right, but they have more guesses left). In this case we tell them they are wrong, then we perform another conditional test to check whether the guess was higher or lower than the answer, displaying a further message as appropriate to tell them higher or lower.
* The last three lines in the function (lines 26β28 above) get us ready for the next guess to be submitted. We add 1 to the `guessCount` variable so the player uses up their turn (`++` is an incrementation operation β increment by 1), and empty the value out of the form text field and focus it again, ready for the next guess to be entered.
### Events
At this point, we have a nicely implemented `checkGuess()` function, but it won't do anything because we haven't called it yet. Ideally, we want to call it when the "Submit guess" button is pressed, and to do this we need to use an **event**. Events are things that happen in the browser β a button being clicked, a page loading, a video playing, etc. β in response to which we can run blocks of code. **Event listeners** observe specific events and call **event handlers**, which are blocks of code that run in response to an event firing.
Add the following line below your `checkGuess()` function:
```js
guessSubmit.addEventListener("click", checkGuess);
```
Here we are adding an event listener to the `guessSubmit` button. This is a method that takes two input values (called *arguments*) β the type of event we are listening out for (in this case `click`) as a string, and the code we want to run when the event occurs (in this case the `checkGuess()` function). Note that we don't need to specify the parentheses when writing it inside `addEventListener()`.
Try saving and refreshing your code now, and your example should work β to a point. The only problem now is that if you guess the correct answer or run out of guesses, the game will break because we've not yet defined the `setGameOver()` function that is supposed to be run once the game is over. Let's add our missing code now and complete the example functionality.
### Finishing the game functionality
Let's add that `setGameOver()` function to the bottom of our code and then walk through it. Add this now, below the rest of your JavaScript:
```js
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement("button");
resetButton.textContent = "Start new game";
document.body.append(resetButton);
resetButton.addEventListener("click", resetGame);
}
```
* The first two lines disable the form text input and button by setting their disabled properties to `true`. This is necessary, because if we didn't, the user could submit more guesses after the game is over, which would mess things up.
* The next three lines generate a new `<button>` element, set its text label to "Start new game", and add it to the bottom of our existing HTML.
* The final line sets an event listener on our new button so that when it is clicked, a function called `resetGame()` is run.
Now we need to define this function too! Add the following code, again to the bottom of your JavaScript:
```js
function resetGame() {
guessCount = 1;
const resetParas = document.querySelectorAll(".resultParas p");
for (const resetPara of resetParas) {
resetPara.textContent = "";
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = "";
guessField.focus();
lastResult.style.backgroundColor = "white";
randomNumber = Math.floor(Math.random() \* 100) + 1;
}
```
This rather long block of code completely resets everything to how it was at the start of the game, so the player can have another go. It:
* Puts the `guessCount` back down to 1.
* Empties all the text out of the information paragraphs. We select all paragraphs inside `<div class="resultParas"></div>`, then loop through each one, setting their `textContent` to `''` (an empty string).
* Removes the reset button from our code.
* Enables the form elements, and empties and focuses the text field, ready for a new guess to be entered.
* Removes the background color from the `lastResult` paragraph.
* Generates a new random number so that you are not just guessing the same number again!
**At this point, you should have a fully working (simple) game β congratulations!**
All we have left to do now in this article is to talk about a few other important code features that you've already seen, although you may have not realized it.
### Loops
One part of the above code that we need to take a more detailed look at is the for...of loop. Loops are a very important concept in programming, which allow you to keep running a piece of code over and over again, until a certain condition is met.
To start with, go to your browser developer tools JavaScript console again, and enter the following:
```js
const fruits = ["apples", "bananas", "cherries"];
for (const fruit of fruits) {
console.log(fruit);
}
```
What happened? The strings `'apples', 'bananas', 'cherries'` were printed out in your console.
This is because of the loop. The line `const fruits = ['apples', 'bananas', 'cherries'];` creates an array. We will work through a complete Arrays guide later in this module, but for now: an array is a collection of items (in this case strings).
A `for...of` loop gives you a way to get each item in the array and run some JavaScript on it. The line `for (const fruit of fruits)` says:
1. Get the first item in `fruits`.
2. Set the `fruit` variable to that item, then run the code between the `{}` curly braces.
3. Get the next item in `fruits`, and repeat 2, until you reach the end of `fruits`.
In this case, the code inside the curly braces is writing out `fruit` to the console.
Now let's look at the loop in our number guessing game β the following can be found inside the `resetGame()` function:
```js
const resetParas = document.querySelectorAll(".resultParas p");
for (const resetPara of resetParas) {
resetPara.textContent = "";
}
```
This code creates a variable containing a list of all the paragraphs inside `<div class="resultParas">` using the `querySelectorAll()` method, then it loops through each one, removing the text content of each.
Note that even though `resetPara` is a constant, we can change its internal properties like `textContent`.
### A small discussion on objects
Let's add one more final improvement before we get to this discussion. Add the following line just below the `let resetButton;` line near the top of your JavaScript, then save your file:
```js
guessField.focus();
```
This line uses the `focus()` method to automatically put the text cursor into the `<input>` text field as soon as the page loads, meaning that the user can start typing their first guess right away, without having to click the form field first. It's only a small addition, but it improves usability β giving the user a good visual clue as to what they've got to do to play the game.
Let's analyze what's going on here in a bit more detail. In JavaScript, most of the items you will manipulate in your code are objects. An object is a collection of related functionality stored in a single grouping. You can create your own objects, but that is quite advanced and we won't be covering it until much later in the course. For now, we'll just briefly discuss the built-in objects that your browser contains, which allow you to do lots of useful things.
In this particular case, we first created a `guessField` constant that stores a reference to the text input form field in our HTML β the following line can be found amongst our declarations near the top of the code:
```js
const guessField = document.querySelector(".guessField");
```
To get this reference, we used the `querySelector()` method of the `document` object. `querySelector()` takes one piece of information β a CSS selector that selects the element you want a reference to.
Because `guessField` now contains a reference to an `<input>` element, it now has access to a number of properties (basically variables stored inside objects, some of which can't have their values changed) and methods (basically functions stored inside objects). One method available to input elements is `focus()`, so we can now use this line to focus the text input:
```js
guessField.focus();
```
Variables that don't contain references to form elements won't have `focus()` available to them. For example, the `guesses` constant contains a reference to a `<p>` element, and the `guessCount` variable contains a number.
### Playing with browser objects
Let's play with some browser objects a bit.
1. First of all, open up your program in a browser.
2. Next, open your browser developer tools, and make sure the JavaScript console tab is open.
3. Type `guessField` into the console and the console shows you that the variable contains an `<input>` element. You'll also notice that the console autocompletes the names of objects that exist inside the execution environment, including your variables!
4. Now type in the following:
```js
guessField.value = 2;
```
The `value` property represents the current value entered into the text field. You'll see that by entering this command, we've changed the text in the text field!
5. Now try typing `guesses` into the console and pressing `Enter` (or `Return`, depending on your keyboard). The console shows you that the variable contains a `<p>` element.
6. Now try entering the following line:
```js
guesses.value;
```
The browser returns `undefined`, because paragraphs don't have the `value` property.
7. To change the text inside a paragraph, you need the `textContent` property instead. Try this:
```js
guesses.textContent = "Where is my paragraph?";
```
8. Now for some fun stuff. Try entering the below lines, one by one:
```js
guesses.style.backgroundColor = "yellow";
guesses.style.fontSize = "200%";
guesses.style.padding = "10px";
guesses.style.boxShadow = "3px 3px 6px black";
```
Every element on a page has a `style` property, which itself contains an object whose properties contain all the inline CSS styles applied to that element. This allows us to dynamically set new CSS styles on elements using JavaScript.
Finished for nowβ¦
-----------------
So that's it for building the example. You got to the end β well done! Try your final code out, or play with our finished version here. If you can't get the example to work, check it against the source code.
* Previous
* Overview: First steps
* Next |
Test your skills: Math - Learn web development | Test your skills: Math
======================
The aim of the tests on this page is to assess whether you've understood the Basic math in JavaScript β numbers and operators article.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If there is an error in your code, it will be logged into the results panel on this page or in the JavaScript console.
If you get stuck, you can reach out to us in one of our communication channels.
Math 1
------
Let's start out by testing your knowledge of basic math operators.
You will create four numeric values, add two together, subtract one from another, then multiply the results.
Finally, we need to write a check that proves that this value is an even number.
Try updating the live code below to recreate the finished example by following these steps:
1. Create four variables that contain numbers. Call the variables something sensible.
2. Add the first two variables together and store the result in another variable.
3. Subtract the fourth variable from the third and store the result in another variable.
4. Multiply the results from steps **2** and **3** and store the result in a variable called `finalResult`.
5. Check if `finalResult` is an even number using an arithmetic operator and store the result in a variable called `evenOddResult`.
To pass this test, `finalResult` should have a value of `48` and `evenOddResult` should have a value of `0`.
Download the starting point for this task to work in your own editor or in an online editor.
Math 2
------
In the second task, you are provided with two calculations with the results stored in the variables `result` and `result2`.
You need to take the calculations, multiply them, and format the result to two decimal places.
Try updating the live code below to recreate the finished example by following these steps:
1. Multiply `result` and `result2` and assign the result back to `result` (use assignment shorthand).
2. Format `result` so that it has two decimal places and store it in a variable called `finalResult`.
3. Check the data type of `finalResult` using `typeof`. If it's a `string`, convert it to a `number` type and store the result in a variable called `finalNumber`.
To pass this test, `finalNumber` should have a result of `4633.33`.
Download the starting point for this task to work in your own editor or in an online editor.
Math 3
------
In the final task for this article, we want you to write some tests.
There are three groups, each consisting of a statement and two variables.
For each one, write a test that proves or disproves the statement made.
Store the results of those tests in variables called `weightComparison`, `heightComparison`, and `pwdMatch`, respectively.
Download the starting point for this task to work in your own editor or in an online editor. |
Test your skills: Arrays - Learn web development | Test your skills: Arrays
========================
The aim of this skill test is to assess whether you've understood our Arrays article.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
Arrays 1
--------
Let's start off with some basic array practice. In this task we'd like you to create an array of three items, stored inside a variable called `myArray`. The items can be anything you want β how about your favorite foods or bands?
Next, modify the first two items in the array using simple bracket notation and assignment. Then add a new item to the beginning of the array.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Arrays 2
--------
Now let's move on to another task. Here you are provided with a string to work with. We'd like you to:
1. Convert the string into an array, removing the `+` characters in the process. Save the result in a variable called `myArray`.
2. Store the length of the array in a variable called `arrayLength`.
3. Store the last item in the array in a variable called `lastItem`.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Arrays 3
--------
For this array task, we provide you with a starting array, and you will work in somewhat the opposite direction. You need to:
1. Remove the last item in the array.
2. Add two new names to the end of the array.
3. Go over each item in the array and add its index number after the name inside parentheses, for example `Ryu (0)`. Note that we don't teach how to do this in the Arrays article, so you'll have to do some research.
4. Finally, join the array items together in a single string called `myString`, with a separator of "`-`".
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Arrays 4
--------
For this array task, we provide you with a starting array listing the names of some birds.
* Find the index of the `"Eagles"` item, and use that to remove the `"Eagles"` item.
* Make a new array from this one, called `eBirds`, that contains only birds from the original array whose names begin with the letter "E". Note that `startsWith()` is a great way to check whether a string starts with a given character.
If it works, you should see `"Emus,Egrets"` appear in the page.
Download the starting point for this task to work in your own editor or in an online editor. |
Useful string methods - Learn web development | Useful string methods
=====================
* Previous
* Overview: First steps
* Next
Now that we've looked at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings with built-in methods, such as finding the length of a text string, joining and splitting strings, substituting one character in a string for another, and more.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of HTML and CSS, an
understanding of what JavaScript is.
|
| Objective: |
To understand that strings are objects, and learn how to use some of the
basic methods available on those objects to manipulate strings.
|
Strings as objects
------------------
Most things are objects in JavaScript. When you create a string, for example by using
```js
const string = "This is my string";
```
your variable becomes a string object instance, and as a result has a large number of properties and methods available to it. You can see this if you go to the `String` object page and look down the list on the side of the page!
**Now, before your brain starts melting, don't worry!** You really don't need to know about most of these early on in your learning journey. But there are a few that you'll potentially use quite often that we'll look at here.
Let's enter some examples into the browser developer console.
Finding the length of a string
------------------------------
This is easy β you use the `length` property. Try entering the following lines:
```js
const browserType = "mozilla";
browserType.length;
```
This should return the number 7, because "mozilla" is 7 characters long. This is useful for many reasons; for example, you might want to find the lengths of a series of names so you can display them in order of length, or let a user know that a username they have entered into a form field is too long if it is over a certain length.
Retrieving a specific string character
--------------------------------------
On a related note, you can return any character inside a string by using **square bracket notation** β this means you include square brackets (`[]`) on the end of your variable name. Inside the square brackets, you include the number of the character you want to return, so for example to retrieve the first letter you'd do this:
```js
browserType[0];
```
Remember: computers count from 0, not 1!
To retrieve the last character of *any* string, we could use the following line, combining this technique with the `length` property we looked at above:
```js
browserType[browserType.length - 1];
```
The length of the string "mozilla" is 7, but because the count starts at 0, the last character's position is 6; using `length-1` gets us the last character.
Testing if a string contains a substring
----------------------------------------
Sometimes you'll want to find if a smaller string is present inside a larger one (we generally say *if a substring is present inside a string*). This can be done using the `includes()` method, which takes a single parameter β the substring you want to search for.
It returns `true` if the string contains the substring, and `false` otherwise.
```js
const browserType = "mozilla";
if (browserType.includes("zilla")) {
console.log("Found zilla!");
} else {
console.log("No zilla here!");
}
```
Often you'll want to know if a string starts or ends with a particular substring. This is a common enough need that there are two special methods for this: `startsWith()` and `endsWith()`:
```js
const browserType = "mozilla";
if (browserType.startsWith("zilla")) {
console.log("Found zilla!");
} else {
console.log("No zilla here!");
}
```
```js
const browserType = "mozilla";
if (browserType.endsWith("zilla")) {
console.log("Found zilla!");
} else {
console.log("No zilla here!");
}
```
Finding the position of a substring in a string
-----------------------------------------------
You can find the position of a substring inside a larger string using the `indexOf()` method. This method takes two parameters β the substring that you want to search for, and an optional parameter that specifies the starting point of the search.
If the string contains the substring, `indexOf()` returns the index of the first occurrence of the substring. If the string does not contain the substring, `indexOf()` returns `-1`.
```js
const tagline = "MDN - Resources for developers, by developers";
console.log(tagline.indexOf("developers")); // 20
```
Starting at `0`, if you count the number of characters (including the whitespace) from the beginning of the string, the first occurrence of the substring `"developers"` is at index `20`.
```js
console.log(tagline.indexOf("x")); // -1
```
This, on the other hand, returns `-1` because the character `x` is not present in the string.
So now that you know how to find the first occurrence of a substring, how do you go about finding subsequent occurrences? You can do that by passing in a value that's greater than the index of the previous occurrence as the second parameter to the method.
```js
const firstOccurrence = tagline.indexOf("developers");
const secondOccurrence = tagline.indexOf("developers", firstOccurrence + 1);
console.log(firstOccurrence); // 20
console.log(secondOccurrence); // 35
```
Here we're telling the method to search for the substring `"developers"` starting at index `21` (`firstOccurrence + 1`), and it returns the index `35`.
Extracting a substring from a string
------------------------------------
You can extract a substring from a string using the `slice()` method. You pass it:
* the index at which to start extracting
* the index at which to stop extracting. This is exclusive, meaning that the character at this index is not included in the extracted substring.
For example:
```js
const browserType = "mozilla";
console.log(browserType.slice(1, 4)); // "ozi"
```
The character at index `1` is `"o"`, and the character at index 4 is `"l"`. So we extract all characters starting at `"o"` and ending just before `"l"`, giving us `"ozi"`.
If you know that you want to extract all of the remaining characters in a string after a certain character, you don't have to include the second parameter. Instead, you only need to include the character position from where you want to extract the remaining characters in a string. Try the following:
```js
browserType.slice(2); // "zilla"
```
This returns `"zilla"` β this is because the character position of 2 is the letter `"z"`, and because you didn't include a second parameter, the substring that was returned was all of the remaining characters in the string.
**Note:** `slice()` has other options too; study the `slice()` page to see what else you can find out.
Changing case
-------------
The string methods `toLowerCase()` and `toUpperCase()` take a string and convert all the characters to lower- or uppercase, respectively. This can be useful for example if you want to normalize all user-entered data before storing it in a database.
Let's try entering the following lines to see what happens:
```js
const radData = "My NaMe Is MuD";
console.log(radData.toLowerCase());
console.log(radData.toUpperCase());
```
Updating parts of a string
--------------------------
You can replace one substring inside a string with another substring using the `replace()` method.
In this example, we're providing two parameters β the string we want to replace, and the string we want to replace it with:
```js
const browserType = "mozilla";
const updated = browserType.replace("moz", "van");
console.log(updated); // "vanilla"
console.log(browserType); // "mozilla"
```
Note that `replace()`, like many string methods, doesn't change the string it was called on, but returns a new string. If you want to update the original `browserType` variable, you would have to do something like this:
```js
let browserType = "mozilla";
browserType = browserType.replace("moz", "van");
console.log(browserType); // "vanilla"
```
Also note that we now have to declare `browserType` using `let`, not `const`, because we are reassigning it.
Be aware that `replace()` in this form only changes the first occurrence of the substring. If you want to change all occurrences, you can use `replaceAll()`:
```js
let quote = "To be or not to be";
quote = quote.replaceAll("be", "code");
console.log(quote); // "To code or not to code"
```
Active learning examples
------------------------
In this section, we'll get you to try your hand at writing some string manipulation code. In each exercise below, we have an array of strings, and a loop that processes each value in the array and displays it in a bulleted list. You don't need to understand arrays or loops right now β these will be explained in future articles. All you need to do in each case is write the code that will output the strings in the format that we want them in.
Each example comes with a "Reset" button, which you can use to reset the code if you make a mistake and can't get it working again, and a "Show solution" button you can press to see a potential answer if you get really stuck.
### Filtering greeting messages
In the first exercise, we'll start you off simple β we have an array of greeting card messages, but we want to sort them to list just the Christmas messages. We want you to fill in a conditional test inside the `if ()` structure to test each string and only print it in the list if it is a Christmas message.
Think about how you could test whether the message in each case is a Christmas message. What string is present in all of those messages, and what method could you use to test whether it is present?
```
<h2>Live output</h2>
<div class="output" style="min-height: 125px;">
<ul></ul>
</div>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 290px; width: 95%">
const list = document.querySelector('.output ul');
list.innerHTML = '';
const greetings = ['Happy Birthday!',
'Merry Christmas my love',
'A happy Christmas to all the family',
'You\'re all I want for Christmas',
'Get well soon'];
for (const greeting of greetings) {
// Your conditional test needs to go inside the parentheses
// in the line below, replacing what's currently there
if (greeting) {
const listItem = document.createElement('li');
listItem.textContent = greeting;
list.appendChild(listItem);
}
}
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = "Show solution";
updateCode();
});
solution.addEventListener("click", () => {
if (solution.value === "Show solution") {
textarea.value = solutionEntry;
solution.value = "Hide solution";
} else {
textarea.value = userEntry;
solution.value = "Show solution";
}
updateCode();
});
const jsSolution = `const list = document.querySelector('.output ul');
list.innerHTML = '';
const greetings = [
'Happy Birthday!',
'Merry Christmas my love',
'A happy Christmas to all the family',
'You\\'re all I want for Christmas',
'Get well soon',
];
for (const greeting of greetings) {
// Your conditional test needs to go inside the parentheses
// in the line below, replacing what's currently there
if (greeting.includes('Christmas')) {
const listItem = document.createElement('li');
listItem.textContent = greeting;
list.appendChild(listItem);
}
}`;
let solutionEntry = jsSolution;
textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
textarea.onkeydown = (e) => {
if (e.keyCode === 9) {
e.preventDefault();
insertAtCaret("\t");
}
if (e.keyCode === 27) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = () => {
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if (solution.value === "Show solution") {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
```
### Fixing capitalization
In this exercise, we have the names of cities in the United Kingdom, but the capitalization is all messed up. We want you to change them so that they are all lowercase, except for a capital first letter. A good way to do this is to:
1. Convert the whole of the string contained in the `city` variable to lowercase and store it in a new variable.
2. Grab the first letter of the string in this new variable and store it in another variable.
3. Using this latest variable as a substring, replace the first letter of the lowercase string with the first letter of the lowercase string changed to upper case. Store the result of this replacement procedure in another new variable.
4. Change the value of the `result` variable to equal to the final result, not the `city`.
**Note:** A hint β the parameters of the string methods don't have to be string literals; they can also be variables, or even variables with a method being invoked on them.
```
<h2>Live output</h2>
<div class="output" style="min-height: 125px;">
<ul></ul>
</div>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 250px; width: 95%">
const list = document.querySelector('.output ul');
list.innerHTML = '';
const cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOL'];
for (const city of cities) {
// write your code just below here
const result = city;
const listItem = document.createElement('li');
listItem.textContent = result;
list.appendChild(listItem);
}
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener("click", function () {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = "Show solution";
updateCode();
});
solution.addEventListener("click", function () {
if (solution.value === "Show solution") {
textarea.value = solutionEntry;
solution.value = "Hide solution";
} else {
textarea.value = userEntry;
solution.value = "Show solution";
}
updateCode();
});
const jsSolution = `const list = document.querySelector('.output ul');
list.innerHTML = '';
const cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOL'];
for (const city of cities) {
// write your code just below here
const lower = city.toLowerCase();
const firstLetter = lower.slice(0,1);
const capitalized = lower.replace(firstLetter,firstLetter.toUpperCase());
const result = capitalized;
const listItem = document.createElement('li');
listItem.textContent = result;
list.appendChild(listItem);
}`;
let solutionEntry = jsSolution;
textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
textarea.onkeydown = function (e) {
if (e.keyCode === 9) {
e.preventDefault();
insertAtCaret("\t");
}
if (e.keyCode === 27) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = function () {
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if (solution.value === "Show solution") {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
```
### Making new strings from old parts
In this last exercise, the array contains a bunch of strings containing information about train stations in the North of England. The strings are data items that contain the three-letter station code, followed by some machine-readable data, followed by a semicolon, followed by the human-readable station name. For example:
```
MAN675847583748sjt567654;Manchester Piccadilly
```
We want to extract the station code and name, and put them together in a string with the following structure:
```
MAN: Manchester Piccadilly
```
We'd recommend doing it like this:
1. Extract the three-letter station code and store it in a new variable.
2. Find the character index number of the semicolon.
3. Extract the human-readable station name using the semicolon character index number as a reference point, and store it in a new variable.
4. Concatenate the two new variables and a string literal to make the final string.
5. Change the value of the `result` variable to the final string, not the `station`.
```
<h2>Live output</h2>
<div class="output" style="min-height: 125px;">
<ul></ul>
</div>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 285px; width: 95%">
const list = document.querySelector('.output ul');
list.innerHTML = '';
const stations = ['MAN675847583748sjt567654;Manchester Piccadilly',
'GNF576746573fhdg4737dh4;Greenfield',
'LIV5hg65hd737456236dch46dg4;Liverpool Lime Street',
'SYB4f65hf75f736463;Stalybridge',
'HUD5767ghtyfyr4536dh45dg45dg3;Huddersfield'];
for (const station of stations) {
// write your code just below here
const result = station;
const listItem = document.createElement('li');
listItem.textContent = result;
list.appendChild(listItem);
}
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener("click", function () {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = "Show solution";
updateCode();
});
solution.addEventListener("click", function () {
if (solution.value === "Show solution") {
textarea.value = solutionEntry;
solution.value = "Hide solution";
} else {
textarea.value = userEntry;
solution.value = "Show solution";
}
updateCode();
});
const jsSolution = `const list = document.querySelector('.output ul');
list.innerHTML = '';
const stations = ['MAN675847583748sjt567654;Manchester Piccadilly',
'GNF576746573fhdg4737dh4;Greenfield',
'LIV5hg65hd737456236dch46dg4;Liverpool Lime Street',
'SYB4f65hf75f736463;Stalybridge',
'HUD5767ghtyfyr4536dh45dg45dg3;Huddersfield'];
for (const station of stations) {
// write your code just below here
const code = station.slice(0,3);
const semiColon = station.indexOf(';');
const name = station.slice(semiColon + 1);
const result = \`\${code}: \${name}\`;
const listItem = document.createElement('li');
listItem.textContent = result;
list.appendChild(listItem);
}`;
let solutionEntry = jsSolution;
textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
textarea.onkeydown = function (e) {
if (e.keyCode === 9) {
e.preventDefault();
insertAtCaret("\t");
}
if (e.keyCode === 27) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = function () {
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if (solution.value === "Show solution") {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
```
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Strings.
Conclusion
----------
You can't escape the fact that being able to handle words and sentences in programming is very important β particularly in JavaScript, as websites are all about communicating with people. This article has given you the basics that you need to know about manipulating strings for now. This should serve you well as you go into more complex topics in the future. Next, we're going to look at the last major type of data we need to focus on in the short term β arrays.
* Previous
* Overview: First steps
* Next |
Storing the information you need β Variables - Learn web development | Storing the information you need β Variables
============================================
* Previous
* Overview: First steps
* Next
After reading the last couple of articles you should now know what JavaScript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level. In this article, we will get down to the real basics, looking at how to work with the most basic building blocks of JavaScript β Variables.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of HTML and CSS, an
understanding of what JavaScript is.
|
| Objective: | To gain familiarity with the basics of JavaScript variables. |
Tools you need
--------------
Throughout this article, you'll be asked to type in lines of code to test your understanding of the content. If you are using a desktop browser, the best place to type your sample code is your browser's JavaScript console (see What are browser developer tools for more information on how to access this tool).
What is a variable?
-------------------
A variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence.
### Variable example
Let's look at a simple example:
```html
<button id="button\_A">Press me</button>
<h3 id="heading\_A"></h3>
```
```js
const buttonA = document.querySelector("#button\_A");
const headingA = document.querySelector("#heading\_A");
buttonA.onclick = () => {
const name = prompt("What is your name?");
alert(`Hello ${name}, nice to see you!`);
headingA.textContent = `Welcome ${name}`;
};
```
In this example pressing the button runs some code. The first line pops a box up on the screen that asks the reader to enter their name, and then stores the value in a variable. The second line displays a welcome message that includes their name, taken from the variable value and the third line displays that name on the page.
### Without a variable
To understand why this is so useful, let's think about how we'd write this example without using a variable. It would end up looking something like this:
```html
<button id="button\_B">Press me</button>
<h3 id="heading\_B"></h3>
```
```js
const buttonB = document.querySelector("#button\_B");
const headingB = document.querySelector("#heading\_B");
buttonB.onclick = () => {
alert(`Hello ${prompt("What is your name?")}, nice to see you!`);
headingB.textContent = `Welcome ${prompt("What is your name?")}`;
};
```
You may not fully understand the syntax we are using (yet!), but you should be able to get the idea. If we didn't have variables available, we'd have to ask the reader for their name every time we needed to use it!
Variables just make sense, and as you learn more about JavaScript they will start to become second nature.
One special thing about variables is that they can contain just about anything β not just strings and numbers. Variables can also contain complex data and even entire functions to do amazing things. You'll learn more about this as you go along.
**Note:** We say variables contain values. This is an important distinction to make. Variables aren't the values themselves; they are containers for values. You can think of them being like little cardboard boxes that you can store things in.
![A screenshot of three 3-dimensional cardboard boxes demonstrating examples of JavaScript variables. Each box contains hypothetical values that represent various JavaScript data types. The sample values are "Bob", true and 35 respectively.](/en-US/docs/Learn/JavaScript/First_steps/Variables/boxes.png)
Declaring a variable
--------------------
To use a variable, you've first got to create it β more accurately, we call this declaring the variable. To do this, we type the keyword `let` followed by the name you want to call your variable:
```js
let myName;
let myAge;
```
Here we're creating two variables called `myName` and `myAge`. Try typing these lines into your web browser's console. After that, try creating a variable (or two) with your own name choices.
**Note:** In JavaScript, all code instructions should end with a semicolon (`;`) β your code may work correctly for single lines, but probably won't when you are writing multiple lines of code together. Try to get into the habit of including it.
You can test whether these values now exist in the execution environment by typing just the variable's name, e.g.
```js
myName;
myAge;
```
They currently have no value; they are empty containers. When you enter the variable names, you should get a value of `undefined` returned. If they don't exist, you'll get an error message β try typing in
```js
scoobyDoo;
```
**Note:** Don't confuse a variable that exists but has no defined value with a variable that doesn't exist at all β they are very different things. In the box analogy you saw above, not existing would mean there's no box (variable) for a value to go in. No value defined would mean that there is a box, but it has no value inside it.
Initializing a variable
-----------------------
Once you've declared a variable, you can initialize it with a value. You do this by typing the variable name, followed by an equals sign (`=`), followed by the value you want to give it. For example:
```js
myName = "Chris";
myAge = 37;
```
Try going back to the console now and typing in these lines. You should see the value you've assigned to the variable returned in the console to confirm it, in each case. Again, you can return your variable values by typing their name into the console β try these again:
```js
myName;
myAge;
```
You can declare and initialize a variable at the same time, like this:
```js
let myDog = "Rover";
```
This is probably what you'll do most of the time, as it is quicker than doing the two actions on two separate lines.
A note about var
----------------
You'll probably also see a different way to declare variables, using the `var` keyword:
```js
var myName;
var myAge;
```
Back when JavaScript was first created, this was the only way to declare variables. The design of `var` is confusing and error-prone. So `let` was created in modern versions of JavaScript, a new keyword for creating variables that works somewhat differently to `var`, fixing its issues in the process.
A couple of simple differences are explained below. We won't go into all the differences now, but you'll start to discover them as you learn more about JavaScript (if you really want to read about them now, feel free to check out our let reference page).
For a start, if you write a multiline JavaScript program that declares and initializes a variable, you can actually declare a variable with `var` after you initialize it and it will still work. For example:
```js
myName = "Chris";
function logName() {
console.log(myName);
}
logName();
var myName;
```
**Note:** This won't work when typing individual lines into a JavaScript console, just when running multiple lines of JavaScript in a web document.
This works because of **hoisting** β read var hoisting for more detail on the subject.
Hoisting no longer works with `let`. If we changed `var` to `let` in the above example, it would fail with an error. This is a good thing β declaring a variable after you initialize it results in confusing, harder to understand code.
Secondly, when you use `var`, you can declare the same variable as many times as you like, but with `let` you can't. The following would work:
```js
var myName = "Chris";
var myName = "Bob";
```
But the following would throw an error on the second line:
```js
let myName = "Chris";
let myName = "Bob";
```
You'd have to do this instead:
```js
let myName = "Chris";
myName = "Bob";
```
Again, this is a sensible language decision. There is no reason to redeclare variables β it just makes things more confusing.
For these reasons and more, we recommend that you use `let` in your code, rather than `var`. Unless you are explicitly writing support for ancient browsers, there is no longer any reason to use `var` as all modern browsers have supported `let` since 2015.
**Note:** If you are trying this code in your browser's console, prefer to copy & paste each of the code blocks here as a whole. There's a feature in Chrome's console where variable re-declarations with `let` and `const` are allowed:
```
> let myName = "Chris";
let myName = "Bob";
// As one input: SyntaxError: Identifier 'myName' has already been declared
> let myName = "Chris";
> let myName = "Bob";
// As two inputs: both succeed
```
Updating a variable
-------------------
Once a variable has been initialized with a value, you can change (or update) that value by giving it a different value. Try entering the following lines into your console:
```js
myName = "Bob";
myAge = 40;
```
### An aside on variable naming rules
You can call a variable pretty much anything you like, but there are limitations. Generally, you should stick to just using Latin characters (0-9, a-z, A-Z) and the underscore character.
* You shouldn't use other characters because they may cause errors or be hard to understand for an international audience.
* Don't use underscores at the start of variable names β this is used in certain JavaScript constructs to mean specific things, so may get confusing.
* Don't use numbers at the start of variables. This isn't allowed and causes an error.
* A safe convention to stick to is lower camel case, where you stick together multiple words, using lower case for the whole first word and then capitalize subsequent words. We've been using this for our variable names in the article so far.
* Make variable names intuitive, so they describe the data they contain. Don't just use single letters/numbers, or big long phrases.
* Variables are case sensitive β so `myage` is a different variable from `myAge`.
* One last point: you also need to avoid using JavaScript reserved words as your variable names β by this, we mean the words that make up the actual syntax of JavaScript! So, you can't use words like `var`, `function`, `let`, and `for` as variable names. Browsers recognize them as different code items, and so you'll get errors.
**Note:** You can find a fairly complete list of reserved keywords to avoid at Lexical grammar β keywords.
Good name examples:
```
age
myAge
init
initialColor
finalOutputValue
audio1
audio2
```
Bad name examples:
```
1
a
_12
myage
MYAGE
var
Document
skjfndskjfnbdskjfb
thisisareallylongvariablenameman
```
Try creating a few more variables now, with the above guidance in mind.
Variable types
--------------
There are a few different types of data we can store in variables. In this section we'll describe these in brief, then in future articles, you'll learn about them in more detail.
So far we've looked at the first two, but there are others.
### Numbers
You can store numbers in variables, either whole numbers like 30 (also called integers) or decimal numbers like 2.456 (also called floats or floating point numbers). You don't need to declare variable types in JavaScript, unlike some other programming languages. When you give a variable a number value, you don't include quotes:
```js
let myAge = 17;
```
### Strings
Strings are pieces of text. When you give a variable a string value, you need to wrap it in single or double quote marks; otherwise, JavaScript tries to interpret it as another variable name.
```js
let dolphinGoodbye = "So long and thanks for all the fish";
```
### Booleans
Booleans are true/false values β they can have two values, `true` or `false`. These are generally used to test a condition, after which code is run as appropriate. So for example, a simple case would be:
```js
let iAmAlive = true;
```
Whereas in reality it would be used more like this:
```js
let test = 6 < 3;
```
This is using the "less than" operator (`<`) to test whether 6 is less than 3. As you might expect, it returns `false`, because 6 is not less than 3! You will learn a lot more about such operators later on in the course.
### Arrays
An array is a single object that contains multiple values enclosed in square brackets and separated by commas. Try entering the following lines into your console:
```js
let myNameArray = ["Chris", "Bob", "Jim"];
let myNumberArray = [10, 15, 40];
```
Once these arrays are defined, you can access each value by their location within the array. Try these lines:
```js
myNameArray[0]; // should return 'Chris'
myNumberArray[2]; // should return 40
```
The square brackets specify an index value corresponding to the position of the value you want returned. You might have noticed that arrays in JavaScript are zero-indexed: the first element is at index 0.
You'll learn a lot more about arrays in a future article.
### Objects
In programming, an object is a structure of code that models a real-life object. You can have a simple object that represents a box and contains information about its width, length, and height, or you could have an object that represents a person, and contains data about their name, height, weight, what language they speak, how to say hello to them, and more.
Try entering the following line into your console:
```js
let dog = { name: "Spot", breed: "Dalmatian" };
```
To retrieve the information stored in the object, you can use the following syntax:
```js
dog.name;
```
We won't be looking at objects any more for now β you can learn more about those in a future module.
Dynamic typing
--------------
JavaScript is a "dynamically typed language", which means that, unlike some other languages, you don't need to specify what data type a variable will contain (numbers, strings, arrays, etc.).
For example, if you declare a variable and give it a value enclosed in quotes, the browser treats the variable as a string:
```js
let myString = "Hello";
```
Even if the value enclosed in quotes is just digits, it is still a string β not a number β so be careful:
```js
let myNumber = "500"; // oops, this is still a string
typeof myNumber;
myNumber = 500; // much better β now this is a number
typeof myNumber;
```
Try entering the four lines above into your console one by one, and see what the results are. You'll notice that we are using a special operator called `typeof` β this returns the data type of the variable you type after it. The first time it is called, it should return `string`, as at that point the `myNumber` variable contains a string, `'500'`. Have a look and see what it returns the second time you call it.
Constants in JavaScript
-----------------------
As well as variables, you can declare constants. These are like variables, except that:
* you must initialize them when you declare them
* you can't assign them a new value after you've initialized them.
For example, using `let` you can declare a variable without initializing it:
```js
let count;
```
If you try to do this using `const` you will see an error:
```js
const count;
```
Similarly, with `let` you can initialize a variable, and then assign it a new value (this is also called *reassigning* the variable):
```js
let count = 1;
count = 2;
```
If you try to do this using `const` you will see an error:
```js
const count = 1;
count = 2;
```
Note that although a constant in JavaScript must always name the same value, you can change the content of the value that it names. This isn't a useful distinction for simple types like numbers or booleans, but consider an object:
```js
const bird = { species: "Kestrel" };
console.log(bird.species); // "Kestrel"
```
You can update, add, or remove properties of an object declared using `const`, because even though the content of the object has changed, the constant is still pointing to the same object:
```js
bird.species = "Striated Caracara";
console.log(bird.species); // "Striated Caracara"
```
When to use const and when to use let
-------------------------------------
If you can't do as much with `const` as you can with `let`, why would you prefer to use it rather than `let`? In fact `const` is very useful. If you use `const` to name a value, it tells anyone looking at your code that this name will never be assigned to a different value. Any time they see this name, they will know what it refers to.
In this course, we adopt the following principle about when to use `let` and when to use `const`:
*Use `const` when you can, and use `let` when you have to.*
This means that if you can initialize a variable when you declare it, and don't need to reassign it later, make it a constant.
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: variables.
Summary
-------
By now you should know a reasonable amount about JavaScript variables and how to create them. In the next article, we'll focus on numbers in more detail, looking at how to do basic math in JavaScript.
* Previous
* Overview: First steps
* Next |
Functions β reusable blocks of code - Learn web development | Functions β reusable blocks of code
===================================
* Previous
* Overview: Building blocks
* Next
Another essential concept in coding is **functions**, which allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command β rather than having to type out the same code multiple times. In this article we'll explore fundamental concepts behind functions such as basic syntax, how to invoke and define them, scope, and parameters.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of HTML, CSS, and
JavaScript first steps.
|
| Objective: | To understand the fundamental concepts behind JavaScript functions. |
Where do I find functions?
--------------------------
In JavaScript, you'll find functions everywhere. In fact, we've been using functions all the way through the course so far; we've just not been talking about them very much. Now is the time, however, for us to start talking about functions explicitly, and really exploring their syntax.
Pretty much anytime you make use of a JavaScript structure that features a pair of parentheses β `()` β and you're **not** using a common built-in language structure like a for loop, while or do...while loop, or if...else statement, you are making use of a function.
Built-in browser functions
--------------------------
We've used functions built into the browser a lot in this course.
Every time we manipulated a text string, for example:
```js
const myText = "I am a string";
const newString = myText.replace("string", "sausage");
console.log(newString);
// the replace() string function takes a source string,
// and a target string and replaces the source string,
// with the target string, and returns the newly formed string
```
Or every time we manipulated an array:
```js
const myArray = ["I", "love", "chocolate", "frogs"];
const madeAString = myArray.join(" ");
console.log(madeAString);
// the join() function takes an array, joins
// all the array items together into a single
// string, and returns this new string
```
Or every time we generate a random number:
```js
const myNumber = Math.random();
// the random() function generates a random number between
// 0 and up to but not including 1, and returns that number
```
We were using a *function*!
**Note:** Feel free to enter these lines into your browser's JavaScript console to re-familiarize yourself with their functionality, if needed.
The JavaScript language has many built-in functions to allow you to do useful things without having to write all that code yourself. In fact, some of the code you are calling when you **invoke** (a fancy word for run, or execute) a built-in browser function couldn't be written in JavaScript β many of these functions are calling parts of the background browser code, which is written largely in low-level system languages like C++, not web languages like JavaScript.
Bear in mind that some built-in browser functions are not part of the core JavaScript language β some are defined as part of browser APIs, which build on top of the default language to provide even more functionality (refer to this early section of our course for more descriptions). We'll look at using browser APIs in more detail in a later module.
Functions versus methods
------------------------
**Functions** that are part of objects are called **methods**. You don't need to learn about the inner workings of structured JavaScript objects yet β you can wait until our later module that will teach you all about the inner workings of objects, and how to create your own. For now, we just wanted to clear up any possible confusion about method versus function β you are likely to meet both terms as you look at the available related resources across the Web.
The built-in code we've made use of so far comes in both forms: **functions** and **methods.** You can check the full list of the built-in functions, as well as the built-in objects and their corresponding methods here.
You've also seen a lot of **custom functions** in the course so far β functions defined in your code, not inside the browser. Anytime you saw a custom name with parentheses straight after it, you were using a custom function. In our random-canvas-circles.html example (see also the full source code) from our loops article, we included a custom `draw()` function that looked like this:
```js
function draw() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
for (let i = 0; i < 100; i++) {
ctx.beginPath();
ctx.fillStyle = "rgb(255 0 0 / 50%)";
ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 \* Math.PI);
ctx.fill();
}
}
```
This function draws 100 random circles inside a `<canvas>` element. Every time we want to do that, we can just invoke the function with this:
```js
draw();
```
rather than having to write all that code out again every time we want to repeat it. Functions can contain whatever code you like β you can even call other functions from inside functions. The above function for example calls the `random()` function three times, which is defined by the following code:
```js
function random(number) {
return Math.floor(Math.random() \* number);
}
```
We needed this function because the browser's built-in Math.random() function only generates a random decimal number between 0 and 1. We wanted a random whole number between 0 and a specified number.
Invoking functions
------------------
You are probably clear on this by now, but just in case, to actually use a function after it has been defined, you've got to run β or invoke β it. This is done by including the name of the function in the code somewhere, followed by parentheses.
```js
function myFunction() {
alert("hello");
}
myFunction();
// calls the function once
```
**Note:** This form of creating a function is also known as *function declaration*. It is always hoisted so that you can call the function above the function definition and it will work fine.
Function parameters
-------------------
Some functions require **parameters** to be specified when you are invoking them β these are values that need to be included inside the function parentheses, which it needs to do its job properly.
**Note:** Parameters are sometimes called arguments, properties, or even attributes.
As an example, the browser's built-in Math.random() function doesn't require any parameters. When called, it always returns a random number between 0 and 1:
```js
const myNumber = Math.random();
```
The browser's built-in string replace() function however needs two parameters β the substring to find in the main string, and the substring to replace that string with:
```js
const myText = "I am a string";
const newString = myText.replace("string", "sausage");
```
**Note:** When you need to specify multiple parameters, they are separated by commas.
### Optional parameters
Sometimes parameters are optional β you don't have to specify them. If you don't, the function will generally adopt some kind of default behavior. As an example, the array join() function's parameter is optional:
```js
const myArray = ["I", "love", "chocolate", "frogs"];
const madeAString = myArray.join(" ");
console.log(madeAString);
// returns 'I love chocolate frogs'
const madeAnotherString = myArray.join();
console.log(madeAnotherString);
// returns 'I,love,chocolate,frogs'
```
If no parameter is included to specify a joining/delimiting character, a comma is used by default.
### Default parameters
If you're writing a function and want to support optional parameters, you can specify default values by adding `=` after the name of the parameter, followed by the default value:
```js
function hello(name = "Chris") {
console.log(`Hello ${name}!`);
}
hello("Ari"); // Hello Ari!
hello(); // Hello Chris!
```
Anonymous functions and arrow functions
---------------------------------------
So far we have just created a function like so:
```js
function myFunction() {
alert("hello");
}
```
But you can also create a function that doesn't have a name:
```js
(function () {
alert("hello");
});
```
This is called an **anonymous function**, because it has no name. You'll often see anonymous functions when a function expects to receive another function as a parameter. In this case, the function parameter is often passed as an anonymous function.
**Note:** This form of creating a function is also known as *function expression*. Unlike function declarations, function expressions are not hoisted.
### Anonymous function example
For example, let's say you want to run some code when the user types into a text box. To do this you can call the `addEventListener()` function of the text box. This function expects you to pass it (at least) two parameters:
* the name of the event to listen for, which in this case is `keydown`
* a function to run when the event happens.
When the user presses a key, the browser will call the function you provided, and will pass it a parameter containing information about this event, including the particular key that the user pressed:
```js
function logKey(event) {
console.log(`You pressed "${event.key}".`);
}
textBox.addEventListener("keydown", logKey);
```
Instead of defining a separate `logKey()` function, you can pass an anonymous function into `addEventListener()`:
```js
textBox.addEventListener("keydown", function (event) {
console.log(`You pressed "${event.key}".`);
});
```
### Arrow functions
If you pass an anonymous function like this, there's an alternative form you can use, called an **arrow function**. Instead of `function(event)`, you write `(event) =>`:
```js
textBox.addEventListener("keydown", (event) => {
console.log(`You pressed "${event.key}".`);
});
```
If the function only takes one parameter, you can omit the parentheses around the parameter:
```js
textBox.addEventListener("keydown", event => {
console.log(`You pressed "${event.key}".`);
});
```
Finally, if your function contains only one line that's a `return` statement, you can also omit the braces and the `return` keyword and implicitly return the expression. In the following example, we're using the `map()` method of `Array` to double every value in the original array:
```js
const originals = [1, 2, 3];
const doubled = originals.map(item => item \* 2);
console.log(doubled); // [2, 4, 6]
```
The `map()` method takes each item in the array in turn, passing it into the given function. It then takes the value returned by that function and adds it to a new array.
So in the example above, `item => item * 2` is the arrow function equivalent of:
```js
function doubleItem(item) {
return item \* 2;
}
```
You can use the same concise syntax to rewrite the `addEventListener` example.
```js
textBox.addEventListener("keydown", (event) =>
console.log(`You pressed "${event.key}".`),
);
```
In this case, the value of `console.log()`, which is `undefined`, is implicitly returned from the callback function.
We recommend that you use arrow functions, as they can make your code shorter and more readable. To learn more, see the section on arrow functions in the JavaScript guide, and our reference page on arrow functions.
**Note:** There are some subtle differences between arrow functions and normal functions. They're outside the scope of this introductory guide and are unlikely to make a difference in the cases we've discussed here. To learn more, see the arrow function reference documentation.
### Arrow function live sample
Here's a complete working example of the "keydown" example we discussed above:
The HTML:
```html
<input id="textBox" type="text" />
<div id="output"></div>
```
The JavaScript:
```js
const textBox = document.querySelector("#textBox");
const output = document.querySelector("#output");
textBox.addEventListener("keydown", (event) => {
output.textContent = `You pressed "${event.key}".`;
});
```
```
div {
margin: 0.5rem 0;
}
```
The result - try typing into the text box and see the output:
Function scope and conflicts
----------------------------
Let's talk a bit about scope β a very important concept when dealing with functions. When you create a function, the variables and other things defined inside the function are inside their own separate **scope**, meaning that they are locked away in their own separate compartments, unreachable from code outside the functions.
The top-level outside all your functions is called the **global scope**. Values defined in the global scope are accessible from everywhere in the code.
JavaScript is set up like this for various reasons β but mainly because of security and organization. Sometimes you don't want variables to be accessible from everywhere in the code β external scripts that you call in from elsewhere could start to mess with your code and cause problems because they happen to be using the same variable names as other parts of the code, causing conflicts. This might be done maliciously, or just by accident.
For example, say you have an HTML file that is calling in two external JavaScript files, and both of them have a variable and a function defined that use the same name:
```html
<!-- Excerpt from my HTML -->
<script src="first.js"></script>
<script src="second.js"></script>
<script>
greeting();
</script>
```
```js
// first.js
const name = "Chris";
function greeting() {
alert(`Hello ${name}: welcome to our company.`);
}
```
```js
// second.js
const name = "Zaptec";
function greeting() {
alert(`Our company is called ${name}.`);
}
```
Both functions you want to call are called `greeting()`, but you can only ever access the `first.js` file's `greeting()` function (the second one is ignored). In addition, an error results when attempting (in the `second.js` file) to assign a new value to the `name` variable β because it was already declared with `const`, and so can't be reassigned.
**Note:** You can see this example running live on GitHub (see also the source code).
Keeping parts of your code locked away in functions avoids such problems, and is considered the best practice.
It is a bit like a zoo. The lions, zebras, tigers, and penguins are kept in their own enclosures and only have access to the things inside their enclosures β in the same manner as the function scopes. If they were able to get into other enclosures, problems would occur. At best, different animals would feel really uncomfortable inside unfamiliar habitats β a lion or tiger would feel terrible inside the penguins' watery, icy domain. At worst, the lions and tigers might try to eat the penguins!
![Four different animals enclosed in their respective habitat in a Zoo](/en-US/docs/Learn/JavaScript/Building_blocks/Functions/mdn-mozilla-zoo.png)
The zoo keeper is like the global scope β they have the keys to access every enclosure, restock food, tend to sick animals, etc.
### Active learning: Playing with scope
Let's look at a real example to demonstrate scoping.
1. First, make a local copy of our function-scope.html example. This contains two functions called `a()` and `b()`, and three variables β `x`, `y`, and `z` β two of which are defined inside the functions, and one in the global scope. It also contains a third function called `output()`, which takes a single parameter and outputs it in a paragraph on the page.
2. Open the example up in a browser and in your text editor.
3. Open the JavaScript console in your browser developer tools. In the JavaScript console, enter the following command:
```js
output(x);
```
You should see the value of variable `x` printed to the browser viewport.
4. Now try entering the following in your console
```js
output(y);
output(z);
```
Both of these should throw an error into the console along the lines of "ReferenceError: y is not defined". Why is that? Because of function scope, `y` and `z` are locked inside the `a()` and `b()` functions, so `output()` can't access them when called from the global scope.
5. However, what about when it's called from inside another function? Try editing `a()` and `b()` so they look like this:
```js
function a() {
const y = 2;
output(y);
}
function b() {
const z = 3;
output(z);
}
```
Save the code and reload it in your browser, then try calling the `a()` and `b()` functions from the JavaScript console:
```js
a();
b();
```
You should see the `y` and `z` values printed in the browser viewport. This works fine, as the `output()` function is being called inside the other functions β in the same scope as the variables it is printing are defined in, in each case. `output()` itself is available from anywhere, as it is defined in the global scope.
6. Now try updating your code like this:
```js
function a() {
const y = 2;
output(x);
}
function b() {
const z = 3;
output(x);
}
```
7. Save and reload again, and try this again in your JavaScript console:
```js
a();
b();
```
Both the `a()` and `b()` call should print the value of x to the browser viewport. These work fine because even though the `output()` calls are not in the same scope as `x` is defined in, `x` is a global variable so is available inside all code, everywhere.
8. Finally, try updating your code like this:
```js
function a() {
const y = 2;
output(z);
}
function b() {
const z = 3;
output(y);
}
```
9. Save and reload again, and try this again in your JavaScript console:
```js
a();
b();
```
This time the `a()` and `b()` calls will throw that annoying ReferenceError: *variable name* is not defined error into the console β this is because the `output()` calls and the variables they are trying to print are not in the same function scopes β the variables are effectively invisible to those function calls.
**Note:** The same scoping rules do not apply to loop (e.g. `for() { }`) and conditional blocks (e.g. `if () { }`) β they look very similar, but they are not the same thing! Take care not to get these confused.
**Note:** The ReferenceError: "x" is not defined error is one of the most common you'll encounter. If you get this error and you are sure that you have defined the variable in question, check what scope it is in.
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Functions. These tests require skills that are covered in the next two articles, so you might want to read those first before trying them.
Conclusion
----------
This article has explored the fundamental concepts behind functions, paving the way for the next one in which we get practical and take you through the steps to building up your own custom function.
See also
--------
* Functions detailed guide β covers some advanced features not included here.
* Functions reference
* Default parameters, Arrow functions β advanced concept references
* Previous
* Overview: Building blocks
* Next |
Introduction to events - Learn web development | Introduction to events
======================
* Previous
* Overview: Building blocks
* Next
Events are things that happen in the system you are programming, which the system tells you about so your code can react to them.
For example, if the user clicks a button on a webpage, you might want to react to that action by displaying an information box.
In this article, we discuss some important concepts surrounding events, and look at how they work in browsers.
This won't be an exhaustive study; just what you need to know at this stage.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of HTML, CSS, and
JavaScript first steps.
|
| Objective: |
To understand the fundamental theory of events, how they work in
browsers, and how events may differ in different programming
environments.
|
What is an event?
-----------------
Events are things that happen in the system you are programming β the system produces (or "fires") a signal of some kind when an event occurs, and provides a mechanism by which an action can be automatically taken (that is, some code running) when the event occurs.
Events are fired inside the browser window, and tend to be attached to a specific item that resides in it. This might be a single element, a set of elements, the HTML document loaded in the current tab, or the entire browser window.
There are many different types of events that can occur.
For example:
* The user selects, clicks, or hovers the cursor over a certain element.
* The user chooses a key on the keyboard.
* The user resizes or closes the browser window.
* A web page finishes loading.
* A form is submitted.
* A video is played, paused, or ends.
* An error occurs.
You can gather from this (and from glancing at the MDN event reference) that there are **a lot** of events that can be fired.
To react to an event, you attach an **event handler** to it. This is a block of code (usually a JavaScript function that you as a programmer create) that runs when the event fires.
When such a block of code is defined to run in response to an event, we say we are **registering an event handler**.
Note: Event handlers are sometimes called **event listeners** β they are pretty much interchangeable for our purposes, although strictly speaking, they work together.
The listener listens out for the event happening, and the handler is the code that is run in response to it happening.
**Note:** Web events are not part of the core JavaScript language β they are defined as part of the APIs built into the browser.
### An example: handling a click event
In the following example, we have a single `<button>` in the page:
```html
<button>Change color</button>
```
```
button {
margin: 10px;
}
```
Then we have some JavaScript. We'll look at this in more detail in the next section, but for now we can just say: it adds an event handler to the button's `"click"` event, and the handler reacts to the event by setting the page background to a random color:
```js
const btn = document.querySelector("button");
function random(number) {
return Math.floor(Math.random() \* (number + 1));
}
btn.addEventListener("click", () => {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
document.body.style.backgroundColor = rndCol;
});
```
The example output is as follows. Try clicking the button:
Using addEventListener()
------------------------
As we saw in the last example, objects that can fire events have an `addEventListener()` method, and this is the recommended mechanism for adding event handlers.
Let's take a closer look at the code from the last example:
```js
const btn = document.querySelector("button");
function random(number) {
return Math.floor(Math.random() \* (number + 1));
}
btn.addEventListener("click", () => {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
document.body.style.backgroundColor = rndCol;
});
```
The HTML `<button>` element will fire an event when the user clicks the button. So it defines an `addEventListener()` function, which we are calling here. We're passing in two parameters:
* the string `"click"`, to indicate that we want to listen to the click event. Buttons can fire lots of other events, such as `"mouseover"` when the user moves their mouse over the button, or `"keydown"` when the user presses a key and the button is focused.
* a function to call when the event happens. In our case, the function generates a random RGB color and sets the `background-color` of the page `<body>` to that color.
It is fine to make the handler function a separate named function, like this:
```js
const btn = document.querySelector("button");
function random(number) {
return Math.floor(Math.random() \* (number + 1));
}
function changeBackground() {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
document.body.style.backgroundColor = rndCol;
}
btn.addEventListener("click", changeBackground);
```
### Listening for other events
There are many different events that can be fired by a button element. Let's experiment.
First, make a local copy of random-color-addeventlistener.html, and open it in your browser.
It's just a copy of the simple random color example we've played with already. Now try changing `click` to the following different values in turn, and observing the results in the example:
* `focus` and `blur` β The color changes when the button is focused and unfocused; try pressing the tab to focus on the button and press the tab again to focus away from the button.
These are often used to display information about filling in form fields when they are focused, or to display an error message if a form field is filled with an incorrect value.
* `dblclick` β The color changes only when the button is double-clicked.
* `mouseover` and `mouseout` β The color changes when the mouse pointer hovers over the button, or when the pointer moves off the button, respectively.
Some events, such as `click`, are available on nearly any element. Others are more specific and only useful in certain situations: for example, the `play` event is only available on some elements, such as `<video>`.
### Removing listeners
If you've added an event handler using `addEventListener()`, you can remove it again using the `removeEventListener()` method. For example, this would remove the `changeBackground()` event handler:
```js
btn.removeEventListener("click", changeBackground);
```
Event handlers can also be removed by passing an `AbortSignal` to `addEventListener()` and then later calling `abort()` on the controller owning the `AbortSignal`.
For example, to add an event handler that we can remove with an `AbortSignal`:
```js
const controller = new AbortController();
btn.addEventListener("click",
() => {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
document.body.style.backgroundColor = rndCol;
},
{ signal: controller.signal } // pass an AbortSignal to this handler
);
```
Then the event handler created by the code above can be removed like this:
```js
controller.abort(); // removes any/all event handlers associated with this controller
```
For simple, small programs, cleaning up old, unused event handlers isn't necessary, but for larger, more complex programs, it can improve efficiency.
Also, the ability to remove event handlers allows you to have the same button performing different actions in different circumstances: all you have to do is add or remove handlers.
### Adding multiple listeners for a single event
By making more than one call to `addEventListener()`, providing different handlers, you can have multiple handlers for a single event:
```js
myElement.addEventListener("click", functionA);
myElement.addEventListener("click", functionB);
```
Both functions would now run when the element is clicked.
### Learn more
There are other powerful features and options available with `addEventListener()`.
These are a little out of scope for this article, but if you want to read them, visit the `addEventListener()` and `removeEventListener()` reference pages.
Other event listener mechanisms
-------------------------------
We recommend that you use `addEventListener()` to register event handlers. It's the most powerful method and scales best with more complex programs. However, there are two other ways of registering event handlers that you might see: *event handler properties* and *inline event handlers*.
### Event handler properties
Objects (such as buttons) that can fire events also usually have properties whose name is `on` followed by the name of the event. For example, elements have a property `onclick`.
This is called an *event handler property*. To listen for the event, you can assign the handler function to the property.
For example, we could rewrite the random-color example like this:
```js
const btn = document.querySelector("button");
function random(number) {
return Math.floor(Math.random() \* (number + 1));
}
btn.onclick = () => {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
document.body.style.backgroundColor = rndCol;
};
```
You can also set the handler property to a named function:
```js
const btn = document.querySelector("button");
function random(number) {
return Math.floor(Math.random() \* (number + 1));
}
function bgChange() {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
document.body.style.backgroundColor = rndCol;
}
btn.onclick = bgChange;
```
With event handler properties, you can't add more than one handler for a single event. For example, you can call `addEventListener('click', handler)` on an element multiple times, with different functions specified in the second argument:
```js
element.addEventListener("click", function1);
element.addEventListener("click", function2);
```
This is impossible with event handler properties because any subsequent attempts to set the property will overwrite earlier ones:
```js
element.onclick = function1;
element.onclick = function2;
```
### Inline event handlers β don't use these
You might also see a pattern like this in your code:
```html
<button onclick="bgChange()">Press me</button>
```
```js
function bgChange() {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
document.body.style.backgroundColor = rndCol;
}
```
The earliest method of registering event handlers found on the Web involved *event handler HTML attributes* (or *inline event handlers*) like the one shown above β the attribute value is literally the JavaScript code you want to run when the event occurs.
The above example invokes a function defined inside a `<script>` element on the same page, but you could also insert JavaScript directly inside the attribute, for example:
```html
<button onclick="alert('Hello, this is my old-fashioned event handler!');">
Press me
</button>
```
You can find HTML attribute equivalents for many of the event handler properties; however, you shouldn't use these β they are considered bad practice.
It might seem easy to use an event handler attribute if you are doing something really quick, but they quickly become unmanageable and inefficient.
For a start, it is not a good idea to mix up your HTML and your JavaScript, as it becomes hard to read. Keeping your JavaScript separate is a good practice, and if it is in a separate file you can apply it to multiple HTML documents.
Even in a single file, inline event handlers are not a good idea.
One button is OK, but what if you had 100 buttons? You'd have to add 100 attributes to the file; it would quickly turn into a maintenance nightmare.
With JavaScript, you could easily add an event handler function to all the buttons on the page no matter how many there were, using something like this:
```js
const buttons = document.querySelectorAll("button");
for (const button of buttons) {
button.addEventListener("click", bgChange);
}
```
Finally, many common server configurations will disallow inline JavaScript, as a security measure.
**You should never use the HTML event handler attributes** β those are outdated, and using them is bad practice.
Event objects
-------------
Sometimes, inside an event handler function, you'll see a parameter specified with a name such as `event`, `evt`, or `e`.
This is called the **event object**, and it is automatically passed to event handlers to provide extra features and information.
For example, let's rewrite our random color example again slightly:
```js
const btn = document.querySelector("button");
function random(number) {
return Math.floor(Math.random() \* (number + 1));
}
function bgChange(e) {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
e.target.style.backgroundColor = rndCol;
console.log(e);
}
btn.addEventListener("click", bgChange);
```
**Note:** You can find the full source code for this example on GitHub (also see it running live).
Here you can see we are including an event object, **e**, in the function, and in the function setting a background color style on `e.target` β which is the button itself.
The `target` property of the event object is always a reference to the element the event occurred upon.
So, in this example, we are setting a random background color on the button, not the page.
**Note:** See the Event delegation section below for an example where we use `event.target`.
**Note:** You can use any name you like for the event object β you just need to choose a name that you can then use to reference it inside the event handler function.
`e`/`evt`/`event` is most commonly used by developers because they are short and easy to remember.
It's always good to be consistent β with yourself, and with others if possible.
### Extra properties of event objects
Most event objects have a standard set of properties and methods available on the event object; see the `Event` object reference for a full list.
Some event objects add extra properties that are relevant to that particular type of event. For example, the `keydown` event fires when the user presses a key. Its event object is a `KeyboardEvent`, which is a specialized `Event` object with a `key` property that tells you which key was pressed:
```html
<input id="textBox" type="text" />
<div id="output"></div>
```
```js
const textBox = document.querySelector("#textBox");
const output = document.querySelector("#output");
textBox.addEventListener("keydown", (event) => {
output.textContent = `You pressed "${event.key}".`;
});
```
```
div {
margin: 0.5rem 0;
}
```
Try typing into the text box and see the output:
Preventing default behavior
---------------------------
Sometimes, you'll come across a situation where you want to prevent an event from doing what it does by default.
The most common example is that of a web form, for example, a custom registration form.
When you fill in the details and click the submit button, the natural behavior is for the data to be submitted to a specified page on the server for processing, and the browser to be redirected to a "success message" page of some kind (or the same page, if another is not specified).
The trouble comes when the user has not submitted the data correctly β as a developer, you want to prevent the submission to the server and give an error message saying what's wrong and what needs to be done to put things right.
Some browsers support automatic form data validation features, but since many don't, you are advised to not rely on those and implement your own validation checks.
Let's look at a simple example.
First, a simple HTML form that requires you to enter your first and last name:
```html
<form>
<div>
<label for="fname">First name: </label>
<input id="fname" type="text" />
</div>
<div>
<label for="lname">Last name: </label>
<input id="lname" type="text" />
</div>
<div>
<input id="submit" type="submit" />
</div>
</form>
<p></p>
```
```
div {
margin-bottom: 10px;
}
```
Now some JavaScript β here we implement a very simple check inside a handler for the `submit` event (the submit event is fired on a form when it is submitted) that tests whether the text fields are empty.
If they are, we call the `preventDefault()` function on the event object β which stops the form submission β and then display an error message in the paragraph below our form to tell the user what's wrong:
```js
const form = document.querySelector("form");
const fname = document.getElementById("fname");
const lname = document.getElementById("lname");
const para = document.querySelector("p");
form.addEventListener("submit", (e) => {
if (fname.value === "" || lname.value === "") {
e.preventDefault();
para.textContent = "You need to fill in both names!";
}
});
```
Obviously, this is pretty weak form validation β it wouldn't stop the user from validating the form with spaces or numbers entered into the fields, for example β but it is OK for example purposes.
The output is as follows:
**Note:** For the full source code, see preventdefault-validation.html (also see it running live here).
Event bubbling
--------------
Event bubbling describes how the browser handles events targeted at nested elements.
### Setting a listener on a parent element
Consider a web page like this:
```html
<div id="container">
<button>Click me!</button>
</div>
<pre id="output"></pre>
```
Here the button is inside another element, a `<div>` element. We say that the `<div>` element here is the **parent** of the element it contains. What happens if we add a click event handler to the parent, then click the button?
```js
const output = document.querySelector("#output");
function handleClick(e) {
output.textContent += `You clicked on a ${e.currentTarget.tagName} element\n`;
}
const container = document.querySelector("#container");
container.addEventListener("click", handleClick);
```
You'll see that the parent fires a click event when the user clicks the button:
```
You clicked on a DIV element
```
This makes sense: the button is inside the `<div>`, so when you click the button you're also implicitly clicking the element it is inside.
### Bubbling example
What happens if we add event listeners to the button *and* the parent?
```html
<body>
<div id="container">
<button>Click me!</button>
</div>
<pre id="output"></pre>
</body>
```
Let's try adding click event handlers to the button, its parent (the `<div>`), and the `<body>` element that contains both of them:
```js
const output = document.querySelector("#output");
function handleClick(e) {
output.textContent += `You clicked on a ${e.currentTarget.tagName} element\n`;
}
const container = document.querySelector("#container");
const button = document.querySelector("button");
document.body.addEventListener("click", handleClick);
container.addEventListener("click", handleClick);
button.addEventListener("click", handleClick);
```
You'll see that all three elements fire a click event when the user clicks the button:
```
You clicked on a BUTTON element
You clicked on a DIV element
You clicked on a BODY element
```
In this case:
* the click on the button fires first
* followed by the click on its parent (the `<div>` element)
* followed by the `<div>` element's parent (the `<body>` element).
We describe this by saying that the event **bubbles up** from the innermost element that was clicked.
This behavior can be useful and can also cause unexpected problems. In the next sections, we'll see a problem that it causes, and find the solution.
### Video player example
In this example our page contains a video, which is hidden initially, and a button labeled "Display video". We want the following interaction:
* When the user clicks the "Display video" button, show the box containing the video, but don't start playing the video yet.
* When the user clicks on the video, start playing the video.
* When the user clicks anywhere in the box outside the video, hide the box.
The HTML looks like this:
```html
<button>Display video</button>
<div class="hidden">
<video>
<source
src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm"
type="video/webm" />
<p>
Your browser doesn't support HTML video. Here is a
<a href="rabbit320.mp4">link to the video</a> instead.
</p>
</video>
</div>
```
It includes:
* a `<button>` element
* a `<div>` element which initially has a `class="hidden"` attribute
* a `<video>` element nested inside the `<div>` element.
We're using CSS to hide elements with the `"hidden"` class set.
```
div {
width: 100%;
height: 100%;
background-color: #eee;
}
.hidden {
display: none;
}
div video {
padding: 40px;
display: block;
width: 400px;
margin: 40px auto;
}
```
The JavaScript looks like this:
```js
const btn = document.querySelector("button");
const box = document.querySelector("div");
const video = document.querySelector("video");
btn.addEventListener("click", () => box.classList.remove("hidden"));
video.addEventListener("click", () => video.play());
box.addEventListener("click", () => box.classList.add("hidden"));
```
This adds three `'click'` event listeners:
* one on the `<button>`, which shows the `<div>` that contains the `<video>`
* one on the `<video>`, which starts playing the video
* one on the `<div>`, which hides the video
Let's see how this works:
You should see that when you click the button, the box and the video it contains are shown. But then when you click the video, the video starts to play, but the box is hidden again!
The video is inside the `<div>` β it is part of it β so clicking the video runs *both* the event handlers, causing this behavior.
### Fixing the problem with stopPropagation()
As we saw in the last section, event bubbling can sometimes create problems, but there is a way to prevent it.
The `Event` object has a function available on it called `stopPropagation()` which, when called inside an event handler, prevents the event from bubbling up to any other elements.
We can fix our current problem by changing the JavaScript to this:
```js
const btn = document.querySelector("button");
const box = document.querySelector("div");
const video = document.querySelector("video");
btn.addEventListener("click", () => box.classList.remove("hidden"));
video.addEventListener("click", (event) => {
event.stopPropagation();
video.play();
});
box.addEventListener("click", () => box.classList.add("hidden"));
```
All we're doing here is calling `stopPropagation()` on the event object in the handler for the `<video>` element's `'click'` event. This will stop that event from bubbling up to the box. Now try clicking the button and then the video:
```
<button>Display video</button>
<div class="hidden">
<video>
<source
src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm"
type="video/webm" />
<p>
Your browser doesn't support HTML video. Here is a
<a href="rabbit320.mp4">link to the video</a> instead.
</p>
</video>
</div>
```
```
div {
width: 100%;
height: 100%;
background-color: #eee;
}
.hidden {
display: none;
}
div video {
padding: 40px;
display: block;
width: 400px;
margin: 40px auto;
}
```
### Event capture
An alternative form of event propagation is *event capture*. This is like event bubbling but the order is reversed: so instead of the event firing first on the innermost element targeted, and then on successively less nested elements, the event fires first on the *least nested* element, and then on successively more nested elements, until the target is reached.
Event capture is disabled by default. To enable it you have to pass the `capture` option in `addEventListener()`.
This example is just like the bubbling example we saw earlier, except that we have used the `capture` option:
```html
<body>
<div id="container">
<button>Click me!</button>
</div>
<pre id="output"></pre>
</body>
```
```js
const output = document.querySelector("#output");
function handleClick(e) {
output.textContent += `You clicked on a ${e.currentTarget.tagName} element\n`;
}
const container = document.querySelector("#container");
const button = document.querySelector("button");
document.body.addEventListener("click", handleClick, { capture: true });
container.addEventListener("click", handleClick, { capture: true });
button.addEventListener("click", handleClick);
```
In this case, the order of messages is reversed: the `<body>` event handler fires first, followed by the `<div>` event handler, followed by the `<button>` event handler:
```
You clicked on a BODY element
You clicked on a DIV element
You clicked on a BUTTON element
```
Why bother with both capturing and bubbling? In the bad old days, when browsers were much less cross-compatible than now, Netscape only used event capturing, and Internet Explorer used only event bubbling. When the W3C decided to try to standardize the behavior and reach a consensus, they ended up with this system that included both, which is what modern browsers implement.
By default almost all event handlers are registered in the bubbling phase, and this makes more sense most of the time.
Event delegation
----------------
In the last section, we looked at a problem caused by event bubbling and how to fix it. Event bubbling isn't just annoying, though: it can be very useful. In particular, it enables **event delegation**. In this practice, when we want some code to run when the user interacts with any one of a large number of child elements, we set the event listener on their parent and have events that happen on them bubble up to their parent rather than having to set the event listener on every child individually.
Let's go back to our first example, where we set the background color of the whole page when the user clicked a button. Suppose that instead, the page is divided into 16 tiles, and we want to set each tile to a random color when the user clicks that tile.
Here's the HTML:
```html
<div id="container">
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
</div>
```
We have a little CSS, to set the size and position of the tiles:
```css
.tile {
height: 100px;
width: 25%;
float: left;
}
```
Now in JavaScript, we could add a click event handler for every tile. But a much simpler and more efficient option is to set the click event handler on the parent, and rely on event bubbling to ensure that the handler is executed when the user clicks on a tile:
```js
function random(number) {
return Math.floor(Math.random() \* number);
}
function bgChange() {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
return rndCol;
}
const container = document.querySelector("#container");
container.addEventListener("click", (event) => {
event.target.style.backgroundColor = bgChange();
});
```
The output is as follows (try clicking around on it):
**Note:** In this example, we're using `event.target` to get the element that was the target of the event (that is, the innermost element). If we wanted to access the element that handled this event (in this case the container) we could use `event.currentTarget`.
**Note:** See useful-eventtarget.html for the full source code; also see it running live here.
It's not just web pages
-----------------------
Events are not unique to JavaScript β most programming languages have some kind of event model, and the way the model works often differs from JavaScript's way.
In fact, the event model in JavaScript for web pages differs from the event model for JavaScript as it is used in other environments.
For example, Node.js is a very popular JavaScript runtime that enables developers to use JavaScript to build network and server-side applications.
The Node.js event model relies on listeners to listen for events and emitters to emit events periodically β it doesn't sound that different, but the code is quite different, making use of functions like `on()` to register an event listener, and `once()` to register an event listener that unregisters after it has run once.
The HTTP connect event docs provide a good example.
You can also use JavaScript to build cross-browser add-ons β browser functionality enhancements β using a technology called WebExtensions.
The event model is similar to the web events model, but a bit different β event listeners' properties are written in camel case (such as `onMessage` rather than `onmessage`), and need to be combined with the `addListener` function.
See the `runtime.onMessage` page for an example.
You don't need to understand anything about other such environments at this stage in your learning; we just wanted to make it clear that events can differ in different programming environments.
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? To verify you've retained this information before you move on β see Test your skills: Events.
Conclusion
----------
You should now know all you need to know about web events at this early stage.
As mentioned, events are not really part of the core JavaScript β they are defined in browser Web APIs.
Also, it is important to understand that the different contexts in which JavaScript is used have different event models β from Web APIs to other areas such as browser WebExtensions and Node.js (server-side JavaScript).
We are not expecting you to understand all of these areas now, but it certainly helps to understand the basics of events as you forge ahead with learning web development.
**Note:** If you get stuck, you can reach out to us in one of our communication channels.
See also
--------
* domevents.dev β a very useful interactive playground app that enables learning about the behavior of the DOM Event system through exploration.
* Event reference
* Event order (discussion of capturing and bubbling) β an excellently detailed piece by Peter-Paul Koch.
* Event accessing (discussion of the event object) β another excellently detailed piece by Peter-Paul Koch.
* Previous
* Overview: Building blocks
* Next |
Test your skills: Functions - Learn web development | Test your skills: Functions
===========================
The aim of this skill test is to assess whether you've understood our Functions β reusable blocks of code, Build your own function, and Function return values articles.
**Note:** You can try solutions by downloading the code and putting it in an online editor such as CodePen, JSFiddle, or Glitch.
If there is an error, it will be logged in the results panel on the page or into the browser's JavaScript console to help you.
If you get stuck, you can reach out to us in one of our communication channels.
DOM manipulation: considered useful
-----------------------------------
Some of the questions below require you to write some DOM manipulation code to complete them β such as creating new HTML elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page β all via JavaScript.
We haven't explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into what DOM APIs you need to successfully answer the questions. A good starting place is our Manipulating documents tutorial.
Functions 1
-----------
For the first task, you have to create a simple function β `chooseName()` β that prints a random name from the provided array (`names`) to the provided paragraph (`para`), and then run it once.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Functions 2
-----------
For our second functions-related task, you need to create a function that draws a rectangle on the provided `<canvas>` (reference variable `canvas`, context available in `ctx`), based on the five provided input variables:
* `x` β the x coordinate of the rectangle.
* `y` β the y coordinate of the rectangle.
* `width` β the width of the rectangle.
* `height` β the height of the rectangle.
* `color` β the color of the rectangle.
You'll want to clear the canvas before drawing, so that when the code is updated in the case of the live version, you don't get lots of rectangles drawn on top of one another.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Functions 3
-----------
In this task, you return to the problem posed in Task 1, with the aim of improving it. The three improvements we want you to make are:
1. Refactor the code that generates the random number into a separate function called `random()`, which takes as parameters two generic bounds that the random number should be between, and returns the result.
2. Update the `chooseName()` function so that it makes use of the random number function, takes the array to choose from as a parameter (making it more flexible), and returns the result.
3. Print the returned result into the paragraph (`para`)'s `textContent`.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Functions 4
-----------
In this task, we have an array of names, and we're using `Array.filter()` to get an array of only names shorter than 5 characters. The filter is currently being passed a named function `isShort()` which checks the length of the name, returning `true` if the name is less than 5 characters long, and `false` otherwise.
We'd like you to change this into an arrow function. See how compact you can make it.
Download the starting point for this task to work in your own editor or in an online editor. |
Making decisions in your code β conditionals - Learn web development | Making decisions in your code β conditionals
============================================
* Overview: Building blocks
* Next
In any programming language, the code needs to make decisions and carry out actions accordingly depending on different inputs. For example, in a game, if the player's number of lives is 0, then it's game over. In a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is nighttime. In this article, we'll explore how so-called conditional statements work in JavaScript.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of HTML, CSS, and
JavaScript first steps.
|
| Objective: | To understand how to use conditional structures in JavaScript. |
You can have it on one condition!
---------------------------------
Human beings (and other animals) make decisions all the time that affect their lives, from small ("should I eat one cookie or two?") to large ("should I stay in my home country and work on my father's farm, or should I move to America and study astrophysics?")
Conditional statements allow us to represent such decision making in JavaScript, from the choice that must be made (for example, "one cookie or two"), to the resulting outcome of those choices (perhaps the outcome of "ate one cookie" might be "still felt hungry", and the outcome of "ate two cookies" might be "felt full, but mom scolded me for eating all the cookies".)
![A cartoon character resembling a person holding a cookie jar labeled 'Cookies'. There is a question mark above the head of the character. There are two speech bubbles. The left speech bubble has one cookie. The right speech bubble has two cookies. Together it implies the character is trying to decide if it wants to one cookie or two cookies.](/en-US/docs/Learn/JavaScript/Building_blocks/conditionals/cookie-choice-small.png)
if...else statements
--------------------
Let's look at by far the most common type of conditional statement you'll use in JavaScript β the humble `if...else` statement.
### Basic if...else syntax
Basic `if...else` syntax looks like this:
```js
if (condition) {
/\* code to run if condition is true \*/
} else {
/\* run some other code instead \*/
}
```
Here we've got:
1. The keyword `if` followed by some parentheses.
2. A condition to test, placed inside the parentheses (typically "is this value bigger than this other value?", or "does this value exist?"). The condition makes use of the comparison operators we discussed in the last module and returns `true` or `false`.
3. A set of curly braces, inside which we have some code β this can be any code we like, and it only runs if the condition returns `true`.
4. The keyword `else`.
5. Another set of curly braces, inside which we have some more code β this can be any code we like, and it only runs if the condition is not `true` β or in other words, the condition is `false`.
This code is pretty human-readable β it is saying "**if** the **condition** returns `true`, run code A, **else** run code B"
You should note that you don't have to include the `else` and the second curly brace block β the following is also perfectly legal code:
```js
if (condition) {
/\* code to run if condition is true \*/
}
/\* run some other code \*/
```
However, you need to be careful here β in this case, the second block of code is not controlled by the conditional statement, so it **always** runs, regardless of whether the condition returns `true` or `false`. This is not necessarily a bad thing, but it might not be what you want β often you want to run one block of code *or* the other, not both.
As a final point, while not recommended, you may sometimes see `if...else` statements written without the curly braces:
```js
if (condition) /\* code to run if condition is true \*/
else /\* run some other code instead \*/
```
This syntax is perfectly valid, but it is much easier to understand the code if you use the curly braces to delimit the blocks of code, and use multiple lines and indentation.
### A real example
To understand this syntax better, let's consider a real example. Imagine a child being asked for help with a chore by their mother or father. The parent might say "Hey sweetheart! If you help me by going and doing the shopping, I'll give you some extra allowance so you can afford that toy you wanted." In JavaScript, we could represent this like so:
```js
let shoppingDone = false;
let childsAllowance;
if (shoppingDone === true) {
childsAllowance = 10;
} else {
childsAllowance = 5;
}
```
This code as shown always results in the `shoppingDone` variable returning `false`, meaning disappointment for our poor child. It'd be up to us to provide a mechanism for the parent to set the `shoppingDone` variable to `true` if the child did the shopping.
**Note:** You can see a more complete version of this example on GitHub (also see it running live.)
### else if
The last example provided us with two choices, or outcomes β but what if we want more than two?
There is a way to chain on extra choices/outcomes to your `if...else` β using `else if`. Each extra choice requires an additional block to put in between `if () { }` and `else { }` β check out the following more involved example, which could be part of a simple weather forecast application:
```html
<label for="weather">Select the weather type today: </label>
<select id="weather">
<option value="">--Make a choice--</option>
<option value="sunny">Sunny</option>
<option value="rainy">Rainy</option>
<option value="snowing">Snowing</option>
<option value="overcast">Overcast</option>
</select>
<p></p>
```
```js
const select = document.querySelector("select");
const para = document.querySelector("p");
select.addEventListener("change", setWeather);
function setWeather() {
const choice = select.value;
if (choice === "sunny") {
para.textContent =
"It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.";
} else if (choice === "rainy") {
para.textContent =
"Rain is falling outside; take a rain coat and an umbrella, and don't stay out for too long.";
} else if (choice === "snowing") {
para.textContent =
"The snow is coming down β it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.";
} else if (choice === "overcast") {
para.textContent =
"It isn't raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.";
} else {
para.textContent = "";
}
}
```
1. Here we've got an HTML `<select>` element allowing us to make different weather choices, and a simple paragraph.
2. In the JavaScript, we are storing a reference to both the `<select>` and `<p>` elements, and adding an event listener to the `<select>` element so that when its value is changed, the `setWeather()` function is run.
3. When this function is run, we first set a variable called `choice` to the current value selected in the `<select>` element. We then use a conditional statement to show different text inside the paragraph depending on what the value of `choice` is. Notice how all the conditions are tested in `else if () { }` blocks, except for the first one, which is tested in an `if () { }` block.
4. The very last choice, inside the `else { }` block, is basically a "last resort" option β the code inside it will be run if none of the conditions are `true`. In this case, it serves to empty the text out of the paragraph if nothing is selected, for example, if a user decides to re-select the "--Make a choice--" placeholder option shown at the beginning.
**Note:** You can also find this example on GitHub (see it running live on there also.)
### A note on comparison operators
Comparison operators are used to test the conditions inside our conditional statements. We first looked at comparison operators back in our Basic math in JavaScript β numbers and operators article. Our choices are:
* `===` and `!==` β test if one value is identical to, or not identical to, another.
* `<` and `>` β test if one value is less than or greater than another.
* `<=` and `>=` β test if one value is less than or equal to, or greater than or equal to, another.
We wanted to make a special mention of testing boolean (`true`/`false`) values, and a common pattern you'll come across again and again. Any value that is not `false`, `undefined`, `null`, `0`, `NaN`, or an empty string (`''`) actually returns `true` when tested as a conditional statement, therefore you can use a variable name on its own to test whether it is `true`, or even that it exists (that is, it is not undefined.) So for example:
```js
let cheese = "Cheddar";
if (cheese) {
console.log("Yay! Cheese available for making cheese on toast.");
} else {
console.log("No cheese on toast for you today.");
}
```
And, returning to our previous example about the child doing a chore for their parent, you could write it like this:
```js
let shoppingDone = false;
let childsAllowance;
// We don't need to explicitly specify 'shoppingDone === true'
if (shoppingDone) {
childsAllowance = 10;
} else {
childsAllowance = 5;
}
```
### Nesting if...else
It is perfectly OK to put one `if...else` statement inside another one β to nest them. For example, we could update our weather forecast application to show a further set of choices depending on what the temperature is:
```js
if (choice === "sunny") {
if (temperature < 86) {
para.textContent = `It is ${temperature} degrees outside β nice and sunny. Let's go out to the beach, or the park, and get an ice cream.`;
} else if (temperature >= 86) {
para.textContent = `It is ${temperature} degrees outside β REALLY HOT! If you want to go outside, make sure to put some sunscreen on.`;
}
}
```
Even though the code all works together, each `if...else` statement works completely independently of the other one.
### Logical operators: AND, OR and NOT
If you want to test multiple conditions without writing nested `if...else` statements, logical operators can help you. When used in conditions, the first two do the following:
* `&&` β AND; allows you to chain together two or more expressions so that all of them have to individually evaluate to `true` for the whole expression to return `true`.
* `||` β OR; allows you to chain together two or more expressions so that one or more of them have to individually evaluate to `true` for the whole expression to return `true`.
To give you an AND example, the previous example snippet can be rewritten to this:
```js
if (choice === "sunny" && temperature < 86) {
para.textContent = `It is ${temperature} degrees outside β nice and sunny. Let's go out to the beach, or the park, and get an ice cream.`;
} else if (choice === "sunny" && temperature >= 86) {
para.textContent = `It is ${temperature} degrees outside β REALLY HOT! If you want to go outside, make sure to put some sunscreen on.`;
}
```
So for example, the first code block will only be run if `choice === 'sunny'` *and* `temperature < 86` return `true`.
Let's look at a quick OR example:
```js
if (iceCreamVanOutside || houseStatus === "on fire") {
console.log("You should leave the house quickly.");
} else {
console.log("Probably should just stay in then.");
}
```
The last type of logical operator, NOT, expressed by the `!` operator, can be used to negate an expression. Let's combine it with OR in the above example:
```js
if (!(iceCreamVanOutside || houseStatus === "on fire")) {
console.log("Probably should just stay in then.");
} else {
console.log("You should leave the house quickly.");
}
```
In this snippet, if the OR statement returns `true`, the NOT operator will negate it so that the overall expression returns `false`.
You can combine as many logical statements together as you want, in whatever structure. The following example executes the code inside only if both OR statements return true, meaning that the overall AND statement will return true:
```js
if ((x === 5 || y > 3 || z <= 10) && (loggedIn || userName === "Steve")) {
// run the code
}
```
A common mistake when using the logical OR operator in conditional statements is to try to state the variable whose value you are checking once, and then give a list of values it could be to return true, separated by `||` (OR) operators. For example:
```js
if (x === 5 || 7 || 10 || 20) {
// run my code
}
```
In this case, the condition inside `if ()` will always evaluate to true since 7 (or any other non-zero value) always evaluates to `true`. This condition is actually saying "if x equals 5, or 7 is true β which it always is". This is logically not what we want! To make this work you've got to specify a complete test on either side of each OR operator:
```js
if (x === 5 || x === 7 || x === 10 || x === 20) {
// run my code
}
```
switch statements
-----------------
`if...else` statements do the job of enabling conditional code well, but they are not without their downsides. They are mainly good for cases where you've got a couple of choices, and each one requires a reasonable amount of code to be run, and/or the conditions are complex (for example, multiple logical operators). For cases where you just want to set a variable to a certain choice of value or print out a particular statement depending on a condition, the syntax can be a bit cumbersome, especially if you've got a large number of choices.
In such a case, `switch` statements are your friend β they take a single expression/value as an input, and then look through several choices until they find one that matches that value, executing the corresponding code that goes along with it. Here's some more pseudocode, to give you an idea:
```js
switch (expression) {
case choice1:
// run this code
break;
case choice2:
// run this code instead
break;
// include as many cases as you like
default:
// actually, just run this code
break;
}
```
Here we've got:
1. The keyword `switch`, followed by a set of parentheses.
2. An expression or value inside the parentheses.
3. The keyword `case`, followed by a choice that the expression/value could be, followed by a colon.
4. Some code to run if the choice matches the expression.
5. A `break` statement, followed by a semicolon. If the previous choice matches the expression/value, the browser stops executing the code block here, and moves on to any code that appears below the switch statement.
6. As many other cases (bullets 3β5) as you like.
7. The keyword `default`, followed by exactly the same code pattern as one of the cases (bullets 3β5), except that `default` does not have a choice after it, and you don't need the `break` statement as there is nothing to run after this in the block anyway. This is the default option that runs if none of the choices match.
**Note:** You don't have to include the `default` section β you can safely omit it if there is no chance that the expression could end up equaling an unknown value. If there is a chance of this, however, you need to include it to handle unknown cases.
### A switch example
Let's have a look at a real example β we'll rewrite our weather forecast application to use a switch statement instead:
```html
<label for="weather">Select the weather type today: </label>
<select id="weather">
<option value="">--Make a choice--</option>
<option value="sunny">Sunny</option>
<option value="rainy">Rainy</option>
<option value="snowing">Snowing</option>
<option value="overcast">Overcast</option>
</select>
<p></p>
```
```js
const select = document.querySelector("select");
const para = document.querySelector("p");
select.addEventListener("change", setWeather);
function setWeather() {
const choice = select.value;
switch (choice) {
case "sunny":
para.textContent =
"It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.";
break;
case "rainy":
para.textContent =
"Rain is falling outside; take a rain coat and an umbrella, and don't stay out for too long.";
break;
case "snowing":
para.textContent =
"The snow is coming down β it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.";
break;
case "overcast":
para.textContent =
"It isn't raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.";
break;
default:
para.textContent = "";
}
}
```
**Note:** You can also find this example on GitHub (see it running live on there also.)
Ternary operator
----------------
There is one final bit of syntax we want to introduce you to before we get you to play with some examples. The ternary or conditional operator is a small bit of syntax that tests a condition and returns one value/expression if it is `true`, and another if it is `false` β this can be useful in some situations, and can take up a lot less code than an `if...else` block if you have two choices that are chosen between via a `true`/`false` condition. The pseudocode looks like this:
```js
condition ? run this code : run this code instead
```
So let's look at a simple example:
```js
const greeting = isBirthday
? "Happy birthday Mrs. Smith β we hope you have a great day!"
: "Good morning Mrs. Smith.";
```
Here we have a variable called `isBirthday` β if this is `true`, we give our guest a happy birthday message; if not, we give her the standard daily greeting.
### Ternary operator example
The ternary operator is not just for setting variable values; you can also run functions, or lines of code β anything you like. The following live example shows a simple theme chooser where the styling for the site is applied using a ternary operator.
```html
<label for="theme">Select theme: </label>
<select id="theme">
<option value="white">White</option>
<option value="black">Black</option>
</select>
<h1>This is my website</h1>
```
```js
const select = document.querySelector("select");
const html = document.querySelector("html");
document.body.style.padding = "10px";
function update(bgColor, textColor) {
html.style.backgroundColor = bgColor;
html.style.color = textColor;
}
select.addEventListener("change", () =>
select.value === "black"
? update("black", "white")
: update("white", "black"),
);
```
Here we've got a `<select>` element to choose a theme (black or white), plus a simple h1 to display a website title. We also have a function called `update()`, which takes two colors as parameters (inputs). The website's background color is set to the first provided color, and its text color is set to the second provided color.
Finally, we've also got an onchange event listener that serves to run a function containing a ternary operator. It starts with a test condition β `select.value === 'black'`. If this returns `true`, we run the `update()` function with parameters of black and white, meaning that we end up with a background color of black and a text color of white. If it returns `false`, we run the `update()` function with parameters of white and black, meaning that the site colors are inverted.
**Note:** You can also find this example on GitHub (see it running live on there also.)
Active learning: A simple calendar
----------------------------------
In this example, you are going to help us finish a simple calendar application. In the code you've got:
* A `<select>` element to allow the user to choose between different months.
* An `onchange` event handler to detect when the value selected in the `<select>` menu is changed.
* A function called `createCalendar()` that draws the calendar and displays the correct month in the h1 element.
We need you to write a conditional statement inside the `onchange` handler function, just below the `// ADD CONDITIONAL HERE` comment. It should:
1. Look at the selected month (stored in the `choice` variable. This will be the `<select>` element value after the value changes, so "January" for example.)
2. Set a variable called `days` to be equal to the number of days in the selected month. To do this you'll have to look up the number of days in each month of the year. You can ignore leap years for the purposes of this example.
Hints:
* You are advised to use logical OR to group multiple months together into a single condition; many of them share the same number of days.
* Think about which number of days is the most common, and use that as a default value.
If you make a mistake, you can always reset the example with the "Reset" button. If you get really stuck, press "Show solution" to see a solution.
```
<h2>Live output</h2>
<iframe id="output" width="100%" height="600px"></iframe>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 400px;width: 95%">
const select = document.querySelector('select');
const list = document.querySelector('ul');
const h1 = document.querySelector('h1');
select.addEventListener('change', () => {
const choice = select.value;
// ADD CONDITIONAL HERE
createCalendar(days, choice);
});
function createCalendar(days, choice) {
list.innerHTML = '';
h1.textContent = choice;
for (let i = 1; i <= days; i++) {
const listItem = document.createElement('li');
listItem.textContent = i;
list.appendChild(listItem);
}
}
createCalendar(31, 'January');
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const outputIFrame = document.querySelector("#output");
const textarea = document.getElementById("code");
const initialCode = textarea.value;
let userCode = textarea.value;
const solutionCode = `const select = document.querySelector("select");
const list = document.querySelector("ul");
const h1 = document.querySelector("h1");
select.addEventListener("change", () => {
const choice = select.value;
let days = 31;
if (choice === "February") {
days = 28;
} else if (
choice === "April" ||
choice === "June" ||
choice === "September" ||
choice === "November"
) {
days = 30;
}
createCalendar(days, choice);
});
function createCalendar(days, choice) {
list.innerHTML = "";
h1.textContent = choice;
for (let i = 1; i <= days; i++) {
const listItem = document.createElement("li");
listItem.textContent = i;
list.appendChild(listItem);
}
}
createCalendar(31, "January");`;
function outputDocument(code) {
const outputBody = `
<div class="output" style="height: 500px; overflow: auto">
<label for="month">Select month: </label>
<select id="month">
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
<h1></h1>
<ul></ul>
</div>`;
const outputStyle = `
.output \* {
box-sizing: border-box;
}
.output ul {
padding-left: 0;
}
.output li {
display: block;
float: left;
width: 25%;
border: 2px solid white;
padding: 5px;
height: 40px;
background-color: #4a2db6;
color: white;
}
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}`;
return `
<!doctype html>
<html>
<head>
<style>${outputStyle}</style>
</head>
<body>
${outputBody}
<script>${code}</script>
</body>
</html>`;
}
function update() {
output.setAttribute("srcdoc", outputDocument(textarea.value));
}
update();
textarea.addEventListener("input", update);
reset.addEventListener("click", () => {
textarea.value = initialCode;
userEntry = textarea.value;
solution.value = "Show solution";
update();
});
solution.addEventListener("click", () => {
if (solution.value === "Show solution") {
// remember the state of the user's code
// so we can restore it
userCode = textarea.value;
textarea.value = solutionCode;
solution.value = "Hide solution";
} else {
textarea.value = userCode;
solution.value = "Show solution";
}
update();
});
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
textarea.onkeydown = (e) => {
if (e.keyCode === 9) {
e.preventDefault();
insertAtCaret("\t");
}
if (e.keyCode === 27) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
```
Active learning: More color choices
-----------------------------------
In this example, you are going to take the ternary operator example we saw earlier and convert the ternary operator into a switch statement to allow us to apply more choices to the simple website. Look at the `<select>` β this time you'll see that it has not two theme options, but five. You need to add a switch statement just underneath the `// ADD SWITCH STATEMENT` comment:
* It should accept the `choice` variable as its input expression.
* For each case, the choice should equal one of the possible `<option>` values that can be selected, that is, `white`, `black`, `purple`, `yellow`, or `psychedelic`.
* For each case, the `update()` function should be run, and be passed two color values, the first one for the background color, and the second one for the text color. Remember that color values are strings, so they need to be wrapped in quotes.
If you make a mistake, you can always reset the example with the "Reset" button. If you get really stuck, press "Show solution" to see a solution.
```
<h2>Live output</h2>
<div class="output" style="height: 300px;">
<label for="theme">Select theme: </label>
<select id="theme">
<option value="white">White</option>
<option value="black">Black</option>
<option value="purple">Purple</option>
<option value="yellow">Yellow</option>
<option value="psychedelic">Psychedelic</option>
</select>
<h1>This is my website</h1>
</div>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 450px;width: 95%">
const select = document.querySelector('select');
const html = document.querySelector('.output');
select.addEventListener('change', () => {
const choice = select.value;
// ADD SWITCH STATEMENT
});
function update(bgColor, textColor) {
html.style.backgroundColor = bgColor;
html.style.color = textColor;
}
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener("click", function () {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = "Show solution";
updateCode();
});
solution.addEventListener("click", function () {
if (solution.value === "Show solution") {
textarea.value = solutionEntry;
solution.value = "Hide solution";
} else {
textarea.value = userEntry;
solution.value = "Show solution";
}
updateCode();
});
const jsSolution = `const select = document.querySelector('select');
const html = document.querySelector('.output');
select.addEventListener('change', () => {
const choice = select.value;
switch(choice) {
case 'black':
update('black','white');
break;
case 'white':
update('white','black');
break;
case 'purple':
update('purple','white');
break;
case 'yellow':
update('yellow','purple');
break;
case 'psychedelic':
update('lime','purple');
break;
}
});
function update(bgColor, textColor) {
html.style.backgroundColor = bgColor;
html.style.color = textColor;
}`;
let solutionEntry = jsSolution;
textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
textarea.onkeydown = function (e) {
if (e.keyCode === 9) {
e.preventDefault();
insertAtCaret("\t");
}
if (e.keyCode === 27) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = function () {
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if (solution.value === "Show solution") {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
```
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Conditionals.
Conclusion
----------
And that's all you really need to know about conditional structures in JavaScript right now! If there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help.
See also
--------
* Comparison operators
* Conditional statements in detail
* if...else reference
* Conditional (ternary) operator reference
* Overview: Building blocks
* Next |
Function return values - Learn web development | Function return values
======================
* Previous
* Overview: Building blocks
* Next
There's one last essential concept about functions for us to discuss β return values. Some functions don't return a significant value, but others do. It's important to understand what their values are, how to use them in your code, and how to make functions return useful values. We'll cover all of these below.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of HTML and CSS,
JavaScript first steps,
Functions β reusable blocks of code.
|
| Objective: | To understand function return values, and how to make use of them. |
What are return values?
-----------------------
**Return values** are just what they sound like β the values that a function returns when it completes. You've already met return values several times, although you may not have thought about them explicitly.
Let's return to a familiar example (from a previous article in this series):
```js
const myText = "The weather is cold";
const newString = myText.replace("cold", "warm");
console.log(newString); // Should print "The weather is warm"
// the replace() string function takes a string,
// replaces one substring with another, and returns
// a new string with the replacement made
```
The `replace()` function is invoked on the `myText` string, and is passed two parameters:
* The substring to find ('cold')
* The string to replace it with ('warm')
When the function completes (finishes running), it returns a value, which is a new string with the replacement made. In the code above, the result of this return value is saved in the variable `newString`.
If you look at the `replace()` function MDN reference page, you'll see a section called return value. It is very useful to know and understand what values are returned by functions, so we try to include this information wherever possible.
Some functions don't return any value. (In these cases, our reference pages list the return value as `void` or `undefined`.) For example, in the `displayMessage()` function we built in the previous article, no specific value is returned when the function is invoked. It just makes a box appear somewhere on the screen β that's it!
Generally, a return value is used where the function is an intermediate step in a calculation of some kind. You want to get to a final result, which involves some values that need to be calculated by a function. After the function calculates the value, it can return the result so it can be stored in a variable; and you can use this variable in the next stage of the calculation.
### Using return values in your own functions
To return a value from a custom function, you need to use the return keyword. We saw this in action recently in our random-canvas-circles.html example. Our `draw()` function draws 100 random circles somewhere on an HTML `<canvas>`:
```js
function draw() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
for (let i = 0; i < 100; i++) {
ctx.beginPath();
ctx.fillStyle = "rgb(255 0 0 / 50%)";
ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 \* Math.PI);
ctx.fill();
}
}
```
Inside each loop iteration, three calls are made to the `random()` function, to generate a random value for the current circle's *x-coordinate*, *y-coordinate*, and *radius*, respectively. The `random()` function takes one parameter β a whole number β and returns a whole random number between `0` and that number. It looks like this:
```js
function random(number) {
return Math.floor(Math.random() \* number);
}
```
This could be written as follows:
```js
function random(number) {
const result = Math.floor(Math.random() \* number);
return result;
}
```
But the first version is quicker to write, and more compact.
We are returning the result of the calculation `Math.floor(Math.random() * number)` each time the function is called. This return value appears at the point the function was called, and the code continues.
So when you execute the following:
```js
ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 \* Math.PI);
```
If the three `random()` calls return the values `500`, `200`, and `35`, respectively, the line would actually be run as if it were this:
```js
ctx.arc(500, 200, 35, 0, 2 \* Math.PI);
```
The function calls on the line are run first, and their return values are substituted for the function calls, before the line itself is then executed.
Active learning: our own return value function
----------------------------------------------
Let's have a go at writing our own functions featuring return values.
1. Make a local copy of the function-library.html file from GitHub. This is a simple HTML page containing a text `<input>` field and a paragraph. There's also a `<script>` element, in which we have stored a reference to both HTML elements in two variables. This page will allow you to enter a number into the text box, and display different numbers related to it below.
2. Add some useful functions to this `<script>` element below the two existing lines:
```js
function squared(num) {
return num \* num;
}
function cubed(num) {
return num \* num \* num;
}
function factorial(num) {
if (num < 0) return undefined;
if (num === 0) return 1;
let x = num - 1;
while (x > 1) {
num \*= x;
x--;
}
return num;
}
```
The `squared()` and `cubed()` functions are fairly obvious β they return the square or cube of the number that was given as a parameter. The `factorial()` function returns the factorial of the given number.
3. Include a way to print out information about the number entered into the text input by adding the following event handler below the existing functions:
```js
input.addEventListener("change", () => {
const num = parseFloat(input.value);
if (isNaN(num)) {
para.textContent = "You need to enter a number!";
} else {
para.textContent = `${num} squared is ${squared(num)}. `;
para.textContent += `${num} cubed is ${cubed(num)}. `;
para.textContent += `${num} factorial is ${factorial(num)}. `;
}
});
```
4. Save your code, load it in a browser, and try it out.
Here are some explanations for the `addEventListener` function in step 3 above:
* By adding a listener to the `change` event, this function runs whenever the `change` event fires on the text input β that is when a new value is entered into the text `input`, and submitted (e.g., enter a value, then un-focus the input by pressing `Tab` or `Return`). When this anonymous function runs, the value in the `input` is stored in the `num` constant.
* The if statement prints an error message if the entered value is not a number. The condition checks if the expression `isNaN(num)` returns `true`. The `isNaN()` function tests whether the `num` value is not a number β if so, it returns `true`, and if not, it returns `false`.
* If the condition returns `false`, the `num` value is a number and the function prints out a sentence inside the paragraph element that states the square, cube, and factorial values of the number. The sentence calls the `squared()`, `cubed()`, and `factorial()` functions to calculate the required values.
**Note:** If you have trouble getting the example to work, check your code against the finished version on GitHub (see it running live also), or ask us for help.
Now it's your turn!
-------------------
At this point, we'd like you to have a go at writing out a couple of functions of your own and adding them to the library. How about the square or cube root of the number? Or the circumference of a circle with a given radius?
Some extra function-related tips:
* Look at another example of writing *error handling* into functions. It is generally a good idea to check that any necessary parameters are validated, and that any optional parameters have some kind of default value provided. This way, your program will be less likely to throw errors.
* Think about the idea of creating a *function library*. As you go further into your programming career, you'll start doing the same kinds of things over and over again. It is a good idea to create your own library of utility functions to do these sorts of things. You can copy them over to new code, or even just apply them to HTML pages wherever you need them.
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Functions.
Conclusion
----------
So there we have it β functions are fun, very useful, and although there's a lot to talk about in regards to their syntax and functionality, they are fairly understandable.
If there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help.
See also
--------
* Functions in-depth β a detailed guide covering more advanced functions-related information.
* Callback functions in JavaScript β a common JavaScript pattern is to pass a function into another function *as an argument*. It is then called inside the first function. This is a little beyond the scope of this course, but worth studying before too long.
* Previous
* Overview: Building blocks
* Next |
Test your skills: Events - Learn web development | Test your skills: Events
========================
The aim of this skill test is to assess whether you've understood our Introduction to events article.
**Note:** You can try solutions by downloading the code and putting it in an online editor such as CodePen, JSFiddle, or Glitch.
If there is an error, it will be logged in the results panel on the page or into the browser's JavaScript console to help you.
If you get stuck, you can reach out to us in one of our communication channels.
DOM manipulation: considered useful
-----------------------------------
Some of the questions below require you to write some DOM manipulation code to complete them β such as creating new HTML elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page β all via JavaScript.
We haven't explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into what DOM APIs you need to successfully answer the questions. A good starting place is our Manipulating documents tutorial.
Events 1
--------
In our first events-related task, you need to create a simple event handler that causes the text inside the button (`btn`) to change when it is clicked on, and change back when it is clicked again.
The HTML should not be changed; just the JavaScript.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Events 2
--------
Now we'll look at keyboard events. To pass this assessment you need to build an event handler that moves the circle around the provided canvas when the WASD keys are pressed on the keyboard. The circle is drawn with the function `drawCircle()`, which takes the following parameters as inputs:
* `x` β the x coordinate of the circle.
* `y` β the y coordinate of the circle.
* `size` β the radius of the circle.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Events 3
--------
In the next events-related task, you need to set an event listener on the `<button>`s' parent element (`<div class="button-bar"> β¦ </div>`), which when invoked by clicking any of the buttons will set the background of the `button-bar` to the color contained in the button's `data-color` attribute.
We want you to solve this without looping through all the buttons and giving each one their own event listener.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
Image gallery - Learn web development | Image gallery
=============
* Previous
* Overview: Building blocks
Now that we've looked at the fundamental building blocks of JavaScript, we'll test your knowledge of loops, functions, conditionals and events by getting you to build a fairly common item you'll see on a lot of websites β a JavaScript-powered image gallery.
| | |
| --- | --- |
| Prerequisites: |
Before attempting this assessment you should have already worked through
all the articles in this module.
|
| Objective: |
To test comprehension of JavaScript loops, functions, conditionals, and
events.
|
Starting point
--------------
To get this assessment started, you should go and grab the ZIP file for the example, unzip it somewhere on your computer, and do the exercise locally to begin with.
Alternatively, you could use an online editor such as CodePen, JSFiddle, or Glitch.
**Note:** If you get stuck, you can reach out to us in one of our communication channels.
Project brief
-------------
You have been provided with some HTML, CSS and image assets and a few lines of JavaScript code; you need to write the necessary JavaScript to turn this into a working program. The HTML body looks like this:
```html
<h1>Image gallery example</h1>
<div class="full-img">
<img
class="displayed-img"
src="images/pic1.jpg"
alt="Closeup of a blue human eye" />
<div class="overlay"></div>
<button class="dark">Darken</button>
</div>
<div class="thumb-bar"></div>
```
The example looks like this:
![An image gallery with a large image on top and five thumbnails below](/en-US/docs/Learn/JavaScript/Building_blocks/Image_gallery/gallery.png)
The most interesting parts of the example's CSS file:
* It absolutely positions the three elements inside the `full-img <div>` β the `<img>` in which the full-sized image is displayed, an empty `<div>` that is sized to be the same size as the `<img>` and put right over the top of it (this is used to apply a darkening effect to the image via a semi-transparent background color), and a `<button>` that is used to control the darkening effect.
* It sets the width of any images inside the `thumb-bar <div>` (so-called "thumbnail" images) to 20%, and floats them to the left so they sit next to one another on a line.
Your JavaScript needs to:
* Declare a `const` array listing the filenames of each image, such as `'pic1.jpg'`.
* Declare a `const` object listing the alternative text for each image.
* Loop through the array of filenames, and for each one, insert an `<img>` element inside the `thumb-bar <div>` that embeds that image in the page along with its alternative text.
* Add a click event listener to each `<img>` inside the `thumb-bar <div>` so that, when they are clicked, the corresponding image and alternative text are displayed in the `displayed-img <img>` element.
* Add a click event listener to the `<button>` so that when it is clicked, a darken effect is applied to the full-size image. When it is clicked again, the darken effect is removed again.
To give you more of an idea, have a look at the finished example (no peeking at the source code!)
Steps to complete
-----------------
The following sections describe what you need to do.
Declare an array of image filenames
-----------------------------------
You need to create an array listing the filenames of all the images to include in the gallery. The array should be declared as a constant.
### Looping through the images
We've already provided you with lines that store a reference to the `thumb-bar <div>` inside a constant called `thumbBar`, create a new `<img>` element, set its `src` and `alt` attributes to a placeholder value `xxx`, and append this new `<img>` element inside `thumbBar`.
You need to:
1. Put the section of code below the "Looping through images" comment inside a loop that loops through all the filenames in the array.
2. In each loop iteration, replace the `xxx` placeholder values with a string that will equal the path to the image and alt attributes in each case. Set the value of the `src` and `alt` attributes to these values in each case. Remember that the image is inside the images directory, and its name is `pic1.jpg`, `pic2.jpg`, etc.
### Adding a click event listener to each thumbnail image
In each loop iteration, you need to add a click event listener to the current `newImage` β this listener should find the value of the `src` attribute of the current image. Set the `src` attribute value of the `displayed-img <img>` to the `src` value passed in as a parameter. Then do the same for the `alt` attribute.
Alternatively, you can add one event listener to the thumb bar.
### Writing a handler that runs the darken/lighten button
That just leaves our darken/lighten `<button>` β we've already provided a line that stores a reference to the `<button>` in a constant called `btn`. You need to add a click event listener that:
1. Checks the current class name set on the `<button>` β you can again achieve this by using `getAttribute()`.
2. If the class name is `"dark"`, changes the `<button>` class to `"light"` (using `setAttribute()`), its text content to "Lighten", and the `background-color` of the overlay `<div>` to `"rgb(0 0 0 / 50%)"`.
3. If the class name is not `"dark"`, changes the `<button>` class to `"dark"`, its text content back to "Darken", and the `background-color` of the overlay `<div>` to `"rgb(0 0 0 / 0%)"`.
The following lines provide a basis for achieving the changes stipulated in points 2 and 3 above.
```js
btn.setAttribute("class", xxx);
btn.textContent = xxx;
overlay.style.backgroundColor = xxx;
```
Hints and tips
--------------
* You don't need to edit the HTML or CSS in any way.
* Previous
* Overview: Building blocks |
Looping code - Learn web development | Looping code
============
* Previous
* Overview: Building blocks
* Next
Programming languages are very useful for rapidly completing repetitive tasks, from multiple basic calculations to just about any other situation where you've got a lot of similar items of work to complete. Here we'll look at the loop structures available in JavaScript that handle such needs.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of HTML, CSS, and
JavaScript first steps.
|
| Objective: | To understand how to use loops in JavaScript. |
Why are loops useful?
---------------------
Loops are all about doing the same thing over and over again. Often, the code will be slightly different each time round the loop, or the same code will run but with different variables.
### Looping code example
Suppose we wanted to draw 100 random circles on a `<canvas>` element (press the *Update* button to run the example again and again to see different random sets):
```
<button>Update</button> <canvas></canvas>
```
```
html {
width: 100%;
height: inherit;
background: #ddd;
}
canvas {
display: block;
}
body {
margin: 0;
}
button {
position: absolute;
top: 5px;
left: 5px;
}
```
Here's the JavaScript code that implements this example:
```js
const btn = document.querySelector("button");
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
document.addEventListener("DOMContentLoaded", () => {
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
});
function random(number) {
return Math.floor(Math.random() \* number);
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < 100; i++) {
ctx.beginPath();
ctx.fillStyle = "rgb(255 0 0 / 50%)";
ctx.arc(
random(canvas.width),
random(canvas.height),
random(50),
0,
2 \* Math.PI,
);
ctx.fill();
}
}
btn.addEventListener("click", draw);
```
### With and without a loop
You don't have to understand all the code for now, but let's look at the part of the code that actually draws the 100 circles:
```js
for (let i = 0; i < 100; i++) {
ctx.beginPath();
ctx.fillStyle = "rgb(255 0 0 / 50%)";
ctx.arc(
random(canvas.width),
random(canvas.height),
random(50),
0,
2 \* Math.PI,
);
ctx.fill();
}
```
* `random(x)`, defined earlier in the code, returns a whole number between `0` and `x-1`.
You should get the basic idea β we are using a loop to run 100 iterations of this code, each one of which draws a circle in a random position on the page.
The amount of code needed would be the same whether we were drawing 100 circles, 1000, or 10,000.
Only one number has to change.
If we weren't using a loop here, we'd have to repeat the following code for every circle we wanted to draw:
```js
ctx.beginPath();
ctx.fillStyle = "rgb(255 0 0 / 50%)";
ctx.arc(
random(canvas.width),
random(canvas.height),
random(50),
0,
2 \* Math.PI,
);
ctx.fill();
```
This would get very boring and difficult to maintain.
Looping through a collection
----------------------------
Most of the time when you use a loop, you will have a collection of items and want to do something with every item.
One type of collection is the `Array`, which we met in the Arrays chapter of this course.
But there are other collections in JavaScript as well, including `Set` and `Map`.
### The for...of loop
The basic tool for looping through a collection is the `for...of` loop:
```js
const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];
for (const cat of cats) {
console.log(cat);
}
```
In this example, `for (const cat of cats)` says:
1. Given the collection `cats`, get the first item in the collection.
2. Assign it to the variable `cat` and then run the code between the curly braces `{}`.
3. Get the next item, and repeat (2) until you've reached the end of the collection.
### map() and filter()
JavaScript also has more specialized loops for collections, and we'll mention two of them here.
You can use `map()` to do something to each item in a collection and create a new collection containing the changed items:
```js
function toUpper(string) {
return string.toUpperCase();
}
const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];
const upperCats = cats.map(toUpper);
console.log(upperCats);
// [ "LEOPARD", "SERVAL", "JAGUAR", "TIGER", "CARACAL", "LION" ]
```
Here we pass a function into `cats.map()`, and `map()` calls the function once for each item in the array, passing in the item. It then adds the return value from each function call to a new array, and finally returns the new array. In this case the function we provide converts the item to uppercase, so the resulting array contains all our cats in uppercase:
```js
[ "LEOPARD", "SERVAL", "JAGUAR", "TIGER", "CARACAL", "LION" ]
```
You can use `filter()` to test each item in a collection, and create a new collection containing only items that match:
```js
function lCat(cat) {
return cat.startsWith("L");
}
const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];
const filtered = cats.filter(lCat);
console.log(filtered);
// [ "Leopard", "Lion" ]
```
This looks a lot like `map()`, except the function we pass in returns a boolean: if it returns `true`, then the item is included in the new array.
Our function tests that the item starts with the letter "L", so the result is an array containing only cats whose names start with "L":
```js
[ "Leopard", "Lion" ]
```
Note that `map()` and `filter()` are both often used with *function expressions*, which we will learn about in the Functions module.
Using function expressions we could rewrite the example above to be much more compact:
```js
const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];
const filtered = cats.filter((cat) => cat.startsWith("L"));
console.log(filtered);
// [ "Leopard", "Lion" ]
```
The standard for loop
---------------------
In the "drawing circles" example above, you don't have a collection of items to loop through: you really just want to run the same code 100 times.
In a case like that, you should use the `for` loop.
This has the following syntax:
```js
for (initializer; condition; final-expression) {
// code to run
}
```
Here we have:
1. The keyword `for`, followed by some parentheses.
2. Inside the parentheses we have three items, separated by semicolons:
1. An **initializer** β this is usually a variable set to a number, which is incremented to count the number of times the loop has run.
It is also sometimes referred to as a **counter variable**.
2. A **condition** β this defines when the loop should stop looping.
This is generally an expression featuring a comparison operator, a test to see if the exit condition has been met.
3. A **final-expression** β this is always evaluated (or run) each time the loop has gone through a full iteration.
It usually serves to increment (or in some cases decrement) the counter variable, to bring it closer to the point where the condition is no longer `true`.
3. Some curly braces that contain a block of code β this code will be run each time the loop iterates.
### Calculating squares
Let's look at a real example so we can visualize what these do more clearly.
```
<button id="calculate">Calculate</button>
<button id="clear">Clear</button>
<pre id="results"></pre>
```
```js
const results = document.querySelector("#results");
function calculate() {
for (let i = 1; i < 10; i++) {
const newResult = `${i} x ${i} = ${i \* i}`;
results.textContent += `${newResult}\n`;
}
results.textContent += "\nFinished!";
}
const calculateBtn = document.querySelector("#calculate");
const clearBtn = document.querySelector("#clear");
calculateBtn.addEventListener("click", calculate);
clearBtn.addEventListener("click", () => (results.textContent = ""));
```
This gives us the following output:
This code calculates squares for the numbers from 1 to 9, and writes out the result. The core of the code is the `for` loop that performs the calculation.
Let's break down the `for (let i = 1; i < 10; i++)` line into its three pieces:
1. `let i = 1`: the counter variable, `i`, starts at `1`. Note that we have to use `let` for the counter, because we're reassigning it each time we go round the loop.
2. `i < 10`: keep going round the loop for as long as `i` is smaller than `10`.
3. `i++`: add one to `i` each time round the loop.
Inside the loop, we calculate the square of the current value of `i`, that is: `i * i`. We create a string expressing the calculation we made and the result, and add this string to the output text. We also add `\n`, so the next string we add will begin on a new line. So:
1. During the first run, `i = 1`, so we will add `1 x 1 = 1`.
2. During the second run, `i = 2`, so we will add `2 x 2 = 4`.
3. And so onβ¦
4. When `i` becomes equal to `10` we will stop running the loop and move straight to the next bit of code below the loop, printing out the `Finished!` message on a new line.
### Looping through collections with a for loop
You can use a `for` loop to iterate through a collection, instead of a `for...of` loop.
Let's look again at our `for...of` example above:
```js
const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];
for (const cat of cats) {
console.log(cat);
}
```
We could rewrite that code like this:
```js
const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];
for (let i = 0; i < cats.length; i++) {
console.log(cats[i]);
}
```
In this loop we're starting `i` at `0`, and stopping when `i` reaches the length of the array.
Then inside the loop, we're using `i` to access each item in the array in turn.
This works just fine, and in early versions of JavaScript, `for...of` didn't exist, so this was the standard way to iterate through an array.
However, it offers more chances to introduce bugs into your code. For example:
* you might start `i` at `1`, forgetting that the first array index is zero, not 1.
* you might stop at `i <= cats.length`, forgetting that the last array index is at `length - 1`.
For reasons like this, it's usually best to use `for...of` if you can.
Sometimes you still need to use a `for` loop to iterate through an array.
For example, in the code below we want to log a message listing our cats:
```js
const cats = ["Pete", "Biggles", "Jasmine"];
let myFavoriteCats = "My cats are called ";
for (const cat of cats) {
myFavoriteCats += `${cat}, `;
}
console.log(myFavoriteCats); // "My cats are called Pete, Biggles, Jasmine, "
```
The final output sentence isn't very well-formed:
```
My cats are called Pete, Biggles, Jasmine,
```
We'd prefer it to handle the last cat differently, like this:
```
My cats are called Pete, Biggles, and Jasmine.
```
But to do this we need to know when we are on the final loop iteration, and to do that we can use a `for` loop and examine the value of `i`:
```js
const cats = ["Pete", "Biggles", "Jasmine"];
let myFavoriteCats = "My cats are called ";
for (let i = 0; i < cats.length; i++) {
if (i === cats.length - 1) {
// We are at the end of the array
myFavoriteCats += `and ${cats[i]}.`;
} else {
myFavoriteCats += `${cats[i]}, `;
}
}
console.log(myFavoriteCats); // "My cats are called Pete, Biggles, and Jasmine."
```
Exiting loops with break
------------------------
If you want to exit a loop before all the iterations have been completed, you can use the break statement.
We already met this in the previous article when we looked at switch statements β when a case is met in a switch statement that matches the input expression, the `break` statement immediately exits the switch statement and moves on to the code after it.
It's the same with loops β a `break` statement will immediately exit the loop and make the browser move on to any code that follows it.
Say we wanted to search through an array of contacts and telephone numbers and return just the number we wanted to find?
First, some simple HTML β a text `<input>` allowing us to enter a name to search for, a `<button>` element to submit a search, and a `<p>` element to display the results in:
```html
<label for="search">Search by contact name: </label>
<input id="search" type="text" />
<button>Search</button>
<p></p>
```
Now on to the JavaScript:
```js
const contacts = [
"Chris:2232322",
"Sarah:3453456",
"Bill:7654322",
"Mary:9998769",
"Dianne:9384975",
];
const para = document.querySelector("p");
const input = document.querySelector("input");
const btn = document.querySelector("button");
btn.addEventListener("click", () => {
const searchName = input.value.toLowerCase();
input.value = "";
input.focus();
para.textContent = "";
for (const contact of contacts) {
const splitContact = contact.split(":");
if (splitContact[0].toLowerCase() === searchName) {
para.textContent = `${splitContact[0]}'s number is ${splitContact[1]}.`;
break;
}
}
if (para.textContent === "") {
para.textContent = "Contact not found.";
}
});
```
1. First of all, we have some variable definitions β we have an array of contact information, with each item being a string containing a name and phone number separated by a colon.
2. Next, we attach an event listener to the button (`btn`) so that when it is pressed some code is run to perform the search and return the results.
3. We store the value entered into the text input in a variable called `searchName`, before then emptying the text input and focusing it again, ready for the next search.
Note that we also run the `toLowerCase()` method on the string, so that searches will be case-insensitive.
4. Now on to the interesting part, the `for...of` loop:
1. Inside the loop, we first split the current contact at the colon character, and store the resulting two values in an array called `splitContact`.
2. We then use a conditional statement to test whether `splitContact[0]` (the contact's name, again lower-cased with `toLowerCase()`) is equal to the inputted `searchName`.
If it is, we enter a string into the paragraph to report what the contact's number is, and use `break` to end the loop.
5. After the loop, we check whether we set a contact, and if not we set the paragraph text to "Contact not found.".
**Note:** You can view the full source code on GitHub too (also see it running live).
Skipping iterations with continue
---------------------------------
The continue statement works similarly to `break`, but instead of breaking out of the loop entirely, it skips to the next iteration of the loop.
Let's look at another example that takes a number as an input, and returns only the numbers that are squares of integers (whole numbers).
The HTML is basically the same as the last example β a simple numeric input, and a paragraph for output.
```html
<label for="number">Enter number: </label>
<input id="number" type="number" />
<button>Generate integer squares</button>
<p>Output:</p>
```
The JavaScript is mostly the same too, although the loop itself is a bit different:
```js
const para = document.querySelector("p");
const input = document.querySelector("input");
const btn = document.querySelector("button");
btn.addEventListener("click", () => {
para.textContent = "Output: ";
const num = input.value;
input.value = "";
input.focus();
for (let i = 1; i <= num; i++) {
let sqRoot = Math.sqrt(i);
if (Math.floor(sqRoot) !== sqRoot) {
continue;
}
para.textContent += `${i} `;
}
});
```
Here's the output:
1. In this case, the input should be a number (`num`). The `for` loop is given a counter starting at 1 (as we are not interested in 0 in this case), an exit condition that says the loop will stop when the counter becomes bigger than the input `num`, and an iterator that adds 1 to the counter each time.
2. Inside the loop, we find the square root of each number using Math.sqrt(i), then check whether the square root is an integer by testing whether it is the same as itself when it has been rounded down to the nearest integer (this is what Math.floor() does to the number it is passed).
3. If the square root and the rounded down square root do not equal one another (`!==`), it means that the square root is not an integer, so we are not interested in it. In such a case, we use the `continue` statement to skip on to the next loop iteration without recording the number anywhere.
4. If the square root is an integer, we skip past the `if` block entirely, so the `continue` statement is not executed; instead, we concatenate the current `i` value plus a space at the end of the paragraph content.
**Note:** You can view the full source code on GitHub too (also see it running live).
while and do...while
--------------------
`for` is not the only type of loop available in JavaScript. There are actually many others and, while you don't need to understand all of these now, it is worth having a look at the structure of a couple of others so that you can recognize the same features at work in a slightly different way.
First, let's have a look at the while loop. This loop's syntax looks like so:
```js
initializer
while (condition) {
// code to run
final-expression
}
```
This works in a very similar way to the `for` loop, except that the initializer variable is set before the loop, and the final-expression is included inside the loop after the code to run, rather than these two items being included inside the parentheses.
The condition is included inside the parentheses, which are preceded by the `while` keyword rather than `for`.
The same three items are still present, and they are still defined in the same order as they are in the for loop.
This is because you must have an initializer defined before you can check whether or not the condition is true.
The final-expression is then run after the code inside the loop has run (an iteration has been completed), which will only happen if the condition is still true.
Let's have a look again at our cats list example, but rewritten to use a while loop:
```js
const cats = ["Pete", "Biggles", "Jasmine"];
let myFavoriteCats = "My cats are called ";
let i = 0;
while (i < cats.length) {
if (i === cats.length - 1) {
myFavoriteCats += `and ${cats[i]}.`;
} else {
myFavoriteCats += `${cats[i]}, `;
}
i++;
}
console.log(myFavoriteCats); // "My cats are called Pete, Biggles, and Jasmine."
```
**Note:** This still works just the same as expected β have a look at it running live on GitHub (also view the full source code).
The do...while loop is very similar, but provides a variation on the while structure:
```js
initializer
do {
// code to run
final-expression
} while (condition)
```
In this case, the initializer again comes first, before the loop starts. The keyword directly precedes the curly braces containing the code to run and the final expression.
The main difference between a `do...while` loop and a `while` loop is that *the code inside a `do...while` loop is always executed at least once*. That's because the condition comes after the code inside the loop. So we always run that code, then check to see if we need to run it again. In `while` and `for` loops, the check comes first, so the code might never be executed.
Let's rewrite our cat listing example again to use a `do...while` loop:
```js
const cats = ["Pete", "Biggles", "Jasmine"];
let myFavoriteCats = "My cats are called ";
let i = 0;
do {
if (i === cats.length - 1) {
myFavoriteCats += `and ${cats[i]}.`;
} else {
myFavoriteCats += `${cats[i]}, `;
}
i++;
} while (i < cats.length);
console.log(myFavoriteCats); // "My cats are called Pete, Biggles, and Jasmine."
```
**Note:** Again, this works just the same as expected β have a look at it running live on GitHub (also view the full source code).
**Warning:** With while and do...while β as with all loops β you must make sure that the initializer is incremented or, depending on the case, decremented, so the condition eventually becomes false.
If not, the loop will go on forever, and either the browser will force it to stop, or it will crash. This is called an **infinite loop**.
Active learning: Launch countdown
---------------------------------
In this exercise, we want you to print out a simple launch countdown to the output box, from 10 down to Blastoff.
Specifically, we want you to:
* Loop from 10 down to 0. We've provided you with an initializer β `let i = 10;`.
* For each iteration, create a new paragraph and append it to the output `<div>`, which we've selected using `const output = document.querySelector('.output');`.
In comments, we've provided you with three code lines that need to be used somewhere inside the loop:
+ `const para = document.createElement('p');` β creates a new paragraph.
+ `output.appendChild(para);` β appends the paragraph to the output `<div>`.
+ `para.textContent =` β makes the text inside the paragraph equal to whatever you put on the right-hand side, after the equals sign.
* Different iteration numbers require different text to be put in the paragraph for that iteration (you'll need a conditional statement and multiple `para.textContent =` lines):
+ If the number is 10, print "Countdown 10" to the paragraph.
+ If the number is 0, print "Blast off!" to the paragraph.
+ For any other number, print just the number to the paragraph.
* Remember to include an iterator! However, in this example we are counting down after each iteration, not up, so you **don't** want `i++` β how do you iterate downwards?
**Note:** If you start typing the loop (for example (while(i>=0)), the browser might get stuck because you have not yet entered the end condition. So be careful with this. You can start writing your code in a comment to deal with this issue and remove the comment after you finish.
If you make a mistake, you can always reset the example with the "Reset" button.
If you get really stuck, press "Show solution" to see a solution.
```
<h2>Live output</h2>
<div class="output" style="height: 410px;overflow: auto;"></div>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 300px;width: 95%">
let output = document.querySelector('.output');
output.innerHTML = '';
// let i = 10;
// const para = document.createElement('p');
// para.textContent = ;
// output.appendChild(para);
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```css
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener("click", function () {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = "Show solution";
updateCode();
});
solution.addEventListener("click", function () {
if (solution.value === "Show solution") {
textarea.value = solutionEntry;
solution.value = "Hide solution";
} else {
textarea.value = userEntry;
solution.value = "Show solution";
}
updateCode();
});
let jsSolution = `const output = document.querySelector('.output');
output.innerHTML = '';
let i = 10;
while (i >= 0) {
const para = document.createElement('p');
if (i === 10) {
para.textContent = \`Countdown \${i}\`;
} else if (i === 0) {
para.textContent = 'Blast off!';
} else {
para.textContent = i;
}
output.appendChild(para);
i--;
}`;
let solutionEntry = jsSolution;
textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
textarea.onkeydown = function (e) {
if (e.keyCode === 9) {
e.preventDefault();
insertAtCaret("\t");
}
if (e.keyCode === 27) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = () => {
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if (solution.value === "Show solution") {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
```
Active learning: Filling in a guest list
----------------------------------------
In this exercise, we want you to take a list of names stored in an array and put them into a guest list. But it's not quite that easy β we don't want to let Phil and Lola in because they are greedy and rude, and always eat all the food! We have two lists, one for guests to admit, and one for guests to refuse.
Specifically, we want you to:
* Write a loop that will iterate through the `people` array.
* During each loop iteration, check if the current array item is equal to "Phil" or "Lola" using a conditional statement:
+ If it is, concatenate the array item to the end of the `refused` paragraph's `textContent`, followed by a comma and a space.
+ If it isn't, concatenate the array item to the end of the `admitted` paragraph's `textContent`, followed by a comma and a space.
We've already provided you with:
* `refused.textContent +=` β the beginnings of a line that will concatenate something at the end of `refused.textContent`.
* `admitted.textContent +=` β the beginnings of a line that will concatenate something at the end of `admitted.textContent`.
Extra bonus question β after completing the above tasks successfully, you will be left with two lists of names, separated by commas, but they will be untidy β there will be a comma at the end of each one.
Can you work out how to write lines that slice the last comma off in each case, and add a full stop to the end?
Have a look at the Useful string methods article for help.
If you make a mistake, you can always reset the example with the "Reset" button.
If you get really stuck, press "Show solution" to see a solution.
```
<h2>Live output</h2>
<div class="output" style="height: 100px;overflow: auto;">
<p class="admitted">Admit:</p>
<p class="refused">Refuse:</p>
</div>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 400px;width: 95%">
const people = ['Chris', 'Anne', 'Colin', 'Terri', 'Phil', 'Lola', 'Sam', 'Kay', 'Bruce'];
const admitted = document.querySelector('.admitted');
const refused = document.querySelector('.refused');
admitted.textContent = 'Admit: ';
refused.textContent = 'Refuse: ';
// loop starts here
// refused.textContent += ;
// admitted.textContent += ;
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener("click", function () {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = "Show solution";
updateCode();
});
solution.addEventListener("click", function () {
if (solution.value === "Show solution") {
textarea.value = solutionEntry;
solution.value = "Hide solution";
} else {
textarea.value = userEntry;
solution.value = "Show solution";
}
updateCode();
});
const jsSolution = `
const people = ['Chris', 'Anne', 'Colin', 'Terri', 'Phil', 'Lola', 'Sam', 'Kay', 'Bruce'];
const admitted = document.querySelector('.admitted');
const refused = document.querySelector('.refused');
admitted.textContent = 'Admit: ';
refused.textContent = 'Refuse: ';
for (const person of people) {
if (person === 'Phil' || person === 'Lola') {
refused.textContent += \`\${person}, \`;
} else {
admitted.textContent += \`\${person}, \`;
}
}
refused.textContent = refused.textContent.slice(0,refused.textContent.length-2) + '.';
admitted.textContent = admitted.textContent.slice(0,admitted.textContent.length-2) + '.';`;
let solutionEntry = jsSolution;
textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
textarea.onkeydown = function (e) {
if (e.keyCode === 9) {
e.preventDefault();
insertAtCaret("\t");
}
if (e.keyCode === 27) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = () => {
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if (solution.value === "Show solution") {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
```
Which loop type should you use?
-------------------------------
If you're iterating through an array or some other object that supports it, and don't need access to the index position of each item, then `for...of` is the best choice. It's easier to read and there's less to go wrong.
For other uses, `for`, `while`, and `do...while` loops are largely interchangeable.
They can all be used to solve the same problems, and which one you use will largely depend on your personal preference β which one you find easiest to remember or most intuitive.
We would recommend `for`, at least to begin with, as it is probably the easiest for remembering everything β the initializer, condition, and final-expression all have to go neatly into the parentheses, so it is easy to see where they are and check that you aren't missing them.
Let's have a look at them all again.
First `for...of`:
```js
for (const item of array) {
// code to run
}
```
`for`:
```js
for (initializer; condition; final-expression) {
// code to run
}
```
`while`:
```js
initializer
while (condition) {
// code to run
final-expression
}
```
and finally `do...while`:
```js
initializer
do {
// code to run
final-expression
} while (condition)
```
**Note:** There are other loop types/features too, which are useful in advanced/specialized situations and beyond the scope of this article. If you want to go further with your loop learning, read our advanced Loops and iteration guide.
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Loops.
Conclusion
----------
This article has revealed to you the basic concepts behind, and different options available when looping code in JavaScript.
You should now be clear on why loops are a good mechanism for dealing with repetitive code and raring to use them in your own examples!
If there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help.
See also
--------
* Loops and iteration in detail
* for...of reference
* for statement reference
* while and do...while references
* break and continue references
* Previous
* Overview: Building blocks
* Next |
Build your own function - Learn web development | Build your own function
=======================
* Previous
* Overview: Building blocks
* Next
With most of the essential theory dealt with in the previous article, this article provides practical experience. Here you will get some practice building your own, custom function. Along the way, we'll also explain some useful details of dealing with functions.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of HTML, CSS, and
JavaScript first steps. Also, Functions β reusable blocks of code.
|
| Objective: |
To provide some practice in building a custom function, and explain a
few more useful associated details.
|
Active learning: Let's build a function
---------------------------------------
The custom function we are going to build will be called `displayMessage()`. It will display a custom message box on a web page and will act as a customized replacement for a browser's built-in alert() function. We've seen this before, but let's just refresh our memories. Type the following in your browser's JavaScript console, on any page you like:
```js
alert("This is a message");
```
The `alert` function takes a single argument β the string that is displayed in the alert box. Try varying the string to change the message.
The `alert` function is limited: you can alter the message, but you can't easily vary anything else, such as the color, icon, or anything else. We'll build one that will prove to be more fun.
**Note:** This example should work in all modern browsers fine, but the styling might look a bit funny in slightly older browsers. We'd recommend you do this exercise in a modern browser like Firefox, Opera, or Chrome.
The basic function
------------------
To begin with, let's put together a basic function.
**Note:** For function naming conventions, you should follow the same rules as variable naming conventions. This is fine, as you can tell them apart β function names appear with parentheses after them, and variables don't.
1. Start by accessing the function-start.html file and making a local copy. You'll see that the HTML is simple β the body contains just a single button. We've also provided some basic CSS to style the custom message box, and an empty `<script>` element to put our JavaScript in.
2. Next, add the following inside the `<script>` element:
```js
function displayMessage() {
...
}
```
We start off with the keyword `function`, which means we are defining a function. This is followed by the name we want to give to our function, a set of parentheses, and a set of curly braces. Any parameters we want to give to our function go inside the parentheses, and the code that runs when we call the function goes inside the curly braces.
3. Finally, add the following code inside the curly braces:
```js
const body = document.body;
const panel = document.createElement("div");
panel.setAttribute("class", "msgBox");
body.appendChild(panel);
const msg = document.createElement("p");
msg.textContent = "This is a message box";
panel.appendChild(msg);
const closeBtn = document.createElement("button");
closeBtn.textContent = "x";
panel.appendChild(closeBtn);
closeBtn.addEventListener("click", () =>
panel.parentNode.removeChild(panel),
);
```
This is quite a lot of code to go through, so we'll walk you through it bit by bit.
The first line selects the `<body>` element by using the DOM API to get the `body` property of the global `document` object, and assigning that to a constant called `body`, so we can do things to it later on:
```js
const body = document.body;
```
The next section uses a DOM API function called `document.createElement()` to create a `<div>` element and store a reference to it in a constant called `panel`. This element will be the outer container of our message box.
We then use yet another DOM API function called `Element.setAttribute()` to set a `class` attribute on our panel with a value of `msgBox`. This is to make it easier to style the element β if you look at the CSS on the page, you'll see that we are using a `.msgBox` class selector to style the message box and its contents.
Finally, we call a DOM function called `Node.appendChild()` on the `body` constant we stored earlier, which nests one element inside the other as a child of it. We specify the panel `<div>` as the child we want to append inside the `<body>` element. We need to do this as the element we created won't just appear on the page on its own β we need to specify where to put it.
```js
const panel = document.createElement("div");
panel.setAttribute("class", "msgBox");
body.appendChild(panel);
```
The next two sections make use of the same `createElement()` and `appendChild()` functions we've already seen to create two new elements β a `<p>` and a `<button>` β and insert them in the page as children of the panel `<div>`. We use their `Node.textContent` property β which represents the text content of an element β to insert a message inside the paragraph, and an "x" inside the button. This button will be what needs to be clicked/activated when the user wants to close the message box.
```js
const msg = document.createElement("p");
msg.textContent = "This is a message box";
panel.appendChild(msg);
const closeBtn = document.createElement("button");
closeBtn.textContent = "x";
panel.appendChild(closeBtn);
```
Finally, we call `addEventListener()` to add a function that will be called when the user clicks the "close" button. The code will delete the whole panel from the page β to close the message box.
Briefly, the `addEventListener()` method is provided by the button (or in fact, any element on the page) that can be passed a function and the name of an event. In this case, the name of the event is 'click', meaning that when the user clicks the button, the function will run. You'll learn a lot more about events in our events article. The line inside the function uses the `Node.removeChild()` DOM API function to specify that we want to remove a specific child element of the HTML element β in this case, the panel `<div>`.
```js
closeBtn.addEventListener("click", () => panel.parentNode.removeChild(panel));
```
Basically, this whole block of code is generating a block of HTML that looks like so, and inserting it into the page:
```html
<div class="msgBox">
<p>This is a message box</p>
<button>x</button>
</div>
```
That was a lot of code to work through β don't worry too much if you don't remember exactly how every bit of it works right now! The main part we want to focus on here is the function's structure and usage, but we wanted to show something interesting for this example.
Calling the function
--------------------
You've now got your function definition written into your `<script>` element just fine, but it will do nothing as it stands.
1. Try including the following line below your function to call it:
```js
displayMessage();
```
This line invokes the function, making it run immediately. When you save your code and reload it in the browser, you'll see the little message box appear immediately, only once. We are only calling it once, after all.
2. Now open your browser developer tools on the example page, go to the JavaScript console and type the line again there, you'll see it appear again! So this is fun β we now have a reusable function that we can call any time we like.
But we probably want it to appear in response to user and system actions. In a real application, such a message box would probably be called in response to new data being available, or an error having occurred, or the user trying to delete their profile ("are you sure about this?"), or the user adding a new contact and the operation completing successfully, etc.
In this demo, we'll get the message box to appear when the user clicks the button.
3. Delete the previous line you added.
4. Next, we'll select the button and store a reference to it in a constant. Add the following line to your code, above the function definition:
```js
const btn = document.querySelector("button");
```
5. Finally, add the following line below the previous one:
```js
btn.addEventListener("click", displayMessage);
```
In a similar way to our closeBtn's click event handler, here we are calling some code in response to a button being clicked. But in this case, instead of calling an anonymous function containing some code, we are calling our `displayMessage()` function by name.
6. Try saving and refreshing the page β now you should see the message box appear when you click the button.
You might be wondering why we haven't included the parentheses after the function name. This is because we don't want to call the function immediately β only after the button has been clicked. If you try changing the line to
```js
btn.addEventListener("click", displayMessage());
```
and saving and reloading, you'll see that the message box appears without the button being clicked! The parentheses in this context are sometimes called the "function invocation operator". You only use them when you want to run the function immediately in the current scope. In the same respect, the code inside the anonymous function is not run immediately, as it is inside the function scope.
If you tried the last experiment, make sure to undo the last change before carrying on.
Improving the function with parameters
--------------------------------------
As it stands, the function is still not very useful β we don't want to just show the same default message every time. Let's improve our function by adding some parameters, allowing us to call it with some different options.
1. First of all, update the first line of the function:
```js
function displayMessage() {
```
to this:
```js
function displayMessage(msgText, msgType) {
```
Now when we call the function, we can provide two variable values inside the parentheses to specify the message to display in the message box, and the type of message it is.
2. To make use of the first parameter, update the following line inside your function:
```js
msg.textContent = "This is a message box";
```
to
```js
msg.textContent = msgText;
```
3. Last but not least, you now need to update your function call to include some updated message text. Change the following line:
```js
btn.addEventListener("click", displayMessage);
```
to this block:
```js
btn.addEventListener("click", () =>
displayMessage("Woo, this is a different message!"),
);
```
If we want to specify parameters inside parentheses for the function we are calling, then we can't call it directly β we need to put it inside an anonymous function so that it isn't in the immediate scope and therefore isn't called immediately. Now it will not be called until the button is clicked.
4. Reload and try the code again and you'll see that it still works just fine, except that now you can also vary the message inside the parameter to get different messages displayed in the box!
### A more complex parameter
On to the next parameter. This one is going to involve slightly more work β we are going to set it so that depending on what the `msgType` parameter is set to, the function will display a different icon and a different background color.
1. First of all, download the icons needed for this exercise (warning and chat) from GitHub. Save them in a new folder called `icons` in the same location as your HTML file.
**Note:** The warning and chat icons were originally found on iconfinder.com, and designed by Nazarrudin Ansyari β Thanks! (The actual icon pages were since moved or removed.)
2. Next, find the CSS inside your HTML file. We'll make a few changes to make way for the icons. First, update the `.msgBox` width from:
```css
width: 200px;
```
to
```css
width: 242px;
```
3. Next, add the following lines inside the `.msgBox p { }` rule:
```css
padding-left: 82px;
background-position: 25px center;
background-repeat: no-repeat;
```
4. Now we need to add code to our `displayMessage()` function to handle displaying the icons. Add the following block just above the closing curly brace (`}`) of your function:
```js
if (msgType === "warning") {
msg.style.backgroundImage = "url(icons/warning.png)";
panel.style.backgroundColor = "red";
} else if (msgType === "chat") {
msg.style.backgroundImage = "url(icons/chat.png)";
panel.style.backgroundColor = "aqua";
} else {
msg.style.paddingLeft = "20px";
}
```
Here, if the `msgType` parameter is set as `'warning'`, the warning icon is displayed and the panel's background color is set to red. If it is set to `'chat'`, the chat icon is displayed and the panel's background color is set to aqua blue. If the `msgType` parameter is not set at all (or to something different), then the `else { }` part of the code comes into play, and the paragraph is given default padding and no icon, with no background panel color set either. This provides a default state if no `msgType` parameter is provided, meaning that it is an optional parameter!
5. Let's test out our updated function, try updating the `displayMessage()` call from this:
```js
displayMessage("Woo, this is a different message!");
```
to one of these:
```js
displayMessage("Your inbox is almost full β delete some mails", "warning");
displayMessage("Brian: Hi there, how are you today?", "chat");
```
You can see how useful our (now not so) little function is becoming.
**Note:** If you have trouble getting the example to work, feel free to check your code against the finished version on GitHub (see it running live also), or ask us for help.
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Functions. These tests require skills that are covered in the next article, so you might want to read that first before trying the test.
Conclusion
----------
Congratulations on reaching the end! This article took you through the entire process of building up a practical custom function, which with a bit more work could be transplanted into a real project. In the next article, we'll wrap up functions by explaining another essential related concept β return values.
* Previous
* Overview: Building blocks
* Next |
Test your skills: Conditionals - Learn web development | Test your skills: Conditionals
==============================
The aim of this skill test is to assess whether you've understood our Making decisions in your code β conditionals article.
**Note:** You can try solutions by downloading the code and putting it in an online editor such as CodePen, JSFiddle, or Glitch.
If there is an error, it will be logged in the results panel on the page or into the browser's JavaScript console to help you.
If you get stuck, you can reach out to us in one of our communication channels.
Conditionals 1
--------------
In this task you are provided with two variables:
* `season` β contains a string that says what the current season is.
* `response` β begins uninitialized, but is later used to store a response that will be printed to the output panel.
We want you to create a conditional that checks whether `season` contains the string "summer", and if so assigns a string to `response` that gives the user an appropriate message about the season. If not, it should assign a generic string to `response` that tells the user we don't know what season it is.
To finish off, you should then add another test that checks whether `season` contains the string "winter", and again assigns an appropriate string to `response`.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Conditionals 2
--------------
For this task you are given three variables:
* `machineActive` β contains an indicator of whether the answer machine is switched on or not (`true`/`false`)
* `score` β Contains your score in an imaginary game. This score is fed into the answer machine, which provides a response to indicate how well you did.
* `response` β begins uninitialized, but is later used to store a response that will be printed to the output panel.
You need to create an `if...else` structure that checks whether the machine is switched on and puts a message into the `response` variable if it isn't, telling the user to switch the machine on.
Inside the first `if...else`, you need to nest another `if...else` that puts appropriate messages into the `response` variable depending on what the value of score is β if the machine is turned on. The different conditional tests (and resulting responses) are as follows:
* Score of less than 0 or more than 100 β "This is not possible, an error has occurred."
* Score of 0 to 19 β "That was a terrible score β total fail!"
* Score of 20 to 39 β "You know some things, but it\'s a pretty bad score. Needs improvement."
* Score of 40 to 69 β "You did a passable job, not bad!"
* Score of 70 to 89 β "That\'s a great score, you really know your stuff."
* Score of 90 to 100 β "What an amazing score! Did you cheat? Are you for real?"
Try updating the live code below to recreate the finished example. After you've entered your code, try changing `machineActive` to `true`, to see if it works.
Download the starting point for this task to work in your own editor or in an online editor.
Conditionals 3
--------------
For the final task you are given four variables:
* `machineActive` β contains an indicator of whether the login machine is switched on or not (`true`/`false`).
* `pwd` β Contains the user's login password.
* `machineResult` β begins uninitialized, but is later used to store a response that will be printed to the output panel, letting the user know whether the machine is switched on.
* `pwdResult` β begins uninitialized, but is later used to store a response that will be printed to the output panel, letting the user know whether their login attempt was successful.
We'd like you to create an `if...else` structure that checks whether the machine is switched on and puts a message into the `machineResult` variable telling the user whether it is on or off.
If the machine is on, we also want a second conditional to run that checks whether the `pwd` is equal to `cheese`. If so, it should assign a string to `pwdResult` telling the user they logged in successfully. If not, it should assign a different string to `pwdResult` telling the user their login attempt was not successful. We'd like you to do this in a single line, using something that isn't an `if...else` structure.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
Test your skills: Loops - Learn web development | Test your skills: Loops
=======================
The aim of this skill test is to assess whether you've understood our Looping code article.
**Note:** You can try solutions by downloading the code and putting it in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
DOM manipulation: considered useful
-----------------------------------
Some of the questions below require you to write some DOM manipulation code to complete them β such as creating new HTML elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page β all via JavaScript.
We haven't explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into what DOM APIs you need to successfully answer the questions. A good starting place is our Manipulating documents tutorial.
Loops 1
-------
In our first looping task we want you to start by creating a simple loop that goes through all the items in the provided `myArray` and prints them out on the screen inside list items (i.e., `<li>` elements), which are appended to the provided `list`.
Download the starting point for this task to work in your own editor or in an online editor.
Loops 2
-------
In this next task, we want you to write a simple program that, given a name, searches an array of objects containing names and phone numbers (`phonebook`) and, if it finds the name, outputs the name and phone number into the paragraph (`para`) and then exits the loop before it has run its course.
If you haven't read about objects yet, don't worry! For now, all you need to know is how to access a member-value pair. You can read up on objects in the JavaScript object basics tutorial.
You are given three variables to begin with:
* `name` β contains a name to search for
* `para` β contains a reference to a paragraph, which will be used to report the results
* `phonebook` - contains the phonebook entries to search.
You should use a type of loop that you've not used in the previous task.
Download the starting point for this task to work in your own editor or in an online editor.
Loops 3
-------
In this final task, you are provided with the following:
* `i` β starts off with a value of 500; intended to be used as an iterator.
* `para` β contains a reference to a paragraph, which will be used to report the results.
* `isPrime()` β a function that, when passed a number, returns `true` if the number is a prime number, and `false` if not.
You need to use a loop to go through the numbers 2 to 500 backwards (1 is not counted as a prime number), and run the provided `isPrime()` function on them. For each number that isn't a prime number, continue on to the next loop iteration. For each one that is a prime number, add it to the paragraph's `textContent` along with some kind of separator.
You should use a type of loop that you've not used in the previous two tasks.
Download the starting point for this task to work in your own editor or in an online editor. |
How to use promises - Learn web development | How to use promises
===================
* Previous
* Overview: Asynchronous
* Next
**Promises** are the foundation of asynchronous programming in modern JavaScript. A promise is an object returned by an asynchronous function, which represents the current state of the operation. At the time the promise is returned to the caller, the operation often isn't finished, but the promise object provides methods to handle the eventual success or failure of the operation.
| | |
| --- | --- |
| Prerequisites: |
A reasonable understanding of JavaScript
fundamentals, including event handling.
|
| Objective: | To understand how to use promises in JavaScript. |
In the previous article, we talked about the use of callbacks to implement asynchronous functions. With that design, you call the asynchronous function, passing in your callback function. The function returns immediately and calls your callback when the operation is finished.
With a promise-based API, the asynchronous function starts the operation and returns a `Promise` object. You can then attach handlers to this promise object, and these handlers will be executed when the operation has succeeded or failed.
Using the fetch() API
---------------------
**Note:** In this article, we will explore promises by copying code samples from the page into your browser's JavaScript console. To set this up:
1. open a browser tab and visit https://example.org
2. in that tab, open the JavaScript console in your browser's developer tools
3. when we show an example, copy it into the console. You will have to reload the page each time you enter a new example, or the console will complain that you have redeclared `fetchPromise`.
In this example, we'll download the JSON file from https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json, and log some information about it.
To do this, we'll make an **HTTP request** to the server. In an HTTP request, we send a request message to a remote server, and it sends us back a response. In this case, we'll send a request to get a JSON file from the server. Remember in the last article, where we made HTTP requests using the `XMLHttpRequest` API? Well, in this article, we'll use the `fetch()` API, which is the modern, promise-based replacement for `XMLHttpRequest`.
Copy this into your browser's JavaScript console:
```js
const fetchPromise = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
console.log(fetchPromise);
fetchPromise.then((response) => {
console.log(`Received response: ${response.status}`);
});
console.log("Started requestβ¦");
```
Here we are:
1. calling the `fetch()` API, and assigning the return value to the `fetchPromise` variable
2. immediately after, logging the `fetchPromise` variable. This should output something like: `Promise { <state>: "pending" }`, telling us that we have a `Promise` object, and it has a `state` whose value is `"pending"`. The `"pending"` state means that the fetch operation is still going on.
3. passing a handler function into the Promise's **`then()`** method. When (and if) the fetch operation succeeds, the promise will call our handler, passing in a `Response` object, which contains the server's response.
4. logging a message that we have started the request.
The complete output should be something like:
```
Promise { <state>: "pending" }
Started requestβ¦
Received response: 200
```
Note that `Started requestβ¦` is logged before we receive the response. Unlike a synchronous function, `fetch()` returns while the request is still going on, enabling our program to stay responsive. The response shows the `200` (OK) status code, meaning that our request succeeded.
This probably seems a lot like the example in the last article, where we added event handlers to the `XMLHttpRequest` object. Instead of that, we're passing a handler into the `then()` method of the returned promise.
Chaining promises
-----------------
With the `fetch()` API, once you get a `Response` object, you need to call another function to get the response data. In this case, we want to get the response data as JSON, so we would call the `json()` method of the `Response` object. It turns out that `json()` is also asynchronous. So this is a case where we have to call two successive asynchronous functions.
Try this:
```js
const fetchPromise = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
fetchPromise.then((response) => {
const jsonPromise = response.json();
jsonPromise.then((data) => {
console.log(data[0].name);
});
});
```
In this example, as before, we add a `then()` handler to the promise returned by `fetch()`. But this time, our handler calls `response.json()`, and then passes a new `then()` handler into the promise returned by `response.json()`.
This should log "baked beans" (the name of the first product listed in "products.json").
But wait! Remember the last article, where we said that by calling a callback inside another callback, we got successively more nested levels of code? And we said that this "callback hell" made our code hard to understand? Isn't this just the same, only with `then()` calls?
It is, of course. But the elegant feature of promises is that *`then()` itself returns a promise, which will be completed with the result of the function passed to it*. This means that we can (and certainly should) rewrite the above code like this:
```js
const fetchPromise = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
fetchPromise
.then((response) => response.json())
.then((data) => {
console.log(data[0].name);
});
```
Instead of calling the second `then()` inside the handler for the first `then()`, we can *return* the promise returned by `json()`, and call the second `then()` on that return value. This is called **promise chaining** and means we can avoid ever-increasing levels of indentation when we need to make consecutive asynchronous function calls.
Before we move on to the next step, there's one more piece to add. We need to check that the server accepted and was able to handle the request, before we try to read it. We'll do this by checking the status code in the response and throwing an error if it wasn't "OK":
```js
const fetchPromise = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
fetchPromise
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json();
})
.then((data) => {
console.log(data[0].name);
});
```
Catching errors
---------------
This brings us to the last piece: how do we handle errors? The `fetch()` API can throw an error for many reasons (for example, because there was no network connectivity or the URL was malformed in some way) and we are throwing an error ourselves if the server returned an error.
In the last article, we saw that error handling can get very difficult with nested callbacks, making us handle errors at every nesting level.
To support error handling, `Promise` objects provide a `catch()` method. This is a lot like `then()`: you call it and pass in a handler function. However, while the handler passed to `then()` is called when the asynchronous operation *succeeds*, the handler passed to `catch()` is called when the asynchronous operation *fails*.
If you add `catch()` to the end of a promise chain, then it will be called when any of the asynchronous function calls fail. So you can implement an operation as several consecutive asynchronous function calls, and have a single place to handle all errors.
Try this version of our `fetch()` code. We've added an error handler using `catch()`, and also modified the URL so the request will fail.
```js
const fetchPromise = fetch(
"bad-scheme://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
fetchPromise
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json();
})
.then((data) => {
console.log(data[0].name);
})
.catch((error) => {
console.error(`Could not get products: ${error}`);
});
```
Try running this version: you should see the error logged by our `catch()` handler.
Promise terminology
-------------------
Promises come with some quite specific terminology that it's worth getting clear about.
First, a promise can be in one of three states:
* **pending**: the promise has been created, and the asynchronous function it's associated with has not succeeded or failed yet. This is the state your promise is in when it's returned from a call to `fetch()`, and the request is still being made.
* **fulfilled**: the asynchronous function has succeeded. When a promise is fulfilled, its `then()` handler is called.
* **rejected**: the asynchronous function has failed. When a promise is rejected, its `catch()` handler is called.
Note that what "succeeded" or "failed" means here is up to the API in question. For example, `fetch()` rejects the returned promise if (among other reasons) a network error prevented the request being sent, but fulfills the promise if the server sent a response, even if the response was an error like 404 Not Found.
Sometimes, we use the term **settled** to cover both **fulfilled** and **rejected**.
A promise is **resolved** if it is settled, or if it has been "locked in" to follow the state of another promise.
The article Let's talk about how to talk about promises gives a great explanation of the details of this terminology.
Combining multiple promises
---------------------------
The promise chain is what you need when your operation consists of several asynchronous functions, and you need each one to complete before starting the next one. But there are other ways you might need to combine asynchronous function calls, and the `Promise` API provides some helpers for them.
Sometimes, you need all the promises to be fulfilled, but they don't depend on each other. In a case like that, it's much more efficient to start them all off together, then be notified when they have all fulfilled. The `Promise.all()` method is what you need here. It takes an array of promises and returns a single promise.
The promise returned by `Promise.all()` is:
* fulfilled when and if *all* the promises in the array are fulfilled. In this case, the `then()` handler is called with an array of all the responses, in the same order that the promises were passed into `all()`.
* rejected when and if *any* of the promises in the array are rejected. In this case, the `catch()` handler is called with the error thrown by the promise that rejected.
For example:
```js
const fetchPromise1 = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
const fetchPromise2 = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/not-found",
);
const fetchPromise3 = fetch(
"https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json",
);
Promise.all([fetchPromise1, fetchPromise2, fetchPromise3])
.then((responses) => {
for (const response of responses) {
console.log(`${response.url}: ${response.status}`);
}
})
.catch((error) => {
console.error(`Failed to fetch: ${error}`);
});
```
Here, we're making three `fetch()` requests to three different URLs. If they all succeed, we will log the response status of each one. If any of them fail, then we're logging the failure.
With the URLs we've provided, all the requests should be fulfilled, although for the second, the server will return `404` (Not Found) instead of `200` (OK) because the requested file does not exist. So the output should be:
```
https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json: 200
https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/not-found: 404
https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json: 200
```
If we try the same code with a badly formed URL, like this:
```js
const fetchPromise1 = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
const fetchPromise2 = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/not-found",
);
const fetchPromise3 = fetch(
"bad-scheme://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json",
);
Promise.all([fetchPromise1, fetchPromise2, fetchPromise3])
.then((responses) => {
for (const response of responses) {
console.log(`${response.url}: ${response.status}`);
}
})
.catch((error) => {
console.error(`Failed to fetch: ${error}`);
});
```
Then we can expect the `catch()` handler to run, and we should see something like:
```
Failed to fetch: TypeError: Failed to fetch
```
Sometimes, you might need any one of a set of promises to be fulfilled, and don't care which one. In that case, you want `Promise.any()`. This is like `Promise.all()`, except that it is fulfilled as soon as any of the array of promises is fulfilled, or rejected if all of them are rejected:
```js
const fetchPromise1 = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
const fetchPromise2 = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/not-found",
);
const fetchPromise3 = fetch(
"https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json",
);
Promise.any([fetchPromise1, fetchPromise2, fetchPromise3])
.then((response) => {
console.log(`${response.url}: ${response.status}`);
})
.catch((error) => {
console.error(`Failed to fetch: ${error}`);
});
```
Note that in this case we can't predict which fetch request will complete first.
These are just two of the extra `Promise` functions for combining multiple promises. To learn about the rest, see the `Promise` reference documentation.
async and await
---------------
The `async` keyword gives you a simpler way to work with asynchronous promise-based code. Adding `async` at the start of a function makes it an async function:
```js
async function myFunction() {
// This is an async function
}
```
Inside an async function, you can use the `await` keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
This enables you to write code that uses asynchronous functions but looks like synchronous code. For example, we could use it to rewrite our fetch example:
```js
async function fetchProducts() {
try {
// after this line, our function will wait for the `fetch()` call to be settled
// the `fetch()` call will either return a Response or throw an error
const response = await fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
// after this line, our function will wait for the `response.json()` call to be settled
// the `response.json()` call will either return the parsed JSON object or throw an error
const data = await response.json();
console.log(data[0].name);
} catch (error) {
console.error(`Could not get products: ${error}`);
}
}
fetchProducts();
```
Here, we are calling `await fetch()`, and instead of getting a `Promise`, our caller gets back a fully complete `Response` object, just as if `fetch()` were a synchronous function!
We can even use a `try...catch` block for error handling, exactly as we would if the code were synchronous.
Note though that async functions always return a promise, so you can't do something like:
```js
async function fetchProducts() {
try {
const response = await fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error(`Could not get products: ${error}`);
}
}
const promise = fetchProducts();
console.log(promise[0].name); // "promise" is a Promise object, so this will not work
```
Instead, you'd need to do something like:
```js
async function fetchProducts() {
try {
const response = await fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error(`Could not get products: ${error}`);
}
}
const promise = fetchProducts();
promise.then((data) => console.log(data[0].name));
```
Also, note that you can only use `await` inside an `async` function, unless your code is in a JavaScript module. That means you can't do this in a normal script:
```js
try {
// using await outside an async function is only allowed in a module
const response = await fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
console.log(data[0].name);
} catch (error) {
console.error(`Could not get products: ${error}`);
}
```
You'll probably use `async` functions a lot where you might otherwise use promise chains, and they make working with promises much more intuitive.
Keep in mind that just like a promise chain, `await` forces asynchronous operations to be completed in series. This is necessary if the result of the next operation depends on the result of the last one, but if that's not the case then something like `Promise.all()` will be more performant.
Conclusion
----------
Promises are the foundation of asynchronous programming in modern JavaScript. They make it easier to express and reason about sequences of asynchronous operations without deeply nested callbacks, and they support a style of error handling that is similar to the synchronous `try...catch` statement.
The `async` and `await` keywords make it easier to build an operation from a series of consecutive asynchronous function calls, avoiding the need to create explicit promise chains, and allowing you to write code that looks just like synchronous code.
Promises work in the latest versions of all modern browsers; the only place where promise support will be a problem is in Opera Mini and IE11 and earlier versions.
We didn't touch on all features of promises in this article, just the most interesting and useful ones. As you start to learn more about promises, you'll come across more features and techniques.
Many modern Web APIs are promise-based, including WebRTC, Web Audio API, Media Capture and Streams API, and many more.
See also
--------
* `Promise()`
* Using promises
* We have a problem with promises by Nolan Lawson
* Let's talk about how to talk about promises
* Previous
* Overview: Asynchronous
* Next |
Introducing workers - Learn web development | Introducing workers
===================
* Previous
* Overview: Asynchronous
* Next
In this final article in our "Asynchronous JavaScript" module, we'll introduce *workers*, which enable you to run some tasks in a separate thread of execution.
| | |
| --- | --- |
| Prerequisites: |
A reasonable understanding of JavaScript
fundamentals, including event handling.
|
| Objective: | To understand how to use web workers. |
In the first article of this module, we saw what happens when you have a long-running synchronous task in your program β the whole window becomes totally unresponsive. Fundamentally, the reason for this is that the program is *single-threaded*. A *thread* is a sequence of instructions that a program follows. Because the program consists of a single thread, it can only do one thing at a time: so if it is waiting for our long-running synchronous call to return, it can't do anything else.
Workers give you the ability to run some tasks in a different thread, so you can start the task, then continue with other processing (such as handling user actions).
One concern from all this is that if multiple threads can have access to the same shared data, it's possible for them to change it independently and unexpectedly (with respect to each other).
This can cause bugs that are hard to find.
To avoid these problems on the web, your main code and your worker code never get direct access to each other's variables, and can only truly "share" data in very specific cases.
Workers and the main code run in completely separate worlds, and only interact by sending each other messages. In particular, this means that workers can't access the DOM (the window, document, page elements, and so on).
There are three different sorts of workers:
* dedicated workers
* shared workers
* service workers
In this article, we'll walk through an example of the first sort of worker, then briefly discuss the other two.
Using web workers
-----------------
Remember in the first article, where we had a page that calculated prime numbers? We're going to use a worker to run the prime-number calculation, so our page stays responsive to user actions.
### The synchronous prime generator
Let's first take another look at the JavaScript in our previous example:
```js
function generatePrimes(quota) {
function isPrime(n) {
for (let c = 2; c <= Math.sqrt(n); ++c) {
if (n % c === 0) {
return false;
}
}
return true;
}
const primes = [];
const maximum = 1000000;
while (primes.length < quota) {
const candidate = Math.floor(Math.random() \* (maximum + 1));
if (isPrime(candidate)) {
primes.push(candidate);
}
}
return primes;
}
document.querySelector("#generate").addEventListener("click", () => {
const quota = document.querySelector("#quota").value;
const primes = generatePrimes(quota);
document.querySelector("#output").textContent =
`Finished generating ${quota} primes!`;
});
document.querySelector("#reload").addEventListener("click", () => {
document.querySelector("#user-input").value =
'Try typing in here immediately after pressing "Generate primes"';
document.location.reload();
});
```
In this program, after we call `generatePrimes()`, the program becomes totally unresponsive.
### Prime generation with a worker
For this example, start by making a local copy of the files at https://github.com/mdn/learning-area/blob/main/javascript/asynchronous/workers/start. There are four files in this directory:
* index.html
* style.css
* main.js
* generate.js
The "index.html" file and the "style.css" files are already complete:
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Prime numbers</title>
<script src="main.js" defer></script>
<link href="style.css" rel="stylesheet" />
</head>
<body>
<label for="quota">Number of primes:</label>
<input type="text" id="quota" name="quota" value="1000000" />
<button id="generate">Generate primes</button>
<button id="reload">Reload</button>
<textarea id="user-input" rows="5" cols="62">
Try typing in here immediately after pressing "Generate primes"
</textarea>
<div id="output"></div>
</body>
</html>
```
```css
textarea {
display: block;
margin: 1rem 0;
}
```
The "main.js" and "generate.js" files are empty. We're going to add the main code to "main.js", and the worker code to "generate.js".
So first, we can see that the worker code is kept in a separate script from the main code. We can also see, looking at "index.html" above, that only the main code is included in a `<script>` element.
Now copy the following code into "main.js":
```js
// Create a new worker, giving it the code in "generate.js"
const worker = new Worker("./generate.js");
// When the user clicks "Generate primes", send a message to the worker.
// The message command is "generate", and the message also contains "quota",
// which is the number of primes to generate.
document.querySelector("#generate").addEventListener("click", () => {
const quota = document.querySelector("#quota").value;
worker.postMessage({
command: "generate",
quota,
});
});
// When the worker sends a message back to the main thread,
// update the output box with a message for the user, including the number of
// primes that were generated, taken from the message data.
worker.addEventListener("message", (message) => {
document.querySelector("#output").textContent =
`Finished generating ${message.data} primes!`;
});
document.querySelector("#reload").addEventListener("click", () => {
document.querySelector("#user-input").value =
'Try typing in here immediately after pressing "Generate primes"';
document.location.reload();
});
```
* First, we're creating the worker using the `Worker()` constructor. We pass it a URL pointing to the worker script. As soon as the worker is created, the worker script is executed.
* Next, as in the synchronous version, we add a `click` event handler to the "Generate primes" button. But now, rather than calling a `generatePrimes()` function, we send a message to the worker using `worker.postMessage()`. This message can take an argument, and in this case, we're passing a JSON object containing two properties:
+ `command`: a string identifying the thing we want the worker to do (in case our worker could do more than one thing)
+ `quota`: the number of primes to generate.
* Next, we add a `message` event handler to the worker. This is so the worker can tell us when it has finished, and pass us any resulting data. Our handler takes the data from the `data` property of the message, and writes it to the output element (the data is exactly the same as `quota`, so this is a bit pointless, but it shows the principle).
* Finally, we implement the `click` event handler for the "Reload" button. This is exactly the same as in the synchronous version.
Now for the worker code. Copy the following code into "generate.js":
```js
// Listen for messages from the main thread.
// If the message command is "generate", call `generatePrimes()`
addEventListener("message", (message) => {
if (message.data.command === "generate") {
generatePrimes(message.data.quota);
}
});
// Generate primes (very inefficiently)
function generatePrimes(quota) {
function isPrime(n) {
for (let c = 2; c <= Math.sqrt(n); ++c) {
if (n % c === 0) {
return false;
}
}
return true;
}
const primes = [];
const maximum = 1000000;
while (primes.length < quota) {
const candidate = Math.floor(Math.random() \* (maximum + 1));
if (isPrime(candidate)) {
primes.push(candidate);
}
}
// When we have finished, send a message to the main thread,
// including the number of primes we generated.
postMessage(primes.length);
}
```
Remember that this runs as soon as the main script creates the worker.
The first thing the worker does is start listening for messages from the main script. It does this using `addEventListener()`, which is a global function in a worker. Inside the `message` event handler, the `data` property of the event contains a copy of the argument passed from the main script. If the main script passed the `generate` command, we call `generatePrimes()`, passing in the `quota` value from the message event.
The `generatePrimes()` function is just like the synchronous version, except instead of returning a value, we send a message to the main script when we are done. We use the `postMessage()` function for this, which like `addEventListener()` is a global function in a worker. As we already saw, the main script is listening for this message and will update the DOM when the message is received.
**Note:** To run this site, you'll have to run a local web server, because file:// URLs are not allowed to load workers. See our guide to setting up a local testing server. With that done, you should be able to click "Generate primes" and have your main page stay responsive.
If you have any problems creating or running the example, you can review the finished version and try it live.
Other types of workers
----------------------
The worker we just created was what's called a *dedicated worker*. This means it's used by a single script instance.
There are other types of workers, though:
* *Shared workers* can be shared by several different scripts running in different windows.
* *Service workers* act like proxy servers, caching resources so that web applications can work when the user is offline. They're a key component of Progressive Web Apps.
Conclusion
----------
In this article we've introduced web workers, which enable a web application to offload tasks to a separate thread. The main thread and the worker don't directly share any variables, but communicate by sending messages, which are received by the other side as `message` events.
Workers can be an effective way to keep the main application responsive, although they can't access all the APIs that the main application can, and in particular can't access the DOM.
See also
--------
* Using web workers
* Using service workers
* Web workers API
* Previous
* Overview: Asynchronous
* Next |
How to implement a promise-based API - Learn web development | How to implement a promise-based API
====================================
* Previous
* Overview: Asynchronous
* Next
In the last article we discussed how to use APIs that return promises. In this article we'll look at the other side β how to *implement* APIs that return promises. This is a much less common task than using promise-based APIs, but it's still worth knowing about.
| | |
| --- | --- |
| Prerequisites: |
A reasonable understanding of JavaScript
fundamentals, including event handling and the basics of promises.
|
| Objective: | To understand how to implement promise-based APIs. |
Generally, when you implement a promise-based API, you'll be wrapping an asynchronous operation, which might use events, or plain callbacks, or a message-passing model. You'll arrange for a `Promise` object to handle the success or failure of that operation properly.
Implementing an alarm() API
---------------------------
In this example we'll implement a promise-based alarm API, called `alarm()`. It will take as arguments the name of the person to wake up and a delay in milliseconds to wait before waking the person up. After the delay, the function will send a "Wake up!" message, including the name of the person we need to wake up.
### Wrapping setTimeout()
We'll use the `setTimeout()` API to implement our `alarm()` function. The `setTimeout()` API takes as arguments a callback function and a delay, given in milliseconds. When `setTimeout()` is called, it starts a timer set to the given delay, and when the time expires, it calls the given function.
In the example below, we call `setTimeout()` with a callback function and a delay of 1000 milliseconds:
```html
<button id="set-alarm">Set alarm</button>
<div id="output"></div>
```
```
div {
margin: 0.5rem 0;
}
```
```js
const output = document.querySelector("#output");
const button = document.querySelector("#set-alarm");
function setAlarm() {
setTimeout(() => {
output.textContent = "Wake up!";
}, 1000);
}
button.addEventListener("click", setAlarm);
```
### The Promise() constructor
Our `alarm()` function will return a `Promise` that is fulfilled when the timer expires. It will pass a "Wake up!" message into the `then()` handler, and will reject the promise if the caller supplies a negative delay value.
The key component here is the `Promise()` constructor. The `Promise()` constructor takes a single function as an argument. We'll call this function the `executor`. When you create a new promise you supply the implementation of the executor.
This executor function itself takes two arguments, which are both also functions, and which are conventionally called `resolve` and `reject`. In your executor implementation, you call the underlying asynchronous function. If the asynchronous function succeeds, you call `resolve`, and if it fails, you call `reject`. If the executor function throws an error, `reject` is called automatically. You can pass a single parameter of any type into `resolve` and `reject`.
So we can implement `alarm()` like this:
```js
function alarm(person, delay) {
return new Promise((resolve, reject) => {
if (delay < 0) {
throw new Error("Alarm delay must not be negative");
}
setTimeout(() => {
resolve(`Wake up, ${person}!`);
}, delay);
});
}
```
This function creates and returns a new `Promise`. Inside the executor for the promise, we:
* check that `delay` is not negative, and throw an error if it is.
* call `setTimeout()`, passing a callback and `delay`. The callback will be called when the timer expires, and in the callback we call `resolve`, passing in our `"Wake up!"` message.
Using the alarm() API
---------------------
This part should be quite familiar from the last article. We can call `alarm()`, and on the returned promise call `then()` and `catch()` to set handlers for promise fulfillment and rejection.
```
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" size="4" value="Matilda" />
</div>
<div>
<label for="delay">Delay:</label>
<input type="text" id="delay" name="delay" size="4" value="1000" />
</div>
<button id="set-alarm">Set alarm</button>
<div id="output"></div>
```
```
button {
display: block;
}
div,
button {
margin: 0.5rem 0;
}
```
```js
const name = document.querySelector("#name");
const delay = document.querySelector("#delay");
const button = document.querySelector("#set-alarm");
const output = document.querySelector("#output");
function alarm(person, delay) {
return new Promise((resolve, reject) => {
if (delay < 0) {
throw new Error("Alarm delay must not be negative");
}
setTimeout(() => {
resolve(`Wake up, ${person}!`);
}, delay);
});
}
button.addEventListener("click", () => {
alarm(name.value, delay.value)
.then((message) => (output.textContent = message))
.catch((error) => (output.textContent = `Couldn't set alarm: ${error}`));
});
```
Try setting different values for "Name" and "Delay". Try setting a negative value for "Delay".
Using async and await with the alarm() API
------------------------------------------
Since `alarm()` returns a `Promise`, we can do everything with it that we could do with any other promise: promise chaining, `Promise.all()`, and `async` / `await`:
```
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" size="4" value="Matilda" />
</div>
<div>
<label for="delay">Delay:</label>
<input type="text" id="delay" name="delay" size="4" value="1000" />
</div>
<button id="set-alarm">Set alarm</button>
<div id="output"></div>
```
```
button {
display: block;
}
div,
button {
margin: 0.5rem 0;
}
```
```js
const name = document.querySelector("#name");
const delay = document.querySelector("#delay");
const button = document.querySelector("#set-alarm");
const output = document.querySelector("#output");
function alarm(person, delay) {
return new Promise((resolve, reject) => {
if (delay < 0) {
throw new Error("Alarm delay must not be negative");
}
setTimeout(() => {
resolve(`Wake up, ${person}!`);
}, delay);
});
}
button.addEventListener("click", async () => {
try {
const message = await alarm(name.value, delay.value);
output.textContent = message;
} catch (error) {
output.textContent = `Couldn't set alarm: ${error}`;
}
});
```
See also
--------
* `Promise()` constructor
* Using promises
* Previous
* Overview: Asynchronous
* Next |
Sequencing animations - Learn web development | Sequencing animations
=====================
* Previous
* Overview: Asynchronous
In this assessment you'll update a page to play a series of animations in a sequence. To do this you'll use some of the techniques we learned in the How to use Promises article.
| | |
| --- | --- |
| Prerequisites: |
A reasonable understanding of JavaScript
fundamentals, how to use promise-based APIs.
|
| Objective: | To test understanding of how to use promise-based APIs. |
Starting point
--------------
Make a local copy of the files at https://github.com/mdn/learning-area/tree/main/javascript/asynchronous/sequencing-animations/start. It contains four files:
* alice.svg
* index.html
* main.js
* style.css
The only file you'll need to edit is "main.js".
If you open "index.html" in a browser you'll see three images arranged diagonally:
![Screenshot of sequencing-animations assessment page](/en-US/docs/Learn/JavaScript/Asynchronous/Sequencing_animations/sequencing-animations.png)
The images are taken from our guide to Using the Web Animations API.
**Note:** If you get stuck, you can reach out to us in one of our communication channels.
Project brief
-------------
We want to update this page so we apply an animation to all three images, one after the other. So when the first has finished we animate the second, and when the second has finished we animate the third.
The animation is already defined in "main.js": it just rotates the image and shrinks it until it disappears.
To give you more of an idea of how we want the page to work, have a look at the finished example. Note that the animations only run once: to see them run again, reload the page.
Steps to complete
-----------------
### Animating the first image
We're using the Web Animations API to animate the images, specifically the `element.animate()` method.
Update "main.js" to add a call to `alice1.animate()`, like this:
```js
const aliceTumbling = [
{ transform: "rotate(0) scale(1)" },
{ transform: "rotate(360deg) scale(0)" },
];
const aliceTiming = {
duration: 2000,
iterations: 1,
fill: "forwards",
};
const alice1 = document.querySelector("#alice1");
const alice2 = document.querySelector("#alice2");
const alice3 = document.querySelector("#alice3");
alice1.animate(aliceTumbling, aliceTiming);
```
Reload the page, and you should see the first image rotate and shrink.
### Animating all the images
Next, we want to animate `alice2` when `alice1` has finished, and `alice3` when `alice2` has finished.
The `animate()` method returns an `Animation` object. This object has a `finished` property, which is a `Promise` that is fulfilled when the animation has finished playing. So we can use this promise to know when to start the next animation.
We'd like you to try a few different ways to implement this, to reinforce different ways of using promises.
1. First, implement something that works, but has the promise version of the "callback hell" problem we saw in our discussion of using callbacks.
2. Next, implement it as a promise chain. Note that there are a few different ways you can write this, because of the different forms you can use for an arrow function. Try some different forms. Which is the most concise? Which do you find the most readable?
3. Finally, implement it using `async` and `await`.
Remember that `element.animate()` does *not* return a `Promise`: it returns an `Animation` object with a `finished` property that is a `Promise`.
* Previous
* Overview: Asynchronous |
Introducing asynchronous JavaScript - Learn web development | Introducing asynchronous JavaScript
===================================
* Overview: Asynchronous
* Next
In this article, we'll explain what asynchronous programming is, why we need it, and briefly discuss some of the ways asynchronous functions have historically been implemented in JavaScript.
| | |
| --- | --- |
| Prerequisites: |
A reasonable understanding of JavaScript
fundamentals, including functions and event handlers.
|
| Objective: | To gain familiarity with what asynchronous JavaScript is, how it differs from synchronous JavaScript, and why we need it. |
Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished. Once that task has finished, your program is presented with the result.
Many functions provided by browsers, especially the most interesting ones, can potentially take a long time, and therefore, are asynchronous. For example:
* Making HTTP requests using `fetch()`
* Accessing a user's camera or microphone using `getUserMedia()`
* Asking a user to select files using `showOpenFilePicker()`
So even though you may not have to *implement* your own asynchronous functions very often, you are very likely to need to *use* them correctly.
In this article, we'll start by looking at the problem with long-running synchronous functions, which make asynchronous programming a necessity.
Synchronous programming
-----------------------
Consider the following code:
```js
const name = "Miriam";
const greeting = `Hello, my name is ${name}!`;
console.log(greeting);
// "Hello, my name is Miriam!"
```
This code:
1. Declares a string called `name`.
2. Declares another string called `greeting`, which uses `name`.
3. Outputs the greeting to the JavaScript console.
We should note here that the browser effectively steps through the program one line at a time, in the order we wrote it. At each point, the browser waits for the line to finish its work before going on to the next line. It has to do this because each line depends on the work done in the preceding lines.
That makes this a **synchronous program**. It would still be synchronous even if we called a separate function, like this:
```js
function makeGreeting(name) {
return `Hello, my name is ${name}!`;
}
const name = "Miriam";
const greeting = makeGreeting(name);
console.log(greeting);
// "Hello, my name is Miriam!"
```
Here, `makeGreeting()` is a **synchronous function** because the caller has to wait for the function to finish its work and return a value before the caller can continue.
### A long-running synchronous function
What if the synchronous function takes a long time?
The program below uses a very inefficient algorithm to generate multiple large prime numbers when a user clicks the "Generate primes" button. The higher the number of primes a user specifies, the longer the operation will take.
```html
<label for="quota">Number of primes:</label>
<input type="text" id="quota" name="quota" value="1000000" />
<button id="generate">Generate primes</button>
<button id="reload">Reload</button>
<div id="output"></div>
```
```js
const MAX\_PRIME = 1000000;
function isPrime(n) {
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
return false;
}
}
return n > 1;
}
const random = (max) => Math.floor(Math.random() \* max);
function generatePrimes(quota) {
const primes = [];
while (primes.length < quota) {
const candidate = random(MAX\_PRIME);
if (isPrime(candidate)) {
primes.push(candidate);
}
}
return primes;
}
const quota = document.querySelector("#quota");
const output = document.querySelector("#output");
document.querySelector("#generate").addEventListener("click", () => {
const primes = generatePrimes(quota.value);
output.textContent = `Finished generating ${quota.value} primes!`;
});
document.querySelector("#reload").addEventListener("click", () => {
document.location.reload();
});
```
Try clicking "Generate primes". Depending on how fast your computer is, it will probably take a few seconds before the program displays the "Finished!" message.
### The trouble with long-running synchronous functions
The next example is just like the last one, except we added a text box for you to type in. This time, click "Generate primes", and try typing in the text box immediately after.
You'll find that while our `generatePrimes()` function is running, our program is completely unresponsive: you can't type anything, click anything, or do anything else.
```
<label for="quota">Number of primes:</label>
<input type="text" id="quota" name="quota" value="1000000" />
<button id="generate">Generate primes</button>
<button id="reload">Reload</button>
<textarea id="user-input" rows="5" cols="62">
Try typing in here immediately after pressing "Generate primes"
</textarea>
<div id="output"></div>
```
```
textarea {
display: block;
margin: 1rem 0;
}
```
```
const MAX\_PRIME = 1000000;
function isPrime(n) {
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
return false;
}
}
return n > 1;
}
const random = (max) => Math.floor(Math.random() \* max);
function generatePrimes(quota) {
const primes = [];
while (primes.length < quota) {
const candidate = random(MAX\_PRIME);
if (isPrime(candidate)) {
primes.push(candidate);
}
}
return primes;
}
const quota = document.querySelector("#quota");
const output = document.querySelector("#output");
document.querySelector("#generate").addEventListener("click", () => {
const primes = generatePrimes(quota.value);
output.textContent = `Finished generating ${quota.value} primes!`;
});
document.querySelector("#reload").addEventListener("click", () => {
document.location.reload();
});
```
The reason for this is that this JavaScript program is *single-threaded*. A thread is a sequence of instructions that a program follows. Because the program consists of a single thread, it can only do one thing at a time: so if it is waiting for our long-running synchronous call to return, it can't do anything else.
What we need is a way for our program to:
1. Start a long-running operation by calling a function.
2. Have that function start the operation and return immediately, so that our program can still be responsive to other events.
3. Have the function execute the operation in a way that does not block the main thread, for example by starting a new thread.
4. Notify us with the result of the operation when it eventually completes.
That's precisely what asynchronous functions enable us to do. The rest of this module explains how they are implemented in JavaScript.
Event handlers
--------------
The description we just saw of asynchronous functions might remind you of event handlers, and if it does, you'd be right. Event handlers are really a form of asynchronous programming: you provide a function (the event handler) that will be called, not right away, but whenever the event happens. If "the event" is "the asynchronous operation has completed", then that event could be used to notify the caller about the result of an asynchronous function call.
Some early asynchronous APIs used events in just this way. The `XMLHttpRequest` API enables you to make HTTP requests to a remote server using JavaScript. Since this can take a long time, it's an asynchronous API, and you get notified about the progress and eventual completion of a request by attaching event listeners to the `XMLHttpRequest` object.
The following example shows this in action. Press "Click to start request" to send a request. We create a new `XMLHttpRequest` and listen for its `loadend` event. The handler logs a "Finished!" message along with the status code.
After adding the event listener we send the request. Note that after this, we can log "Started XHR request": that is, our program can continue to run while the request is going on, and our event handler will be called when the request is complete.
```html
<button id="xhr">Click to start request</button>
<button id="reload">Reload</button>
<pre readonly class="event-log"></pre>
```
```
pre {
display: block;
margin: 1rem 0;
}
```
```js
const log = document.querySelector(".event-log");
document.querySelector("#xhr").addEventListener("click", () => {
log.textContent = "";
const xhr = new XMLHttpRequest();
xhr.addEventListener("loadend", () => {
log.textContent = `${log.textContent}Finished with status: ${xhr.status}`;
});
xhr.open(
"GET",
"https://raw.githubusercontent.com/mdn/content/main/files/en-us/\_wikihistory.json",
);
xhr.send();
log.textContent = `${log.textContent}Started XHR request\n`;
});
document.querySelector("#reload").addEventListener("click", () => {
log.textContent = "";
document.location.reload();
});
```
This is just like the event handlers we've encountered in a previous module, except that instead of the event being a user action, such as the user clicking a button, the event is a change in the state of some object.
Callbacks
---------
An event handler is a particular type of callback. A callback is just a function that's passed into another function, with the expectation that the callback will be called at the appropriate time. As we just saw, callbacks used to be the main way asynchronous functions were implemented in JavaScript.
However, callback-based code can get hard to understand when the callback itself has to call functions that accept a callback. This is a common situation if you need to perform some operation that breaks down into a series of asynchronous functions. For example, consider the following:
```js
function doStep1(init) {
return init + 1;
}
function doStep2(init) {
return init + 2;
}
function doStep3(init) {
return init + 3;
}
function doOperation() {
let result = 0;
result = doStep1(result);
result = doStep2(result);
result = doStep3(result);
console.log(`result: ${result}`);
}
doOperation();
```
Here we have a single operation that's split into three steps, where each step depends on the last step. In our example, the first step adds 1 to the input, the second adds 2, and the third adds 3. Starting with an input of 0, the end result is 6 (0 + 1 + 2 + 3). As a synchronous program, this is very straightforward. But what if we implemented the steps using callbacks?
```js
function doStep1(init, callback) {
const result = init + 1;
callback(result);
}
function doStep2(init, callback) {
const result = init + 2;
callback(result);
}
function doStep3(init, callback) {
const result = init + 3;
callback(result);
}
function doOperation() {
doStep1(0, (result1) => {
doStep2(result1, (result2) => {
doStep3(result2, (result3) => {
console.log(`result: ${result3}`);
});
});
});
}
doOperation();
```
Because we have to call callbacks inside callbacks, we get a deeply nested `doOperation()` function, which is much harder to read and debug. This is sometimes called "callback hell" or the "pyramid of doom" (because the indentation looks like a pyramid on its side).
When we nest callbacks like this, it can also get very hard to handle errors: often you have to handle errors at each level of the "pyramid", instead of having error handling only once at the top level.
For these reasons, most modern asynchronous APIs don't use callbacks. Instead, the foundation of asynchronous programming in JavaScript is the `Promise`, and that's the subject of the next article.
* Overview: Asynchronous
* Next |
Drawing graphics - Learn web development | Drawing graphics
================
* Previous
* Overview: Client-side web APIs
* Next
The browser contains some very powerful graphics programming tools, from the Scalable Vector Graphics (SVG) language, to APIs for drawing on HTML `<canvas>` elements, (see The Canvas API and WebGL). This article provides an introduction to canvas, and further resources to allow you to learn more.
| | |
| --- | --- |
| Prerequisites: |
JavaScript basics (see
first steps,
building blocks,
JavaScript objects),
the
basics of Client-side APIs |
| Objective: |
To learn the basics of drawing on `<canvas>` elements
using JavaScript.
|
Graphics on the Web
-------------------
As we talked about in our HTML Multimedia and embedding module, the Web was originally just text, which was very boring, so images were introduced β first via the `<img>` element and later via CSS properties such as `background-image`, and SVG.
This however was still not enough. While you could use CSS and JavaScript to animate (and otherwise manipulate) SVG vector images β as they are represented by markup β there was still no way to do the same for bitmap images, and the tools available were rather limited. The Web still had no way to effectively create animations, games, 3D scenes, and other requirements commonly handled by lower level languages such as C++ or Java.
The situation started to improve when browsers began to support the `<canvas>` element and associated Canvas API in 2004. As you'll see below, canvas provides some useful tools for creating 2D animations, games, data visualizations, and other types of applications, especially when combined with some of the other APIs the web platform provides, but can be difficult or impossible to make accessible
The below example shows a simple 2D canvas-based bouncing balls animation that we originally met in our Introducing JavaScript objects module:
Around 2006β2007, Mozilla started work on an experimental 3D canvas implementation. This became WebGL, which gained traction among browser vendors, and was standardized around 2009β2010. WebGL allows you to create real 3D graphics inside your web browser; the below example shows a simple rotating WebGL cube:
This article will focus mainly on 2D canvas, as raw WebGL code is very complex. We will however show how to use a WebGL library to create a 3D scene more easily, and you can find a tutorial covering raw WebGL elsewhere β see Getting started with WebGL.
Active learning: Getting started with a <canvas>
------------------------------------------------
If you want to create a 2D *or* 3D scene on a web page, you need to start with an HTML `<canvas>` element. This element is used to define the area on the page into which the image will be drawn. This is as simple as including the element on the page:
```html
<canvas width="320" height="240"></canvas>
```
This will create a canvas on the page with a size of 320 by 240 pixels.
You should put some fallback content inside the `<canvas>` tags. This should describe the canvas content to users of browsers that don't support canvas, or users of screen readers.
```html
<canvas width="320" height="240">
<p>Description of the canvas for those unable to view it.</p>
</canvas>
```
The fallback should provide useful alternative content to the canvas content. For example, if you are rendering a constantly updating graph of stock prices, the fallback content could be a static image of the latest stock graph, with `alt` text saying what the prices are in text or a list of links to individual stock pages.
**Note:** Canvas content is not accessible to screen readers. Include descriptive text as the value of the `aria-label` attribute directly on the canvas element itself or include fallback content placed within the opening and closing `<canvas>` tags. Canvas content is not part of the DOM, but nested fallback content is.
### Creating and sizing our canvas
Let's start by creating our own canvas that we draw future experiments on to.
1. First make a local copy of the 0\_canvas\_start directory. It contains three files:
* "index.html"
* "script.js"
* "style.css"
2. Open "index.html", and add the following code into it, just below the opening `<body>` tag:
```html
<canvas class="myCanvas">
<p>Add suitable fallback here.</p>
</canvas>
```
We have added a `class` to the `<canvas>` element so it will be easier to select if we have multiple canvases on the page, but we have removed the `width` and `height` attributes for now (you could add them back in if you wanted, but we will set them using JavaScript in a below section). Canvases with no explicit width and height default to 300 pixels wide by 150 pixels high.
3. Now open "script.js" and add the following lines of JavaScript:
```js
const canvas = document.querySelector(".myCanvas");
const width = (canvas.width = window.innerWidth);
const height = (canvas.height = window.innerHeight);
```
Here we have stored a reference to the canvas in the `canvas` constant. In the second line we set both a new constant `width` and the canvas' `width` property equal to `Window.innerWidth` (which gives us the viewport width). In the third line we set both a new constant `height` and the canvas' `height` property equal to `Window.innerHeight` (which gives us the viewport height). So now we have a canvas that fills the entire width and height of the browser window!
You'll also see that we are chaining assignments together with multiple equals signs β this is allowed in JavaScript, and it is a good technique if you want to make multiple variables all equal to the same value. We wanted to make the canvas width and height easily accessible in the width/height variables, as they are useful values to have available for later (for example, if you want to draw something exactly halfway across the width of the canvas).
**Note:** You should generally set the size of the image using HTML attributes or DOM properties, as explained above. You could use CSS, but the trouble then is that the sizing is done after the canvas has rendered, and just like any other image (the rendered canvas is just an image), the image could become pixelated/distorted.
### Getting the canvas context and final setup
We need to do one final thing before we can consider our canvas template finished. To draw onto the canvas we need to get a special reference to the drawing area called a context. This is done using the `HTMLCanvasElement.getContext()` method, which for basic usage takes a single string as a parameter representing the type of context you want to retrieve.
In this case we want a 2d canvas, so add the following JavaScript line below the others in "script.js":
```js
const ctx = canvas.getContext("2d");
```
**Note:** other context values you could choose include `webgl` for WebGL, `webgl2` for WebGL 2, etc., but we won't need those in this article.
So that's it β our canvas is now primed and ready for drawing on! The `ctx` variable now contains a `CanvasRenderingContext2D` object, and all drawing operations on the canvas will involve manipulating this object.
Let's do one last thing before we move on. We'll color the canvas background black to give you a first taste of the canvas API. Add the following lines at the bottom of your JavaScript:
```js
ctx.fillStyle = "rgb(0 0 0)";
ctx.fillRect(0, 0, width, height);
```
Here we are setting a fill color using the canvas' `fillStyle` property (this takes color values just like CSS properties do), then drawing a rectangle that covers the entire area of the canvas with the `fillRect` method (the first two parameters are the coordinates of the rectangle's top left-hand corner; the last two are the width and height you want the rectangle drawn at β we told you those `width` and `height` variables would be useful)!
OK, our template is done and it's time to move on.
2D canvas basics
----------------
As we said above, all drawing operations are done by manipulating a `CanvasRenderingContext2D` object (in our case, `ctx`). Many operations need to be given coordinates to pinpoint exactly where to draw something β the top left of the canvas is point (0, 0), the horizontal (x) axis runs from left to right, and the vertical (y) axis runs from top to bottom.
![Gridded graph paper with small squares covering its area with a steelblue square in the middle. The top left corner of the canvas is point (0, 0) of the canvas x-axis and y-axis. The horizontal (x) axis runs from left to right denoting the width, and the vertical (y) axis runs from top to bottom denotes the height. The top left corner of the blue square is labeled as being a distance of x units from the y-axis and y units from the x-axis.](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Drawing_graphics/canvas_default_grid.png)
Drawing shapes tends to be done using the rectangle shape primitive, or by tracing a line along a certain path and then filling in the shape. Below we'll show how to do both.
### Simple rectangles
Let's start with some simple rectangles.
1. First of all, take a copy of your newly coded canvas template (or make a local copy of the 1\_canvas\_template directory if you didn't follow the above steps).
2. Next, add the following lines to the bottom of your JavaScript:
```js
ctx.fillStyle = "rgb(255 0 0)";
ctx.fillRect(50, 50, 100, 150);
```
If you save and refresh, you should see a red rectangle has appeared on your canvas. Its top left corner is 50 pixels away from the top and left of the canvas edge (as defined by the first two parameters), and it is 100 pixels wide and 150 pixels tall (as defined by the third and fourth parameters).
3. Let's add another rectangle into the mix β a green one this time. Add the following at the bottom of your JavaScript:
```js
ctx.fillStyle = "rgb(0 255 0)";
ctx.fillRect(75, 75, 100, 100);
```
Save and refresh, and you'll see your new rectangle. This raises an important point: graphics operations like drawing rectangles, lines, and so forth are performed in the order in which they occur. Think of it like painting a wall, where each coat of paint overlaps and may even hide what's underneath. You can't do anything to change this, so you have to think carefully about the order in which you draw the graphics.
4. Note that you can draw semi-transparent graphics by specifying a semi-transparent color, for example by using `rgb()`. The "alpha channel" defines the amount of transparency the color has. The higher its value, the more it will obscure whatever's behind it. Add the following to your code:
```js
ctx.fillStyle = "rgb(255 0 255 / 75%)";
ctx.fillRect(25, 100, 175, 50);
```
5. Now try drawing some more rectangles of your own; have fun!
### Strokes and line widths
So far we've looked at drawing filled rectangles, but you can also draw rectangles that are just outlines (called **strokes** in graphic design). To set the color you want for your stroke, you use the `strokeStyle` property; drawing a stroke rectangle is done using `strokeRect`.
1. Add the following to the previous example, again below the previous JavaScript lines:
```js
ctx.strokeStyle = "rgb(255 255 255)";
ctx.strokeRect(25, 25, 175, 200);
```
2. The default width of strokes is 1 pixel; you can adjust the `lineWidth` property value to change this (it takes a number representing the number of pixels wide the stroke is). Add the following line in between the previous two lines:
```js
ctx.lineWidth = 5;
```
Now you should see that your white outline has become much thicker! That's it for now. At this point your example should look like this:
**Note:** The finished code is available on GitHub as 2\_canvas\_rectangles.
### Drawing paths
If you want to draw anything more complex than a rectangle, you need to draw a path. Basically, this involves writing code to specify exactly what path the pen should move along on your canvas to trace the shape you want to draw. Canvas includes functions for drawing straight lines, circles, BΓ©zier curves, and more.
Let's start the section off by making a fresh copy of our canvas template (1\_canvas\_template), in which to draw the new example.
We'll be using some common methods and properties across all of the below sections:
* `beginPath()` β start drawing a path at the point where the pen currently is on the canvas. On a new canvas, the pen starts out at (0, 0).
* `moveTo()` β move the pen to a different point on the canvas, without recording or tracing the line; the pen "jumps" to the new position.
* `fill()` β draw a filled shape by filling in the path you've traced so far.
* `stroke()` β draw an outline shape by drawing a stroke along the path you've drawn so far.
* You can also use features like `lineWidth` and `fillStyle`/`strokeStyle` with paths as well as rectangles.
A typical, simple path-drawing operation would look something like so:
```js
ctx.fillStyle = "rgb(255 0 0)";
ctx.beginPath();
ctx.moveTo(50, 50);
// draw your path
ctx.fill();
```
#### Drawing lines
Let's draw an equilateral triangle on the canvas.
1. First of all, add the following helper function to the bottom of your code. This converts degree values to radians, which is useful because whenever you need to provide an angle value in JavaScript, it will nearly always be in radians, but humans usually think in degrees.
```js
function degToRad(degrees) {
return (degrees \* Math.PI) / 180;
}
```
2. Next, start off your path by adding the following below your previous addition; here we set a color for our triangle, start drawing a path, and then move the pen to (50, 50) without drawing anything. That's where we'll start drawing our triangle.
```js
ctx.fillStyle = "rgb(255 0 0)";
ctx.beginPath();
ctx.moveTo(50, 50);
```
3. Now add the following lines at the bottom of your script:
```js
ctx.lineTo(150, 50);
const triHeight = 50 \* Math.tan(degToRad(60));
ctx.lineTo(100, 50 + triHeight);
ctx.lineTo(50, 50);
ctx.fill();
```
Let's run through this in order:
First we draw a line across to (150, 50) β our path now goes 100 pixels to the right along the x axis.
Second, we work out the height of our equilateral triangle, using a bit of simple trigonometry. Basically, we are drawing the triangle pointing downwards. The angles in an equilateral triangle are always 60 degrees; to work out the height we can split it down the middle into two right-angled triangles, which will each have angles of 90 degrees, 60 degrees, and 30 degrees. In terms of the sides:
* The longest side is called the **hypotenuse**
* The side next to the 60 degree angle is called the **adjacent** β which we know is 50 pixels, as it is half of the line we just drew.
* The side opposite the 60 degree angle is called the **opposite**, which is the height of the triangle we want to calculate.![An equilateral triangle pointing downwards with labeled angles and sides. The horizontal line at the top is labeled 'adjacent'. A perpendicular dotted line, from the middle of the adjacent line, labeled 'opposite', splits the triangle creating two equal right triangles. The right side of the triangle is labeled the hypotenuse, as it is the hypotenuse of the right triangle formed by the line labeled 'opposite'. while all three-sided of the triangle are of equal length, the hypotenuse is the longest side of the right triangle.](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Drawing_graphics/trigonometry.png)
One of the basic trigonometric formulae states that the length of the adjacent multiplied by the tangent of the angle is equal to the opposite, hence we come up with `50 * Math.tan(degToRad(60))`. We use our `degToRad()` function to convert 60 degrees to radians, as `Math.tan()` expects an input value in radians.
4. With the height calculated, we draw another line to `(100, 50 + triHeight)`. The X coordinate is simple; it must be halfway between the previous two X values we set. The Y value on the other hand must be 50 plus the triangle height, as we know the top of the triangle is 50 pixels from the top of the canvas.
5. The next line draws a line back to the starting point of the triangle.
6. Last of all, we run `ctx.fill()` to end the path and fill in the shape.
#### Drawing circles
Now let's look at how to draw a circle in canvas. This is accomplished using the `arc()` method, which draws all or part of a circle at a specified point.
1. Let's add an arc to our canvas β add the following to the bottom of your code:
```js
ctx.fillStyle = "rgb(0 0 255)";
ctx.beginPath();
ctx.arc(150, 106, 50, degToRad(0), degToRad(360), false);
ctx.fill();
```
`arc()` takes six parameters. The first two specify the position of the arc's center (X and Y, respectively). The third is the circle's radius, the fourth and fifth are the start and end angles at which to draw the circle (so specifying 0 and 360 degrees gives us a full circle), and the sixth parameter defines whether the circle should be drawn counterclockwise (anticlockwise) or clockwise (`false` is clockwise).
**Note:** 0 degrees is horizontally to the right.
2. Let's try adding another arc:
```js
ctx.fillStyle = "yellow";
ctx.beginPath();
ctx.arc(200, 106, 50, degToRad(-45), degToRad(45), true);
ctx.lineTo(200, 106);
ctx.fill();
```
The pattern here is very similar, but with two differences:
* We have set the last parameter of `arc()` to `true`, meaning that the arc is drawn counterclockwise, which means that even though the arc is specified as starting at -45 degrees and ending at 45 degrees, we draw the arc around the 270 degrees not inside this portion. If you were to change `true` to `false` and then re-run the code, only the 90 degree slice of the circle would be drawn.
* Before calling `fill()`, we draw a line to the center of the circle. This means that we get the rather nice Pac-Man-style cutout rendered. If you removed this line (try it!) then re-ran the code, you'd get just an edge of the circle chopped off between the start and end point of the arc. This illustrates another important point of the canvas β if you try to fill an incomplete path (i.e. one that is not closed), the browser fills in a straight line between the start and end point and then fills it in.
That's it for now; your final example should look like this:
**Note:** The finished code is available on GitHub as 3\_canvas\_paths.
**Note:** To find out more about advanced path drawing features such as BΓ©zier curves, check out our Drawing shapes with canvas tutorial.
### Text
Canvas also has features for drawing text. Let's explore these briefly. Start by making another fresh copy of our canvas template (1\_canvas\_template) in which to draw the new example.
Text is drawn using two methods:
* `fillText()` β draws filled text.
* `strokeText()` β draws outline (stroke) text.
Both of these take three properties in their basic usage: the text string to draw and the X and Y coordinates of the point to start drawing the text at. This works out as the **bottom left** corner of the **text box** (literally, the box surrounding the text you draw), which might confuse you as other drawing operations tend to start from the top left corner β bear this in mind.
There are also a number of properties to help control text rendering such as `font`, which lets you specify font family, size, etc. It takes as its value the same syntax as the CSS `font` property.
Canvas content is not accessible to screen readers. Text painted to the canvas is not available to the DOM, but must be made available to be accessible. In this example, we include the text as the value for `aria-label`.
Try adding the following block to the bottom of your JavaScript:
```js
ctx.strokeStyle = "white";
ctx.lineWidth = 1;
ctx.font = "36px arial";
ctx.strokeText("Canvas text", 50, 50);
ctx.fillStyle = "red";
ctx.font = "48px georgia";
ctx.fillText("Canvas text", 50, 150);
canvas.setAttribute("aria-label", "Canvas text");
```
Here we draw two lines of text, one outline and the other stroke. The final example should look like so:
**Note:** The finished code is available on GitHub as 4\_canvas\_text.
Have a play and see what you can come up with! You can find more information on the options available for canvas text at Drawing text.
### Drawing images onto canvas
It is possible to render external images onto your canvas. These can be simple images, frames from videos, or the content of other canvases. For the moment we'll just look at the case of using some simple images on our canvas.
1. As before, make another fresh copy of our canvas template (1\_canvas\_template) in which to draw the new example.
Images are drawn onto canvas using the `drawImage()` method. The simplest version takes three parameters β a reference to the image you want to render, and the X and Y coordinates of the image's top left corner.
2. Let's start by getting an image source to embed in our canvas. Add the following lines to the bottom of your JavaScript:
```js
const image = new Image();
image.src = "firefox.png";
```
Here we create a new `HTMLImageElement` object using the `Image()` constructor. The returned object is the same type as that which is returned when you grab a reference to an existing `<img>` element. We then set its `src` attribute to equal our Firefox logo image. At this point, the browser starts loading the image.
3. We could now try to embed the image using `drawImage()`, but we need to make sure the image file has been loaded first, otherwise the code will fail. We can achieve this using the `load` event, which will only be fired when the image has finished loading. Add the following block below the previous one:
```js
image.addEventListener("load", () => ctx.drawImage(image, 20, 20));
```
If you load your example in the browser now, you should see the image embedded in the canvas.
4. But there's more! What if we want to display only a part of the image, or to resize it? We can do both with the more complex version of `drawImage()`. Update your `ctx.drawImage()` line like so:
```js
ctx.drawImage(image, 20, 20, 185, 175, 50, 50, 185, 175);
```
* The first parameter is the image reference, as before.
* Parameters 2 and 3 define the coordinates of the top left corner of the area you want to cut out of the loaded image, relative to the top-left corner of the image itself. Nothing to the left of the first parameter or above the second will be drawn.
* Parameters 4 and 5 define the width and height of the area we want to cut out from the original image we loaded.
* Parameters 6 and 7 define the coordinates at which you want to draw the top-left corner of the cut-out portion of the image, relative to the top-left corner of the canvas.
* Parameters 8 and 9 define the width and height to draw the cut-out area of the image. In this case, we have specified the same dimensions as the original slice, but you could resize it by specifying different values.
5. When the image is meaningfully updated, the accessible description must also be updated.
```js
canvas.setAttribute("aria-label", "Firefox Logo");
```
The final example should look like so:
**Note:** The finished code is available on GitHub as 5\_canvas\_images.
Loops and animations
--------------------
We have so far covered some very basic uses of 2D canvas, but really you won't experience the full power of canvas unless you update or animate it in some way. After all, canvas does provide scriptable images! If you aren't going to change anything, then you might as well just use static images and save yourself all the work.
### Creating a loop
Playing with loops in canvas is rather fun β you can run canvas commands inside a `for` (or other type of) loop just like any other JavaScript code.
Let's build a simple example.
1. Make another fresh copy of our canvas template (1\_canvas\_template) and open it in your code editor.
2. Add the following line to the bottom of your JavaScript. This contains a new method, `translate()`, which moves the origin point of the canvas:
```js
ctx.translate(width / 2, height / 2);
```
This causes the coordinate origin (0, 0) to be moved to the center of the canvas, rather than being at the top left corner. This is very useful in many situations, like this one, where we want our design to be drawn relative to the center of the canvas.
3. Now add the following code to the bottom of the JavaScript:
```js
function degToRad(degrees) {
return (degrees \* Math.PI) / 180;
}
function rand(min, max) {
return Math.floor(Math.random() \* (max - min + 1)) + min;
}
let length = 250;
let moveOffset = 20;
for (let i = 0; i < length; i++) {}
```
Here we are implementing the same `degToRad()` function we saw in the triangle example above, a `rand()` function that returns a random number between given lower and upper bounds, `length` and `moveOffset` variables (which we'll find out more about later), and an empty `for` loop.
4. The idea here is that we'll draw something on the canvas inside the `for` loop, and iterate on it each time so we can create something interesting. Add the following code inside your `for` loop:
```js
ctx.fillStyle = `rgb(${255 - length} 0 ${255 - length} / 90%)`;
ctx.beginPath();
ctx.moveTo(moveOffset, moveOffset);
ctx.lineTo(moveOffset + length, moveOffset);
const triHeight = (length / 2) \* Math.tan(degToRad(60));
ctx.lineTo(moveOffset + length / 2, moveOffset + triHeight);
ctx.lineTo(moveOffset, moveOffset);
ctx.fill();
length--;
moveOffset += 0.7;
ctx.rotate(degToRad(5));
```
So on each iteration, we:
* Set the `fillStyle` to be a shade of slightly transparent purple, which changes each time based on the value of `length`. As you'll see later the length gets smaller each time the loop runs, so the effect here is that the color gets brighter with each successive triangle drawn.
* Begin the path.
* Move the pen to a coordinate of `(moveOffset, moveOffset)`; This variable defines how far we want to move each time we draw a new triangle.
* Draw a line to a coordinate of `(moveOffset+length, moveOffset)`. This draws a line of length `length` parallel to the X axis.
* Calculate the triangle's height, as before.
* Draw a line to the downward-pointing corner of the triangle, then draw a line back to the start of the triangle.
* Call `fill()` to fill in the triangle.
* Update the variables that describe the sequence of triangles, so we can be ready to draw the next one. We decrease the `length` value by 1, so the triangles get smaller each time; increase `moveOffset` by a small amount so each successive triangle is slightly further away, and use another new function, `rotate()`, which allows us to rotate the entire canvas! We rotate it by 5 degrees before drawing the next triangle.
That's it! The final example should look like so:
At this point, we'd like to encourage you to play with the example and make it your own! For example:
* Draw rectangles or arcs instead of triangles, or even embed images.
* Play with the `length` and `moveOffset` values.
* Introduce some random numbers using that `rand()` function we included above but didn't use.
**Note:** The finished code is available on GitHub as 6\_canvas\_for\_loop.
### Animations
The loop example we built above was fun, but really you need a constant loop that keeps going and going for any serious canvas applications (such as games and real time visualizations). If you think of your canvas as being like a movie, you really want the display to update on each frame to show the updated view, with an ideal refresh rate of 60 frames per second so that movement appears nice and smooth to the human eye.
There are a few JavaScript functions that will allow you to run functions repeatedly, several times a second, the best one for our purposes here being `window.requestAnimationFrame()`. It takes one parameter β the name of the function you want to run for each frame. The next time the browser is ready to update the screen, your function will get called. If that function draws the new update to your animation, then calls `requestAnimationFrame()` again just before the end of the function, the animation loop will continue to run. The loop ends when you stop calling `requestAnimationFrame()` or if you call `window.cancelAnimationFrame()` after calling `requestAnimationFrame()` but before the frame is called.
**Note:** It's good practice to call `cancelAnimationFrame()` from your main code when you're done using the animation, to ensure that no updates are still waiting to be run.
The browser works out complex details such as making the animation run at a consistent speed, and not wasting resources animating things that can't be seen.
To see how it works, let's quickly look again at our Bouncing Balls example (see it live, and also see the source code). The code for the loop that keeps everything moving looks like this:
```js
function loop() {
ctx.fillStyle = "rgb(0 0 0 / 25%)";
ctx.fillRect(0, 0, width, height);
for (const ball of balls) {
ball.draw();
ball.update();
ball.collisionDetect();
}
requestAnimationFrame(loop);
}
loop();
```
We run the `loop()` function once at the bottom of the code to start the cycle, drawing the first animation frame; the `loop()` function then takes charge of calling `requestAnimationFrame(loop)` to run the next frame of the animation, again and again.
Note that on each frame we are completely clearing the canvas and redrawing everything. For every ball present we draw it, update its position, and check to see if it is colliding with any other balls. Once you've drawn a graphic to a canvas, there's no way to manipulate that graphic individually like you can with DOM elements. You can't move each ball around on the canvas, because once it's drawn, it's part of the canvas, and is not an individual accessible element or object. Instead, you have to erase and redraw, either by erasing the entire frame and redrawing everything, or by having code that knows exactly what parts need to be erased and only erases and redraws the minimum area of the canvas necessary.
Optimizing animation of graphics is an entire specialty of programming, with lots of clever techniques available. Those are beyond what we need for our example, though!
In general, the process of doing a canvas animation involves the following steps:
1. Clear the canvas contents (e.g. with `fillRect()` or `clearRect()`).
2. Save state (if necessary) using `save()` β this is needed when you want to save settings you've updated on the canvas before continuing, which is useful for more advanced applications.
3. Draw the graphics you are animating.
4. Restore the settings you saved in step 2, using `restore()`
5. Call `requestAnimationFrame()` to schedule drawing of the next frame of the animation.
**Note:** We won't cover `save()` and `restore()` here, but they are explained nicely in our Transformations tutorial (and the ones that follow it).
### A simple character animation
Now let's create our own simple animation β we'll get a character from a certain rather awesome retro computer game to walk across the screen.
1. Make another fresh copy of our canvas template (1\_canvas\_template) and open it in your code editor.
2. Update the inner HTML to reflect the image:
```html
<canvas class="myCanvas">
<p>A man walking.</p>
</canvas>
```
3. At the bottom of the JavaScript, add the following line to once again make the coordinate origin sit in the middle of the canvas:
```js
ctx.translate(width / 2, height / 2);
```
4. Now let's create a new `HTMLImageElement` object, set its `src` to the image we want to load, and add an `onload` event handler that will cause the `draw()` function to fire when the image is loaded:
```js
const image = new Image();
image.src = "walk-right.png";
image.onload = draw;
```
5. Now we'll add some variables to keep track of the position the sprite is to be drawn on the screen, and the sprite number we want to display.
```js
let sprite = 0;
let posX = 0;
```
Let's explain the spritesheet image (which we have respectfully borrowed from Mike Thomas' Walking cycle using CSS animation CodePen). The image looks like this:
![A sprite sheet with six sprite images of a pixelated character resembling a walking person from their right side at different instances of a single step forward. The character has a white shirt with sky blue buttons, black trousers, and black shoes. Each sprite is 102 pixels wide and 148 pixels high.](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Drawing_graphics/walk-right.png)
It contains six sprites that make up the whole walking sequence β each one is 102 pixels wide and 148 pixels high. To display each sprite cleanly we will have to use `drawImage()` to chop out a single sprite image from the spritesheet and display only that part, like we did above with the Firefox logo. The X coordinate of the slice will have to be a multiple of 102, and the Y coordinate will always be 0. The slice size will always be 102 by 148 pixels.
6. Now let's insert an empty `draw()` function at the bottom of the code, ready for filling up with some code:
```js
function draw() {}
```
7. The rest of the code in this section goes inside `draw()`. First, add the following line, which clears the canvas to prepare for drawing each frame. Notice that we have to specify the top-left corner of the rectangle as `-(width/2), -(height/2)` because we specified the origin position as `width/2, height/2` earlier on.
```js
ctx.fillRect(-(width / 2), -(height / 2), width, height);
```
8. Next, we'll draw our image using drawImage β the 9-parameter version. Add the following:
```js
ctx.drawImage(image, sprite \* 102, 0, 102, 148, 0 + posX, -74, 102, 148);
```
As you can see:
* We specify `image` as the image to embed.
* Parameters 2 and 3 specify the top-left corner of the slice to cut out of the source image, with the X value as `sprite` multiplied by 102 (where `sprite` is the sprite number between 0 and 5) and the Y value always 0.
* Parameters 4 and 5 specify the size of the slice to cut out β 102 pixels by 148 pixels.
* Parameters 6 and 7 specify the top-left corner of the box into which to draw the slice on the canvas β the X position is 0 + `posX`, meaning that we can alter the drawing position by altering the `posX` value.
* Parameters 8 and 9 specify the size of the image on the canvas. We just want to keep its original size, so we specify 102 and 148 as the width and height.
9. Now we'll alter the `sprite` value after each draw β well, after some of them anyway. Add the following block to the bottom of the `draw()` function:
```js
if (posX % 13 === 0) {
if (sprite === 5) {
sprite = 0;
} else {
sprite++;
}
}
```
We are wrapping the whole block in `if (posX % 13 === 0) { }`. We use the modulo (`%`) operator (also known as the remainder operator) to check whether the `posX` value can be exactly divided by 13 with no remainder. If so, we move on to the next sprite by incrementing `sprite` (wrapping to 0 after we're done with sprite #5). This effectively means that we are only updating the sprite on every 13th frame, or roughly about 5 frames a second (`requestAnimationFrame()` calls us at up to 60 frames per second if possible). We are deliberately slowing down the frame rate because we only have six sprites to work with, and if we display one every 60th of a second, our character will move way too fast!
Inside the outer block we use an `if...else` statement to check whether the `sprite` value is at 5 (the last sprite, given that the sprite numbers run from 0 to 5). If we are showing the last sprite already, we reset `sprite` back to 0; if not we just increment it by 1.
10. Next we need to work out how to change the `posX` value on each frame β add the following code block just below your last one.
```js
if (posX > width / 2) {
let newStartPos = -(width / 2 + 102);
posX = Math.ceil(newStartPos);
console.log(posX);
} else {
posX += 2;
}
```
We are using another `if...else` statement to see if the value of `posX` has become greater than `width/2`, which means our character has walked off the right edge of the screen. If so, we calculate a position that would put the character just to the left of the left side of the screen.
If our character hasn't yet walked off the edge of the screen, we increment `posX` by 2. This will make him move a little bit to the right the next time we draw him.
11. Finally, we need to make the animation loop by calling `requestAnimationFrame()` at the bottom of the `draw()` function:
```js
window.requestAnimationFrame(draw);
```
That's it! The final example should look like so:
**Note:** The finished code is available on GitHub as 7\_canvas\_walking\_animation.
### A simple drawing application
As a final animation example, we'd like to show you a very simple drawing application, to illustrate how the animation loop can be combined with user input (like mouse movement, in this case). We won't get you to walk through and build this one; we'll just explore the most interesting parts of the code.
The example can be found on GitHub as 8\_canvas\_drawing\_app, and you can play with it live below:
Let's look at the most interesting parts. First of all, we keep track of the mouse's X and Y coordinates and whether it is being clicked or not with three variables: `curX`, `curY`, and `pressed`. When the mouse moves, we fire a function set as the `onmousemove` event handler, which captures the current X and Y values. We also use `onmousedown` and `onmouseup` event handlers to change the value of `pressed` to `true` when the mouse button is pressed, and back to `false` again when it is released.
```js
let curX;
let curY;
let pressed = false;
// update mouse pointer coordinates
document.addEventListener("mousemove", (e) => {
curX = e.pageX;
curY = e.pageY;
});
canvas.addEventListener("mousedown", () => (pressed = true));
canvas.addEventListener("mouseup", () => (pressed = false));
```
When the "Clear canvas" button is pressed, we run a simple function that clears the whole canvas back to black, the same way we've seen before:
```js
clearBtn.addEventListener("click", () => {
ctx.fillStyle = "rgb(0 0 0)";
ctx.fillRect(0, 0, width, height);
});
```
The drawing loop is pretty simple this time around β if pressed is `true`, we draw a circle with a fill style equal to the value in the color picker, and a radius equal to the value set in the range input. We have to draw the circle 85 pixels above where we measured it from, because the vertical measurement is taken from the top of the viewport, but we are drawing the circle relative to the top of the canvas, which starts below the 85 pixel-high toolbar. If we drew it with just `curY` as the y coordinate, it would appear 85 pixels lower than the mouse position.
```js
function draw() {
if (pressed) {
ctx.fillStyle = colorPicker.value;
ctx.beginPath();
ctx.arc(
curX,
curY - 85,
sizePicker.value,
degToRad(0),
degToRad(360),
false,
);
ctx.fill();
}
requestAnimationFrame(draw);
}
draw();
```
All `<input>` types are well supported. If a browser doesn't support an input type, it will fall back to a plain text fields.
WebGL
-----
It's now time to leave 2D behind, and take a quick look at 3D canvas. 3D canvas content is specified using the WebGL API, which is a completely separate API from the 2D canvas API, even though they both render onto `<canvas>` elements.
WebGL is based on OpenGL (Open Graphics Library), and allows you to communicate directly with the computer's GPU. As such, writing raw WebGL is closer to low level languages such as C++ than regular JavaScript; it is quite complex but incredibly powerful.
### Using a library
Because of its complexity, most people write 3D graphics code using a third party JavaScript library such as Three.js, PlayCanvas, or Babylon.js. Most of these work in a similar way, providing functionality to create primitive and custom shapes, position viewing cameras and lighting, covering surfaces with textures, and more. They handle the WebGL for you, letting you work on a higher level.
Yes, using one of these means learning another new API (a third party one, in this case), but they are a lot simpler than coding raw WebGL.
### Recreating our cube
Let's look at a simple example of how to create something with a WebGL library. We'll choose Three.js, as it is one of the most popular ones. In this tutorial we'll create the 3D spinning cube we saw earlier.
1. To start with, make a local copy of threejs-cube/index.html in a new folder, then save a copy of metal003.png in the same folder. This is the image we'll use as a surface texture for the cube later on.
2. Next, create a new file called `script.js`, again in the same folder as before.
3. Next, you need to download the three.min.js library and save it in the same directory as before.
4. Now we've got `three.js` attached to our page, we can start to write JavaScript that makes use of it into `script.js`. Let's start by creating a new scene β add the following into your `script.js` file:
```js
const scene = new THREE.Scene();
```
The `Scene()` constructor creates a new scene, which represents the whole 3D world we are trying to display.
5. Next, we need a **camera** so we can see the scene. In 3D imagery terms, the camera represents a viewer's position in the world. To create a camera, add the following lines next:
```js
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000,
);
camera.position.z = 5;
```
The `PerspectiveCamera()` constructor takes four arguments:
* The field of view: How wide the area in front of the camera is that should be visible onscreen, in degrees.
* The aspect ratio: Usually, this is the ratio of the scene's width divided by the scene's height. Using another value will distort the scene (which might be what you want, but usually isn't).
* The near plane: How close to the camera objects can be before we stop rendering them to the screen. Think about how when you move your fingertip closer and closer to the space between your eyes, eventually you can't see it anymore.
* The far plane: How far away things are from the camera before they are no longer rendered.We also set the camera's position to be 5 distance units out of the Z axis, which, like in CSS, is out of the screen towards you, the viewer.
6. The third vital ingredient is a renderer. This is an object that renders a given scene, as viewed through a given camera. We'll create one for now using the `WebGLRenderer()` constructor, but we'll not use it till later. Add the following lines next:
```js
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
```
The first line creates a new renderer, the second line sets the size at which the renderer will draw the camera's view, and the third line appends the `<canvas>` element created by the renderer to the document's `<body>`. Now anything the renderer draws will be displayed in our window.
7. Next, we want to create the cube we'll display on the canvas. Add the following chunk of code at the bottom of your JavaScript:
```js
let cube;
const loader = new THREE.TextureLoader();
loader.load("metal003.png", (texture) => {
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(2, 2);
const geometry = new THREE.BoxGeometry(2.4, 2.4, 2.4);
const material = new THREE.MeshLambertMaterial({ map: texture });
cube = new THREE.Mesh(geometry, material);
scene.add(cube);
draw();
});
```
There's a bit more to take in here, so let's go through it in stages:
* We first create a `cube` global variable so we can access our cube from anywhere in the code.
* Next, we create a new `TextureLoader` object, then call `load()` on it. `load()` takes two parameters in this case (although it can take more): the texture we want to load (our PNG), and a function that will run when the texture has loaded.
* Inside this function we use properties of the `texture` object to specify that we want a 2 x 2 repeat of the image wrapped around all sides of the cube. Next, we create a new `BoxGeometry` object and a new `MeshLambertMaterial` object, and bring them together in a `Mesh` to create our cube. An object typically requires a geometry (what shape it is) and a material (what its surface looks like).
* Last of all, we add our cube to the scene, then call our `draw()` function to start off the animation.
8. Before we get to defining `draw()`, we'll add a couple of lights to the scene, to liven things up a bit; add the following blocks next:
```js
const light = new THREE.AmbientLight("rgb(255 255 255)"); // soft white light
scene.add(light);
const spotLight = new THREE.SpotLight("rgb(255 255 255)");
spotLight.position.set(100, 1000, 1000);
spotLight.castShadow = true;
scene.add(spotLight);
```
An `AmbientLight` object is a kind of soft light that lightens the whole scene a bit, like the sun when you are outside. The `SpotLight` object, on the other hand, is a directional beam of light, more like a flashlight/torch (or a spotlight, in fact).
9. Last of all, let's add our `draw()` function to the bottom of the code:
```js
function draw() {
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
requestAnimationFrame(draw);
}
```
This is fairly intuitive; on each frame, we rotate our cube slightly on its X and Y axes, then render the scene as viewed by our camera, then finally call `requestAnimationFrame()` to schedule drawing our next frame.
Let's have another quick look at what the finished product should look like:
You can find the finished code on GitHub.
**Note:** In our GitHub repo you can also find another interesting 3D cube example β Three.js Video Cube (see it live also). This uses `getUserMedia()` to take a video stream from a computer web cam and project it onto the side of the cube as a texture!
Summary
-------
At this point, you should have a useful idea of the basics of graphics programming using Canvas and WebGL and what you can do with these APIs, as well as a good idea of where to go for further information. Have fun!
See also
--------
Here we have covered only the real basics of canvas β there is so much more to learn! The below articles will take you further.
* Canvas tutorial β A very detailed tutorial series explaining what you should know about 2D canvas in much more detail than was covered here. Essential reading.
* WebGL tutorial β A series that teaches the basics of raw WebGL programming.
* Building up a basic demo with Three.js β basic Three.js tutorial. We also have equivalent guides for PlayCanvas or Babylon.js.
* Game development β the landing page for web games development on MDN. There are some really useful tutorials and techniques available here related to 2D and 3D canvas β see the Techniques and Tutorials menu options.
Examples
--------
* Violent theremin β Uses the Web Audio API to generate sound, and canvas to generate a pretty visualization to go along with it.
* Voice change-o-matic β Uses a canvas to visualize real-time audio data from the Web Audio API.
* Previous
* Overview: Client-side web APIs
* Next |
Third-party APIs - Learn web development | Third-party APIs
================
* Previous
* Overview: Client-side web APIs
* Next
The APIs we've covered so far are built into the browser, but not all APIs are. Many large websites and services such as Google Maps, Twitter, Facebook, PayPal, etc. provide APIs allowing developers to make use of their data (e.g. displaying your twitter stream on your blog) or services (e.g. using Facebook login to log in your users). This article looks at the difference between browser APIs and 3rd party APIs and shows some typical uses of the latter.
| | |
| --- | --- |
| Prerequisites: |
JavaScript basics (see
first steps,
building blocks,
JavaScript objects),
the
basics of Client-side APIs |
| Objective: |
To learn how third-party APIs work, and how to use them to enhance your
websites.
|
What are third party APIs?
--------------------------
Third party APIs are APIs provided by third parties β generally companies such as Facebook, Twitter, or Google β to allow you to access their functionality via JavaScript and use it on your site. One of the most obvious examples is using mapping APIs to display custom maps on your pages.
Let's look at a Simple Mapquest API example, and use it to illustrate how third-party APIs differ from browser APIs.
**Note:** You might want to just get all our code examples at once, in which case you can then just search the repo for the example files you need in each section.
### They are found on third-party servers
Browser APIs are built into the browser β you can access them from JavaScript immediately. For example, the Web Audio API we saw in the Introductory article is accessed using the native `AudioContext` object. For example:
```js
const audioCtx = new AudioContext();
// β¦
const audioElement = document.querySelector("audio");
// β¦
const audioSource = audioCtx.createMediaElementSource(audioElement);
// etc.
```
Third party APIs, on the other hand, are located on third party servers. To access them from JavaScript you first need to connect to the API functionality and make it available on your page. This typically involves first linking to a JavaScript library available on the server via a `<script>` element, as seen in our Mapquest example:
```html
<script
src="https://api.mqcdn.com/sdk/mapquest-js/v1.3.2/mapquest.js"
defer></script>
<link
rel="stylesheet"
href="https://api.mqcdn.com/sdk/mapquest-js/v1.3.2/mapquest.css" />
```
You can then start using the objects available in that library. For example:
```js
const map = L.mapquest.map("map", {
center: [53.480759, -2.242631],
layers: L.mapquest.tileLayer("map"),
zoom: 12,
});
```
Here we are creating a variable to store the map information in, then creating a new map using the `mapquest.map()` method, which takes as its parameters the ID of a `<div>` element you want to display the map in ('map'), and an options object containing the details of the particular map we want to display. In this case we specify the coordinates of the center of the map, a map layer of type `map` to show (created using the `mapquest.tileLayer()` method), and the default zoom level.
This is all the information the Mapquest API needs to plot a simple map. The server you are connecting to handles all the complicated stuff, like displaying the correct map tiles for the area being shown, etc.
**Note:** Some APIs handle access to their functionality slightly differently, requiring the developer to make an HTTP request to a specific URL pattern to retrieve data. These are called RESTful APIs β we'll show an example later on.
### They usually require API keys
Security for browser APIs tends to be handled by permission prompts, as discussed in our first article. The purpose of these is so that the user knows what is going on in the websites they visit and is less likely to fall victim to someone using an API in a malicious way.
Third party APIs have a slightly different permissions system β they tend to use developer keys to allow developers access to the API functionality, which is more to protect the API vendor than the user.
You'll find a line similar to the following in the Mapquest API example:
```js
L.mapquest.key = "YOUR-API-KEY-HERE";
```
This line specifies an API or developer key to use in your application β the developer of the application must apply to get a key, and then include it in their code to be allowed access to the API's functionality. In our example we've just provided a placeholder.
**Note:** When creating your own examples, you'll use your own API key in place of any placeholder.
Other APIs may require that you include the key in a slightly different way, but the pattern is relatively similar for most of them.
Requiring a key enables the API provider to hold users of the API accountable for their actions. When the developer has registered for a key, they are then known to the API provider, and action can be taken if they start to do anything malicious with the API (such as tracking people's location or trying to spam the API with loads of requests to stop it working, for example). The easiest action would be to just revoke their API privileges.
Extending the Mapquest example
------------------------------
Let's add some more functionality to the Mapquest example to show how to use some other features of the API.
1. To start this section, make yourself a copy of the mapquest starter file, in a new directory. If you've already cloned the examples repository, you'll already have a copy of this file, which you can find in the *javascript/apis/third-party-apis/mapquest/start* directory.
2. Next, you need to go to the Mapquest developer site, create an account, and then create a developer key to use with your example. (At the time of writing, it was called a "consumer key" on the site, and the key creation process also asked for an optional "callback URL". You don't need to fill in a URL here: just leave it blank.)
3. Open up your starting file, and replace the API key placeholder with your key.
### Changing the type of map
There are a number of different types of map that can be shown with the Mapquest API. To do this, find the following line:
```js
layers: L.mapquest.tileLayer("map");
```
Try changing `'map'` to `'hybrid'` to show a hybrid-style map. Try some other values too. The `tileLayer` reference page shows the different available options, plus a lot more information.
### Adding different controls
The map has a number of different controls available; by default it just shows a zoom control. You can expand the controls available using the `map.addControl()` method; add this to your code:
```js
map.addControl(L.mapquest.control());
```
The `mapquest.control()` method just creates a simple full-featured control set, and it is placed in the top-right-hand corner by default. You can adjust the position by specifying an options object as a parameter for the control containing a `position` property, the value of which is a string specifying a position for the control. Try this, for example:
```js
map.addControl(L.mapquest.control({ position: "bottomright" }));
```
There are other types of control available, for example `mapquest.searchControl()` and `mapquest.satelliteControl()`, and some are quite complex and powerful. Have a play around and see what you can come up with.
### Adding a custom marker
Adding a marker (icon) at a certain point on the map is easy β you just use the `L.marker()` method (which seems to be documented in the related Leaflet.js docs). Add the following code to your example, again inside `window.onload`:
```js
L.marker([53.480759, -2.242631], {
icon: L.mapquest.icons.marker({
primaryColor: "#22407F",
secondaryColor: "#3B5998",
shadow: true,
size: "md",
symbol: "A",
}),
})
.bindPopup("This is Manchester!")
.addTo(map);
```
As you can see, this at its simplest takes two parameters, an array containing the coordinates at which to display the marker, and an options object containing an `icon` property that defines the icon to display at that point.
The icon is defined using an `mapquest.icons.marker()` method, which as you can see contains information such as color and size of marker.
Onto the end of the first method call we chain `.bindPopup('This is Manchester!')`, which defines content to display when the marker is clicked.
Finally, we chain `.addTo(map)` to the end of the chain to actually add the marker to the map.
Have a play with the other options shown in the documentation and see what you can come up with! Mapquest provides some pretty advanced functionality, such as directions, searching, etc.
**Note:** If you have trouble getting the example to work, check your code against our finished version.
A RESTful API β NYTimes
-----------------------
Now let's look at another API example β the New York Times API. This API allows you to retrieve New York Times news story information and display it on your site. This type of API is known as a **RESTful API** β instead of getting data using the features of a JavaScript library like we did with Mapquest, we get data by making HTTP requests to specific URLs, with data like search terms and other properties encoded in the URL (often as URL parameters). This is a common pattern you'll encounter with APIs.
An approach for using third-party APIs
--------------------------------------
Below we'll take you through an exercise to show you how to use the NYTimes API, which also provides a more general set of steps to follow that you can use as an approach for working with new APIs.
### Find the documentation
When you want to use a third party API, it is essential to find out where the documentation is, so you can find out what features the API has, how you use them, etc. The New York Times API documentation is at https://developer.nytimes.com/.
### Get a developer key
Most APIs require you to use some kind of developer key, for reasons of security and accountability. To sign up for an NYTimes API key, following the instructions at https://developer.nytimes.com/get-started.
1. Let's request a key for the Article Search API β create a new app, selecting this as the API you want to use (fill in a name and description, toggle the switch under the "Article Search API" to the on position, and then click "Create").
2. Get the API key from the resulting page.
3. Now, to start the example off, make a copy of all the files in the nytimes/start directory. If you've already cloned the examples repository, you'll already have a copy of these files, which you can find in the *javascript/apis/third-party-apis/nytimes/start* directory. Initially the `script.js` file contains a number of variables needed for the setup of the example; below we'll fill in the required functionality.
The app will end up allowing you to type in a search term and optional start and end dates, which it will then use to query the Article Search API and display the search results.
![A screenshot of a sample search query and search results as retrieved from the New York Article Search API.](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Third_party_APIs/nytimes-example.png)
### Connect the API to your app
First, you'll need to make a connection between the API and your app. In the case of this API, you need to include the API key as a get parameter every time you request data from the service at the correct URL.
1. Find the following line:
```js
const key = "INSERT-YOUR-API-KEY-HERE";
```
Replace the existing API key with the actual API key you got in the previous section.
2. Add the following line to your JavaScript, below the "`// Event listeners to control the functionality`" comment. This runs a function called `submitSearch()` when the form is submitted (the button is pressed).
```js
searchForm.addEventListener("submit", submitSearch);
```
3. Now add the `submitSearch()` and `fetchResults()` function definitions, below the previous line:
```js
function submitSearch(e) {
pageNumber = 0;
fetchResults(e);
}
function fetchResults(e) {
// Use preventDefault() to stop the form submitting
e.preventDefault();
// Assemble the full URL
let url = `${baseURL}?api-key=${key}&page=${pageNumber}&q=${searchTerm.value}&fq=document\_type:("article")`;
if (startDate.value !== "") {
url = `${url}&begin\_date=${startDate.value}`;
}
if (endDate.value !== "") {
url = `${url}&end\_date=${endDate.value}`;
}
}
```
`submitSearch()` sets the page number back to 0 to begin with, then calls `fetchResults()`. This first calls `preventDefault()` on the event object, to stop the form actually submitting (which would break the example). Next, we use some string manipulation to assemble the full URL that we will make the request to. We start off by assembling the parts we deem as mandatory for this demo:
* The base URL (taken from the `baseURL` variable).
* The API key, which has to be specified in the `api-key` URL parameter (the value is taken from the `key` variable).
* The page number, which has to be specified in the `page` URL parameter (the value is taken from the `pageNumber` variable).
* The search term, which has to be specified in the `q` URL parameter (the value is taken from the value of the `searchTerm` text `<input>`).
* The document type to return results for, as specified in an expression passed in via the `fq` URL parameter. In this case, we want to return articles.
Next, we use a couple of `if ()` statements to check whether the `startDate` and `endDate` elements have had values filled in on them. If they do, we append their values to the URL, specified in `begin_date` and `end_date` URL parameters respectively.
So, a complete URL would end up looking something like this:
```url
https://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=YOUR-API-KEY-HERE&page=0&q=cats&fq=document\_type:("article")&begin_date=20170301&end_date=20170312
```
**Note:** You can find more details of what URL parameters can be included at the NYTimes developer docs.
**Note:** The example has rudimentary form data validation β the search term field has to be filled in before the form can be submitted (achieved using the `required` attribute), and the date fields have `pattern` attributes specified, which means they won't submit unless their values consist of 8 numbers (`pattern="[0-9]{8}"`). See Form data validation for more details on how these work.
### Requesting data from the API
Now we've constructed our URL, let's make a request to it. We'll do this using the Fetch API.
Add the following code block inside the `fetchResults()` function, just above the closing curly brace:
```js
// Use fetch() to make the request to the API
fetch(url)
.then((response) => response.json())
.then((json) => displayResults(json))
.catch((error) => console.error(`Error fetching data: ${error.message}`));
```
Here we run the request by passing our `url` variable to `fetch()`, convert the response body to JSON using the `json()` function, then pass the resulting JSON to the `displayResults()` function so the data can be displayed in our UI. We also catch and log any errors that might be thrown.
### Displaying the data
OK, let's look at how we'll display the data. Add the following function below your `fetchResults()` function.
```js
function displayResults(json) {
while (section.firstChild) {
section.removeChild(section.firstChild);
}
const articles = json.response.docs;
nav.style.display = articles.length === 10 ? "block" : "none";
if (articles.length === 0) {
const para = document.createElement("p");
para.textContent = "No results returned.";
section.appendChild(para);
} else {
for (const current of articles) {
const article = document.createElement("article");
const heading = document.createElement("h2");
const link = document.createElement("a");
const img = document.createElement("img");
const para1 = document.createElement("p");
const keywordPara = document.createElement("p");
keywordPara.classList.add("keywords");
console.log(current);
link.href = current.web_url;
link.textContent = current.headline.main;
para1.textContent = current.snippet;
keywordPara.textContent = "Keywords: ";
for (const keyword of current.keywords) {
const span = document.createElement("span");
span.textContent = `${keyword.value} `;
keywordPara.appendChild(span);
}
if (current.multimedia.length > 0) {
img.src = `http://www.nytimes.com/${current.multimedia[0].url}`;
img.alt = current.headline.main;
}
article.appendChild(heading);
heading.appendChild(link);
article.appendChild(img);
article.appendChild(para1);
article.appendChild(keywordPara);
section.appendChild(article);
}
}
}
```
There's a lot of code here; let's explain it step by step:
* The `while` loop is a common pattern used to delete all of the contents of a DOM element, in this case, the `<section>` element. We keep checking to see if the `<section>` has a first child, and if it does, we remove the first child. The loop ends when `<section>` no longer has any children.
* Next, we set the `articles` variable to equal `json.response.docs` β this is the array holding all the objects that represent the articles returned by the search. This is done purely to make the following code a bit simpler.
* The first `if ()` block checks to see if 10 articles are returned (the API returns up to 10 articles at a time.) If so, we display the `<nav>` that contains the *Previous 10*/*Next 10* pagination buttons. If fewer than 10 articles are returned, they will all fit on one page, so we don't need to show the pagination buttons. We will wire up the pagination functionality in the next section.
* The next `if ()` block checks to see if no articles are returned. If so, we don't try to display any β we create a `<p>` containing the text "No results returned." and insert it into the `<section>`.
* If some articles are returned, we, first of all, create all the elements that we want to use to display each news story, insert the right contents into each one, and then insert them into the DOM at the appropriate places. To work out which properties in the article objects contained the right data to show, we consulted the Article Search API reference (see NYTimes APIs). Most of these operations are fairly obvious, but a few are worth calling out:
+ We used a `for...of` loop to go through all the keywords associated with each article, and insert each one inside its own `<span>`, inside a `<p>`. This was done to make it easy to style each one.
+ We used an `if ()` block (`if (current.multimedia.length > 0) { }`) to check whether each article has any images associated with it, as some stories don't. We display the first image only if it exists; otherwise, an error would be thrown.
### Wiring up the pagination buttons
To make the pagination buttons work, we will increment (or decrement) the value of the `pageNumber` variable, and then re-rerun the fetch request with the new value included in the page URL parameter. This works because the NYTimes API only returns 10 results at a time β if more than 10 results are available, it will return the first 10 (0-9) if the `page` URL parameter is set to 0 (or not included at all β 0 is the default value), the next 10 (10-19) if it is set to 1, and so on.
This allows us to write a simplistic pagination function.
1. Below the existing `addEventListener()` call, add these two new ones, which cause the `nextPage()` and `previousPage()` functions to be invoked when the relevant buttons are clicked:
```js
nextBtn.addEventListener("click", nextPage);
previousBtn.addEventListener("click", previousPage);
```
2. Below your previous addition, let's define the two functions β add this code now:
```js
function nextPage(e) {
pageNumber++;
fetchResults(e);
}
function previousPage(e) {
if (pageNumber > 0) {
pageNumber--;
} else {
return;
}
fetchResults(e);
}
```
The first function increments the `pageNumber` variable, then run the `fetchResults()` function again to display the next page's results.
The second function works nearly exactly the same way in reverse, but we also have to take the extra step of checking that `pageNumber` is not already zero before decrementing it β if the fetch request runs with a minus `page` URL parameter, it could cause errors. If the `pageNumber` is already 0, we `return` out of the function β if we are already at the first page, we don't need to load the same results again.
**Note:** You can find our finished NYTimes API example code on GitHub (also see it running live here).
YouTube example
---------------
We also built another example for you to study and learn from β see our YouTube video search example. This uses two related APIs:
* The YouTube Data API to search for YouTube videos and return results.
* The YouTube IFrame Player API to display the returned video examples inside IFrame video players so you can watch them.
This example is interesting because it shows two related third-party APIs being used together to build an app. The first one is a RESTful API, while the second one works more like Mapquest (with API-specific methods, etc.). It is worth noting however that both of the APIs require a JavaScript library to be applied to the page. The RESTful API has functions available to handle making the HTTP requests and returning the results.
![A screenshot of a sample Youtube video search using two related APIs. The left side of the image has a sample search query using the YouTube Data API. The right side of the image displays the search results using the Youtube Iframe Player API.](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Third_party_APIs/youtube-example.png)
We are not going to say too much more about this example in the article β the source code has detailed comments inserted inside it to explain how it works.
To get it running, you'll need to:
* Read the YouTube Data API Overview documentation.
* Make sure you visit the Enabled APIs page, and in the list of APIs, make sure the status is ON for the YouTube Data API v3.
* Get an API key from Google Cloud.
* Find the string `ENTER-API-KEY-HERE` in the source code, and replace it with your API key.
* Run the example through a web server. It won't work if you just run it directly in the browser (i.e. via a `file://` URL).
Summary
-------
This article has given you a useful introduction to using third-party APIs to add functionality to your websites.
* Previous
* Overview: Client-side web APIs
* Next |
Client-side storage - Learn web development | Client-side storage
===================
* Previous
* Overview: Client-side web APIs
Modern web browsers support a number of ways for websites to store data on the user's computer β with the user's permission β then retrieve it when necessary. This lets you persist data for long-term storage, save sites or documents for offline use, retain user-specific settings for your site, and more. This article explains the very basics of how these work.
| | |
| --- | --- |
| Prerequisites: |
JavaScript basics (see
first steps,
building blocks,
JavaScript objects),
the
basics of Client-side APIs |
| Objective: | To learn how to use client-side storage APIs to store application data. |
Client-side storage?
--------------------
Elsewhere in the MDN learning area, we talked about the difference between static sites and dynamic sites. Most major modern websites are dynamic β they store data on the server using some kind of database (server-side storage), then run server-side code to retrieve needed data, insert it into static page templates, and serve the resulting HTML to the client to be displayed by the user's browser.
Client-side storage works on similar principles, but has different uses. It consists of JavaScript APIs that allow you to store data on the client (i.e. on the user's machine) and then retrieve it when needed. This has many distinct uses, such as:
* Personalizing site preferences (e.g. showing a user's choice of custom widgets, color scheme, or font size).
* Persisting previous site activity (e.g. storing the contents of a shopping cart from a previous session, remembering if a user was previously logged in).
* Saving data and assets locally so a site will be quicker (and potentially less expensive) to download, or be usable without a network connection.
* Saving web application generated documents locally for use offline
Often client-side and server-side storage are used together. For example, you could download a batch of music files (perhaps used by a web game or music player application), store them inside a client-side database, and play them as needed. The user would only have to download the music files once β on subsequent visits they would be retrieved from the database instead.
**Note:** There are limits to the amount of data you can store using client-side storage APIs (possibly both per individual API and cumulatively); the exact limit varies depending on the browser and possibly based on user settings. See Browser storage quotas and eviction criteria for more information.
### Old school: Cookies
The concept of client-side storage has been around for a long time. Since the early days of the web, sites have used cookies to store information to personalize user experience on websites. They're the earliest form of client-side storage commonly used on the web.
These days, there are easier mechanisms available for storing client-side data, therefore we won't be teaching you how to use cookies in this article. However, this does not mean cookies are completely useless on the modern-day web β they are still used commonly to store data related to user personalization and state, e.g. session IDs and access tokens. For more information on cookies see our Using HTTP cookies article.
### New school: Web Storage and IndexedDB
The "easier" features we mentioned above are as follows:
* The Web Storage API provides a mechanism for storing and retrieving smaller, data items consisting of a name and a corresponding value. This is useful when you just need to store some simple data, like the user's name, whether they are logged in, what color to use for the background of the screen, etc.
* The IndexedDB API provides the browser with a complete database system for storing complex data. This can be used for things from complete sets of customer records to even complex data types like audio or video files.
You'll learn more about these APIs below.
### The Cache API
The `Cache` API is designed for storing HTTP responses to specific requests, and is very useful for doing things like storing website assets offline so the site can subsequently be used without a network connection. Cache is usually used in combination with the Service Worker API, although it doesn't have to be.
The use of Cache and Service Workers is an advanced topic, and we won't be covering it in great detail in this article, although we will show an example in the Offline asset storage section below.
Storing simple data β web storage
---------------------------------
The Web Storage API is very easy to use β you store simple name/value pairs of data (limited to strings, numbers, etc.) and retrieve these values when needed.
### Basic syntax
Let's show you how:
1. First, go to our web storage blank template on GitHub (open this in a new tab).
2. Open the JavaScript console of your browser's developer tools.
3. All of your web storage data is contained within two object-like structures inside the browser: `sessionStorage` and `localStorage`. The first one persists data for as long as the browser is open (the data is lost when the browser is closed) and the second one persists data even after the browser is closed and then opened again. We'll use the second one in this article as it is generally more useful.
The `Storage.setItem()` method allows you to save a data item in storage β it takes two parameters: the name of the item, and its value. Try typing this into your JavaScript console (change the value to your own name, if you wish!):
```js
localStorage.setItem("name", "Chris");
```
4. The `Storage.getItem()` method takes one parameter β the name of a data item you want to retrieve β and returns the item's value. Now type these lines into your JavaScript console:
```js
let myName = localStorage.getItem("name");
myName;
```
Upon typing in the second line, you should see that the `myName` variable now contains the value of the `name` data item.
5. The `Storage.removeItem()` method takes one parameter β the name of a data item you want to remove β and removes that item out of web storage. Type the following lines into your JavaScript console:
```js
localStorage.removeItem("name");
myName = localStorage.getItem("name");
myName;
```
The third line should now return `null` β the `name` item no longer exists in the web storage.
### The data persists!
One key feature of web storage is that the data persists between page loads (and even when the browser is shut down, in the case of `localStorage`). Let's look at this in action.
1. Open our web storage blank template again, but this time in a different browser to the one you've got this tutorial open in! This will make it easier to deal with.
2. Type these lines into the browser's JavaScript console:
```js
localStorage.setItem("name", "Chris");
let myName = localStorage.getItem("name");
myName;
```
You should see the name item returned.
3. Now close down the browser and open it up again.
4. Enter the following lines again:
```js
let myName = localStorage.getItem("name");
myName;
```
You should see that the value is still available, even though the browser has been closed and then opened again.
### Separate storage for each domain
There is a separate data store for each domain (each separate web address loaded in the browser). You will see that if you load two websites (say google.com and amazon.com) and try storing an item on one website, it won't be available to the other website.
This makes sense β you can imagine the security issues that would arise if websites could see each other's data!
### A more involved example
Let's apply this new-found knowledge by writing a working example to give you an idea of how web storage can be used. Our example will allow you to enter a name, after which the page will update to give you a personalized greeting. This state will also persist across page/browser reloads, because the name is stored in web storage.
You can find the example HTML at personal-greeting.html β this contains a website with a header, content, and footer, and a form for entering your name.
![A Screenshot of a website that has a header, content and footer sections. The header has a welcome text to the left-hand side and a button labelled 'forget' to the right-hand side. The content has an heading followed by a two paragraphs of dummy text. The footer reads 'Copyright nobody. Use the code as you like'.](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage/web-storage-demo.png)
Let's build up the example, so you can understand how it works.
1. First, make a local copy of our personal-greeting.html file in a new directory on your computer.
2. Next, note how our HTML references a JavaScript file called `index.js`, with a line like `<script src="index.js" defer></script>`. We need to create this and write our JavaScript code into it. Create an `index.js` file in the same directory as your HTML file.
3. We'll start off by creating references to all the HTML features we need to manipulate in this example β we'll create them all as constants, as these references do not need to change in the lifecycle of the app. Add the following lines to your JavaScript file:
```js
// create needed constants
const rememberDiv = document.querySelector(".remember");
const forgetDiv = document.querySelector(".forget");
const form = document.querySelector("form");
const nameInput = document.querySelector("#entername");
const submitBtn = document.querySelector("#submitname");
const forgetBtn = document.querySelector("#forgetname");
const h1 = document.querySelector("h1");
const personalGreeting = document.querySelector(".personal-greeting");
```
4. Next up, we need to include a small event listener to stop the form from actually submitting itself when the submit button is pressed, as this is not the behavior we want. Add this snippet below your previous code:
```js
// Stop the form from submitting when a button is pressed
form.addEventListener("submit", (e) => e.preventDefault());
```
5. Now we need to add an event listener, the handler function of which will run when the "Say hello" button is clicked. The comments explain in detail what each bit does, but in essence here we are taking the name the user has entered into the text input box and saving it in web storage using `setItem()`, then running a function called `nameDisplayCheck()` that will handle updating the actual website text. Add this to the bottom of your code:
```js
// run function when the 'Say hello' button is clicked
submitBtn.addEventListener("click", () => {
// store the entered name in web storage
localStorage.setItem("name", nameInput.value);
// run nameDisplayCheck() to sort out displaying the personalized greetings and updating the form display
nameDisplayCheck();
});
```
6. At this point we also need an event handler to run a function when the "Forget" button is clicked β this is only displayed after the "Say hello" button has been clicked (the two form states toggle back and forth). In this function we remove the `name` item from web storage using `removeItem()`, then again run `nameDisplayCheck()` to update the display. Add this to the bottom:
```js
// run function when the 'Forget' button is clicked
forgetBtn.addEventListener("click", () => {
// Remove the stored name from web storage
localStorage.removeItem("name");
// run nameDisplayCheck() to sort out displaying the generic greeting again and updating the form display
nameDisplayCheck();
});
```
7. It is now time to define the `nameDisplayCheck()` function itself. Here we check whether the name item has been stored in web storage by using `localStorage.getItem('name')` as a conditional test. If the name has been stored, this call will evaluate to `true`; if not, the call will evaluate to `false`. If the call evaluates to `true`, we display a personalized greeting, display the "forget" part of the form, and hide the "Say hello" part of the form. If the call evaluates to `false`, we display a generic greeting and do the opposite. Again, put the following code at the bottom:
```js
// define the nameDisplayCheck() function
function nameDisplayCheck() {
// check whether the 'name' data item is stored in web Storage
if (localStorage.getItem("name")) {
// If it is, display personalized greeting
const name = localStorage.getItem("name");
h1.textContent = `Welcome, ${name}`;
personalGreeting.textContent = `Welcome to our website, ${name}! We hope you have fun while you are here.`;
// hide the 'remember' part of the form and show the 'forget' part
forgetDiv.style.display = "block";
rememberDiv.style.display = "none";
} else {
// if not, display generic greeting
h1.textContent = "Welcome to our website ";
personalGreeting.textContent =
"Welcome to our website. We hope you have fun while you are here.";
// hide the 'forget' part of the form and show the 'remember' part
forgetDiv.style.display = "none";
rememberDiv.style.display = "block";
}
}
```
8. Last but not least, we need to run the `nameDisplayCheck()` function when the page is loaded. If we don't do this, then the personalized greeting will not persist across page reloads. Add the following to the bottom of your code:
```js
nameDisplayCheck();
```
Your example is finished β well done! All that remains now is to save your code and test your HTML page in a browser. You can see our finished version running live here.
**Note:** There is another, slightly more complex example to explore at Using the Web Storage API.
**Note:** In the line `<script src="index.js" defer></script>` of the source for our finished version, the `defer` attribute specifies that the contents of the `<script>` element will not execute until the page has finished loading.
Storing complex data β IndexedDB
--------------------------------
The IndexedDB API (sometimes abbreviated IDB) is a complete database system available in the browser in which you can store complex related data, the types of which aren't limited to simple values like strings or numbers. You can store videos, images, and pretty much anything else in an IndexedDB instance.
The IndexedDB API allows you to create a database, then create object stores within that database.
Object stores are like tables in a relational database, and each object store can contain a number of objects.
To learn more about the IndexedDB API, see Using IndexedDB.
However, this does come at a cost: IndexedDB is much more complex to use than the Web Storage API. In this section, we'll really only scratch the surface of what it is capable of, but we will give you enough to get started.
### Working through a note storage example
Here we'll run you through an example that allows you to store notes in your browser and view and delete them whenever you like, getting you to build it up for yourself and explaining the most fundamental parts of IDB as we go along.
The app looks something like this:
![IndexDB notes demo screenshot with 4 sections. The first section is the header. The second section lists all the notes that have been created. It has two notes, each with a delete button. A third section is a form with 2 input fields for 'Note title' and 'Note text' and a button labeled 'Create new note'. The bottom section footer reads 'Copyright nobody. Use the code as you like'.](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage/idb-demo.png)
Each note has a title and some body text, each individually editable. The JavaScript code we'll go through below has detailed comments to help you understand what's going on.
### Getting started
1. First of all, make local copies of our `index.html`, `style.css`, and `index-start.js` files into a new directory on your local machine.
2. Have a look at the files. You'll see that the HTML defines a website with a header and footer, as well as a main content area that contains a place to display notes, and a form for entering new notes into the database. The CSS provides some styling to make it clearer what is going on. The JavaScript file contains five declared constants containing references to the `<ul>` element the notes will be displayed in, the title and body `<input>` elements, the `<form>` itself, and the `<button>`.
3. Rename your JavaScript file to `index.js`. You are now ready to start adding code to it.
### Database initial setup
Now let's look at what we have to do in the first place, to actually set up a database.
1. Below the constant declarations, add the following lines:
```js
// Create an instance of a db object for us to store the open database in
let db;
```
Here we are declaring a variable called `db` β this will later be used to store an object representing our database. We will use this in a few places, so we've declared it globally here to make things easier.
2. Next, add the following:
```js
// Open our database; it is created if it doesn't already exist
// (see the upgradeneeded handler below)
const openRequest = window.indexedDB.open("notes\_db", 1);
```
This line creates a request to open version `1` of a database called `notes_db`. If this doesn't already exist, it will be created for you by subsequent code. You will see this request pattern used very often throughout IndexedDB. Database operations take time. You don't want to hang the browser while you wait for the results, so database operations are asynchronous, meaning that instead of happening immediately, they will happen at some point in the future, and you get notified when they're done.
To handle this in IndexedDB, you create a request object (which can be called anything you like β we called it `openRequest` here, so it is obvious what it is for). You then use event handlers to run code when the request completes, fails, etc., which you'll see in use below.
**Note:** The version number is important. If you want to upgrade your database (for example, by changing the table structure), you have to run your code again with an increased version number, different schema specified inside the `upgradeneeded` handler (see below), etc. We won't cover upgrading databases in this tutorial.
3. Now add the following event handlers just below your previous addition:
```js
// error handler signifies that the database didn't open successfully
openRequest.addEventListener("error", () =>
console.error("Database failed to open"),
);
// success handler signifies that the database opened successfully
openRequest.addEventListener("success", () => {
console.log("Database opened successfully");
// Store the opened database object in the db variable. This is used a lot below
db = openRequest.result;
// Run the displayData() function to display the notes already in the IDB
displayData();
});
```
The `error` event handler will run if the system comes back saying that the request failed. This allows you to respond to this problem. In our example, we just print a message to the JavaScript console.
The `success` event handler will run if the request returns successfully, meaning the database was successfully opened. If this is the case, an object representing the opened database becomes available in the `openRequest.result` property, allowing us to manipulate the database. We store this in the `db` variable we created earlier for later use. We also run a function called `displayData()`, which displays the data in the database inside the `<ul>`. We run it now so that the notes already in the database are displayed as soon as the page loads. You'll see `displayData()` defined later on.
4. Finally for this section, we'll add probably the most important event handler for setting up the database: `upgradeneeded`. This handler runs if the database has not already been set up, or if the database is opened with a bigger version number than the existing stored database (when performing an upgrade). Add the following code, below your previous handler:
```js
// Set up the database tables if this has not already been done
openRequest.addEventListener("upgradeneeded", (e) => {
// Grab a reference to the opened database
db = e.target.result;
// Create an objectStore in our database to store notes and an auto-incrementing key
// An objectStore is similar to a 'table' in a relational database
const objectStore = db.createObjectStore("notes\_os", {
keyPath: "id",
autoIncrement: true,
});
// Define what data items the objectStore will contain
objectStore.createIndex("title", "title", { unique: false });
objectStore.createIndex("body", "body", { unique: false });
console.log("Database setup complete");
});
```
This is where we define the schema (structure) of our database; that is, the set of columns (or fields) it contains. Here we first grab a reference to the existing database from the `result` property of the event's target (`e.target.result`), which is the `request` object. This is equivalent to the line `db = openRequest.result;` inside the `success` event handler, but we need to do this separately here because the `upgradeneeded` event handler (if needed) will run before the `success` event handler, meaning that the `db` value wouldn't be available if we didn't do this.
We then use `IDBDatabase.createObjectStore()` to create a new object store inside our opened database called `notes_os`. This is equivalent to a single table in a conventional database system. We've given it the name notes, and also specified an `autoIncrement` key field called `id` β in each new record this will automatically be given an incremented value β the developer doesn't need to set this explicitly. Being the key, the `id` field will be used to uniquely identify records, such as when deleting or displaying a record.
We also create two other indexes (fields) using the `IDBObjectStore.createIndex()` method: `title` (which will contain a title for each note), and `body` (which will contain the body text of the note).
So with this database schema set up, when we start adding records to the database, each one will be represented as an object along these lines:
```json
{
"title": "Buy milk",
"body": "Need both cows milk and soy.",
"id": 8
}
```
### Adding data to the database
Now let's look at how we can add records to the database. This will be done using the form on our page.
Below your previous event handler, add the following line, which sets up a `submit` event handler that runs a function called `addData()` when the form is submitted (when the submit `<button>` is pressed leading to a successful form submission):
```js
// Create a submit event handler so that when the form is submitted the addData() function is run
form.addEventListener("submit", addData);
```
Now let's define the `addData()` function. Add this below your previous line:
```js
// Define the addData() function
function addData(e) {
// prevent default - we don't want the form to submit in the conventional way
e.preventDefault();
// grab the values entered into the form fields and store them in an object ready for being inserted into the DB
const newItem = { title: titleInput.value, body: bodyInput.value };
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["notes\_os"], "readwrite");
// call an object store that's already been added to the database
const objectStore = transaction.objectStore("notes\_os");
// Make a request to add our newItem object to the object store
const addRequest = objectStore.add(newItem);
addRequest.addEventListener("success", () => {
// Clear the form, ready for adding the next entry
titleInput.value = "";
bodyInput.value = "";
});
// Report on the success of the transaction completing, when everything is done
transaction.addEventListener("complete", () => {
console.log("Transaction completed: database modification finished.");
// update the display of data to show the newly added item, by running displayData() again.
displayData();
});
transaction.addEventListener("error", () =>
console.log("Transaction not opened due to error"),
);
}
```
This is quite complex; breaking it down, we:
* Run `Event.preventDefault()` on the event object to stop the form actually submitting in the conventional manner (this would cause a page refresh and spoil the experience).
* Create an object representing a record to enter into the database, populating it with values from the form inputs. Note that we don't have to explicitly include an `id` value β as we explained earlier, this is auto-populated.
* Open a `readwrite` transaction against the `notes_os` object store using the `IDBDatabase.transaction()` method. This transaction object allows us to access the object store so we can do something to it, e.g. add a new record.
* Access the object store using the `IDBTransaction.objectStore()` method, saving the result in the `objectStore` variable.
* Add the new record to the database using `IDBObjectStore.add()`. This creates a request object, in the same fashion as we've seen before.
* Add a bunch of event handlers to the `request` and the `transaction` objects to run code at critical points in the lifecycle. Once the request has succeeded, we clear the form inputs ready for entering the next note. Once the transaction has completed, we run the `displayData()` function again to update the display of notes on the page.
### Displaying the data
We've referenced `displayData()` twice in our code already, so we'd probably better define it. Add this to your code, below the previous function definition:
```js
// Define the displayData() function
function displayData() {
// Here we empty the contents of the list element each time the display is updated
// If you didn't do this, you'd get duplicates listed each time a new note is added
while (list.firstChild) {
list.removeChild(list.firstChild);
}
// Open our object store and then get a cursor - which iterates through all the
// different data items in the store
const objectStore = db.transaction("notes\_os").objectStore("notes\_os");
objectStore.openCursor().addEventListener("success", (e) => {
// Get a reference to the cursor
const cursor = e.target.result;
// If there is still another data item to iterate through, keep running this code
if (cursor) {
// Create a list item, h3, and p to put each data item inside when displaying it
// structure the HTML fragment, and append it inside the list
const listItem = document.createElement("li");
const h3 = document.createElement("h3");
const para = document.createElement("p");
listItem.appendChild(h3);
listItem.appendChild(para);
list.appendChild(listItem);
// Put the data from the cursor inside the h3 and para
h3.textContent = cursor.value.title;
para.textContent = cursor.value.body;
// Store the ID of the data item inside an attribute on the listItem, so we know
// which item it corresponds to. This will be useful later when we want to delete items
listItem.setAttribute("data-note-id", cursor.value.id);
// Create a button and place it inside each listItem
const deleteBtn = document.createElement("button");
listItem.appendChild(deleteBtn);
deleteBtn.textContent = "Delete";
// Set an event handler so that when the button is clicked, the deleteItem()
// function is run
deleteBtn.addEventListener("click", deleteItem);
// Iterate to the next item in the cursor
cursor.continue();
} else {
// Again, if list item is empty, display a 'No notes stored' message
if (!list.firstChild) {
const listItem = document.createElement("li");
listItem.textContent = "No notes stored.";
list.appendChild(listItem);
}
// if there are no more cursor items to iterate through, say so
console.log("Notes all displayed");
}
});
}
```
Again, let's break this down:
* First, we empty out the `<ul>` element's content, before then filling it with the updated content. If you didn't do this, you'd end up with a huge list of duplicated content being added to with each update.
* Next, we get a reference to the `notes_os` object store using `IDBDatabase.transaction()` and `IDBTransaction.objectStore()` like we did in `addData()`, except here we are chaining them together in one line.
* The next step is to use the `IDBObjectStore.openCursor()` method to open a request for a cursor β this is a construct that can be used to iterate over the records in an object store. We chain a `success` event handler onto the end of this line to make the code more concise β when the cursor is successfully returned, the handler is run.
* We get a reference to the cursor itself (an `IDBCursor` object) using `const cursor = e.target.result`.
* Next, we check to see if the cursor contains a record from the datastore (`if (cursor){ }`) β if so, we create a DOM fragment, populate it with the data from the record, and insert it into the page (inside the `<ul>` element). We also include a delete button that, when clicked, will delete that note by running the `deleteItem()` function, which we will look at in the next section.
* At the end of the `if` block, we use the `IDBCursor.continue()` method to advance the cursor to the next record in the datastore, and run the content of the `if` block again. If there is another record to iterate to, this causes it to be inserted into the page, and then `continue()` is run again, and so on.
* When there are no more records to iterate over, `cursor` will return `undefined`, and therefore the `else` block will run instead of the `if` block. This block checks whether any notes were inserted into the `<ul>` β if not, it inserts a message to say no note was stored.
### Deleting a note
As stated above, when a note's delete button is pressed, the note is deleted. This is achieved by the `deleteItem()` function, which looks like so:
```js
// Define the deleteItem() function
function deleteItem(e) {
// retrieve the name of the task we want to delete. We need
// to convert it to a number before trying to use it with IDB; IDB key
// values are type-sensitive.
const noteId = Number(e.target.parentNode.getAttribute("data-note-id"));
// open a database transaction and delete the task, finding it using the id we retrieved above
const transaction = db.transaction(["notes\_os"], "readwrite");
const objectStore = transaction.objectStore("notes\_os");
const deleteRequest = objectStore.delete(noteId);
// report that the data item has been deleted
transaction.addEventListener("complete", () => {
// delete the parent of the button
// which is the list item, so it is no longer displayed
e.target.parentNode.parentNode.removeChild(e.target.parentNode);
console.log(`Note ${noteId} deleted.`);
// Again, if list item is empty, display a 'No notes stored' message
if (!list.firstChild) {
const listItem = document.createElement("li");
listItem.textContent = "No notes stored.";
list.appendChild(listItem);
}
});
}
```
* The first part of this could use some explaining β we retrieve the ID of the record to be deleted using `Number(e.target.parentNode.getAttribute('data-note-id'))` β recall that the ID of the record was saved in a `data-note-id` attribute on the `<li>` when it was first displayed. We do however need to pass the attribute through the global built-in `Number()` object as it is of datatype string, and therefore wouldn't be recognized by the database, which expects a number.
* We then get a reference to the object store using the same pattern we've seen previously, and use the `IDBObjectStore.delete()` method to delete the record from the database, passing it the ID.
* When the database transaction is complete, we delete the note's `<li>` from the DOM, and again do the check to see if the `<ul>` is now empty, inserting a note as appropriate.
So that's it! Your example should now work.
If you are having trouble with it, feel free to check it against our live example (see the source code also).
### Storing complex data via IndexedDB
As we mentioned above, IndexedDB can be used to store more than just text strings. You can store just about anything you want, including complex objects such as video or image blobs. And it isn't much more difficult to achieve than any other type of data.
To demonstrate how to do it, we've written another example called IndexedDB video store (see it running live here also). When you first run the example, it downloads all the videos from the network, stores them in an IndexedDB database, and then displays the videos in the UI inside `<video>` elements. The second time you run it, it finds the videos in the database and gets them from there instead before displaying them β this makes subsequent loads much quicker and less bandwidth-hungry.
Let's walk through the most interesting parts of the example. We won't look at it all β a lot of it is similar to the previous example, and the code is well-commented.
1. For this example, we've stored the names of the videos to fetch in an array of objects:
```js
const videos = [
{ name: "crystal" },
{ name: "elf" },
{ name: "frog" },
{ name: "monster" },
{ name: "pig" },
{ name: "rabbit" },
];
```
2. To start with, once the database is successfully opened we run an `init()` function. This loops through the different video names, trying to load a record identified by each name from the `videos` database.
If each video is found in the database (checked by seeing whether `request.result` evaluates to `true` β if the record is not present, it will be `undefined`), its video files (stored as blobs) and the video name are passed straight to the `displayVideo()` function to place them in the UI. If not, the video name is passed to the `fetchVideoFromNetwork()` function to, you guessed it, fetch the video from the network.
```js
function init() {
// Loop through the video names one by one
for (const video of videos) {
// Open transaction, get object store, and get() each video by name
const objectStore = db.transaction("videos\_os").objectStore("videos\_os");
const request = objectStore.get(video.name);
request.addEventListener("success", () => {
// If the result exists in the database (is not undefined)
if (request.result) {
// Grab the videos from IDB and display them using displayVideo()
console.log("taking videos from IDB");
displayVideo(
request.result.mp4,
request.result.webm,
request.result.name,
);
} else {
// Fetch the videos from the network
fetchVideoFromNetwork(video);
}
});
}
}
```
3. The following snippet is taken from inside `fetchVideoFromNetwork()` β here we fetch MP4 and WebM versions of the video using two separate `fetch()` requests. We then use the `Response.blob()` method to extract each response's body as a blob, giving us an object representation of the videos that can be stored and displayed later on.
We have a problem here though β these two requests are both asynchronous, but we only want to try to display or store the video when both promises have fulfilled. Fortunately there is a built-in method that handles such a problem β `Promise.all()`. This takes one argument β references to all the individual promises you want to check for fulfillment placed in an array β and returns a promise which is fulfilled when all the individual promises are fulfilled.
Inside the `then()` handler for this promise, we call the `displayVideo()` function like we did before to display the videos in the UI, then we also call the `storeVideo()` function to store those videos inside the database.
```js
// Fetch the MP4 and WebM versions of the video using the fetch() function,
// then expose their response bodies as blobs
const mp4Blob = fetch(`videos/${video.name}.mp4`).then((response) =>
response.blob(),
);
const webmBlob = fetch(`videos/${video.name}.webm`).then((response) =>
response.blob(),
);
// Only run the next code when both promises have fulfilled
Promise.all([mp4Blob, webmBlob]).then((values) => {
// display the video fetched from the network with displayVideo()
displayVideo(values[0], values[1], video.name);
// store it in the IDB using storeVideo()
storeVideo(values[0], values[1], video.name);
});
```
4. Let's look at `storeVideo()` first. This is very similar to the pattern you saw in the previous example for adding data to the database β we open a `readwrite` transaction and get a reference to our `videos_os` object store, create an object representing the record to add to the database, then add it using `IDBObjectStore.add()`.
```js
// Define the storeVideo() function
function storeVideo(mp4, webm, name) {
// Open transaction, get object store; make it a readwrite so we can write to the IDB
const objectStore = db
.transaction(["videos\_os"], "readwrite")
.objectStore("videos\_os");
// Add the record to the IDB using add()
const request = objectStore.add({ mp4, webm, name });
request.addEventListener("success", () =>
console.log("Record addition attempt finished"),
);
request.addEventListener("error", () => console.error(request.error));
}
```
5. Finally, we have `displayVideo()`, which creates the DOM elements needed to insert the video in the UI and then appends them to the page. The most interesting parts of this are those shown below β to actually display our video blobs in a `<video>` element, we need to create object URLs (internal URLs that point to the video blobs stored in memory) using the `URL.createObjectURL()` method. Once that is done, we can set the object URLs to be the values of our `<source>` element's `src` attributes, and it works fine.
```js
// Define the displayVideo() function
function displayVideo(mp4Blob, webmBlob, title) {
// Create object URLs out of the blobs
const mp4URL = URL.createObjectURL(mp4Blob);
const webmURL = URL.createObjectURL(webmBlob);
// Create DOM elements to embed video in the page
const article = document.createElement("article");
const h2 = document.createElement("h2");
h2.textContent = title;
const video = document.createElement("video");
video.controls = true;
const source1 = document.createElement("source");
source1.src = mp4URL;
source1.type = "video/mp4";
const source2 = document.createElement("source");
source2.src = webmURL;
source2.type = "video/webm";
// Embed DOM elements into page
section.appendChild(article);
article.appendChild(h2);
article.appendChild(video);
video.appendChild(source1);
video.appendChild(source2);
}
```
Offline asset storage
---------------------
The above example already shows how to create an app that will store large assets in an IndexedDB database, avoiding the need to download them more than once. This is already a great improvement to the user experience, but there is still one thing missing β the main HTML, CSS, and JavaScript files still need to be downloaded each time the site is accessed, meaning that it won't work when there is no network connection.
![Firefox offline screen with an illustration of a cartoon character to the left-hand side holding a two-pin plug in its right hand and a two-pin socket in its left hand. On the right-hand side there is an Offline Mode message and a button labeled 'Try again'.](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage/ff-offline.png)
This is where Service workers and the closely-related Cache API come in.
A service worker is a JavaScript file that is registered against a particular origin (website, or part of a website at a certain domain) when it is accessed by a browser. When registered, it can control pages available at that origin. It does this by sitting between a loaded page and the network and intercepting network requests aimed at that origin.
When it intercepts a request, it can do anything you wish to it (see use case ideas), but the classic example is saving the network responses offline and then providing those in response to a request instead of the responses from the network. In effect, it allows you to make a website work completely offline.
The Cache API is another client-side storage mechanism, with a bit of a difference β it is designed to save HTTP responses, and so works very well with service workers.
### A service worker example
Let's look at an example, to give you a bit of an idea of what this might look like. We have created another version of the video store example we saw in the previous section β this functions identically, except that it also saves the HTML, CSS, and JavaScript in the Cache API via a service worker, allowing the example to run offline!
See IndexedDB video store with service worker running live, and also see the source code.
#### Registering the service worker
The first thing to note is that there's an extra bit of code placed in the main JavaScript file (see index.js). First, we do a feature detection test to see if the `serviceWorker` member is available in the `Navigator` object. If this returns true, then we know that at least the basics of service workers are supported. Inside here we use the `ServiceWorkerContainer.register()` method to register a service worker contained in the `sw.js` file against the origin it resides at, so it can control pages in the same directory as it, or subdirectories. When its promise fulfills, the service worker is deemed registered.
```js
// Register service worker to control making site work offline
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register(
"/learning-area/javascript/apis/client-side-storage/cache-sw/video-store-offline/sw.js",
)
.then(() => console.log("Service Worker Registered"));
}
```
**Note:** The given path to the `sw.js` file is relative to the site origin, not the JavaScript file that contains the code. The service worker is at `https://mdn.github.io/learning-area/javascript/apis/client-side-storage/cache-sw/video-store-offline/sw.js`. The origin is `https://mdn.github.io`, and therefore the given path has to be `/learning-area/javascript/apis/client-side-storage/cache-sw/video-store-offline/sw.js`. If you wanted to host this example on your own server, you'd have to change this accordingly. This is rather confusing, but it has to work this way for security reasons.
#### Installing the service worker
The next time any page under the service worker's control is accessed (e.g. when the example is reloaded), the service worker is installed against that page, meaning that it will start controlling it. When this occurs, an `install` event is fired against the service worker; you can write code inside the service worker itself that will respond to the installation.
Let's look at an example, in the sw.js file (the service worker). You'll see that the install listener is registered against `self`. This `self` keyword is a way to refer to the global scope of the service worker from inside the service worker file.
Inside the `install` handler, we use the `ExtendableEvent.waitUntil()` method, available on the event object, to signal that the browser shouldn't complete installation of the service worker until after the promise inside it has fulfilled successfully.
Here is where we see the Cache API in action. We use the `CacheStorage.open()` method to open a new cache object in which responses can be stored (similar to an IndexedDB object store). This promise fulfills with a `Cache` object representing the `video-store` cache. We then use the `Cache.addAll()` method to fetch a series of assets and add their responses to the cache.
```js
self.addEventListener("install", (e) => {
e.waitUntil(
caches
.open("video-store")
.then((cache) =>
cache.addAll([
"/learning-area/javascript/apis/client-side-storage/cache-sw/video-store-offline/",
"/learning-area/javascript/apis/client-side-storage/cache-sw/video-store-offline/index.html",
"/learning-area/javascript/apis/client-side-storage/cache-sw/video-store-offline/index.js",
"/learning-area/javascript/apis/client-side-storage/cache-sw/video-store-offline/style.css",
]),
),
);
});
```
That's it for now, installation done.
#### Responding to further requests
With the service worker registered and installed against our HTML page, and the relevant assets all added to our cache, we are nearly ready to go. There is only one more thing to do: write some code to respond to further network requests.
This is what the second bit of code in `sw.js` does. We add another listener to the service worker global scope, which runs the handler function when the `fetch` event is raised. This happens whenever the browser makes a request for an asset in the directory the service worker is registered against.
Inside the handler, we first log the URL of the requested asset. We then provide a custom response to the request, using the `FetchEvent.respondWith()` method.
Inside this block, we use `CacheStorage.match()` to check whether a matching request (i.e. matches the URL) can be found in any cache. This promise fulfills with the matching response if a match is found, or `undefined` if it isn't.
If a match is found, we return it as the custom response. If not, we fetch() the response from the network and return that instead.
```js
self.addEventListener("fetch", (e) => {
console.log(e.request.url);
e.respondWith(
caches.match(e.request).then((response) => response || fetch(e.request)),
);
});
```
And that is it for our service worker.
There is a whole load more you can do with them β for a lot more detail, see the service worker cookbook.
Many thanks to Paul Kinlan for his article Adding a Service Worker and Offline into your Web App, which inspired this example.
#### Testing the example offline
To test our service worker example, you'll need to load it a couple of times to make sure it is installed. Once this is done, you can:
* Try unplugging your network/turning your Wi-Fi off.
* Select *File > Work Offline* if you are using Firefox.
* Go to the devtools, then choose *Application > Service Workers*, then check the *Offline* checkbox if you are using Chrome.
If you refresh your example page again, you should still see it load just fine. Everything is stored offline β the page assets in a cache, and the videos in an IndexedDB database.
Summary
-------
That's it for now. We hope you've found our rundown of client-side storage technologies useful.
See also
--------
* Web storage API
* IndexedDB API
* Cookies
* Service worker API
* Previous
* Overview: Client-side web APIs |
Video and Audio APIs - Learn web development | Video and Audio APIs
====================
* Previous
* Overview: Client-side web APIs
* Next
HTML comes with elements for embedding rich media in documents β `<video>` and `<audio>` β which in turn come with their own APIs for controlling playback, seeking, etc. This article shows you how to do common tasks such as creating custom playback controls.
| | |
| --- | --- |
| Prerequisites: |
JavaScript basics (see
first steps,
building blocks,
JavaScript objects),
the
basics of Client-side APIs |
| Objective: | To learn how to use browser APIs to control video and audio playback. |
HTML video and audio
--------------------
The `<video>` and `<audio>` elements allow us to embed video and audio into web pages. As we showed in Video and audio content, a typical implementation looks like this:
```html
<video controls>
<source src="rabbit320.mp4" type="video/mp4" />
<source src="rabbit320.webm" type="video/webm" />
<p>
Your browser doesn't support HTML video. Here is a
<a href="rabbit320.mp4">link to the video</a> instead.
</p>
</video>
```
This creates a video player inside the browser like so:
You can review what all the HTML features do in the article linked above; for our purposes here, the most interesting attribute is `controls`, which enables the default set of playback controls. If you don't specify this, you get no playback controls:
This is not as immediately useful for video playback, but it does have advantages. One big issue with the native browser controls is that they are different in each browser β not very good for cross-browser support! Another big issue is that the native controls in most browsers aren't very keyboard-accessible.
You can solve both these problems by hiding the native controls (by removing the `controls` attribute), and programming your own with HTML, CSS, and JavaScript. In the next section, we'll look at the basic tools we have available to do this.
The HTMLMediaElement API
------------------------
Part of the HTML spec, the `HTMLMediaElement` API provides features to allow you to control video and audio players programmatically β for example `HTMLMediaElement.play()`, `HTMLMediaElement.pause()`, etc. This interface is available to both `<audio>` and `<video>` elements, as the features you'll want to implement are nearly identical. Let's go through an example, adding features as we go.
Our finished example will look (and function) something like the following:
### Getting started
To get started with this example, download our media-player-start.zip and unzip it into a new directory on your hard drive. If you downloaded our examples repo, you'll find it in `javascript/apis/video-audio/start/`.
At this point, if you load the HTML you should see a perfectly normal HTML video player, with the native controls rendered.
#### Exploring the HTML
Open the HTML index file. You'll see a number of features; the HTML is dominated by the video player and its controls:
```html
<div class="player">
<video controls>
<source src="video/sintel-short.mp4" type="video/mp4" />
<source src="video/sintel-short.webm" type="video/webm" />
<!-- fallback content here -->
</video>
<div class="controls">
<button class="play" data-icon="P" aria-label="play pause toggle"></button>
<button class="stop" data-icon="S" aria-label="stop"></button>
<div class="timer">
<div></div>
<span aria-label="timer">00:00</span>
</div>
<button class="rwd" data-icon="B" aria-label="rewind"></button>
<button class="fwd" data-icon="F" aria-label="fast forward"></button>
</div>
</div>
```
* The whole player is wrapped in a `<div>` element, so it can all be styled as one unit if needed.
* The `<video>` element contains two `<source>` elements so that different formats can be loaded depending on the browser viewing the site.
* The controls HTML is probably the most interesting:
+ We have four `<button>`s β play/pause, stop, rewind, and fast forward.
+ Each `<button>` has a `class` name, a `data-icon` attribute for defining what icon should be shown on each button (we'll show how this works in the below section), and an `aria-label` attribute to provide an understandable description of each button, since we're not providing a human-readable label inside the tags. The contents of `aria-label` attributes are read out by screen readers when their users focus on the elements that contain them.
+ There is also a timer `<div>`, which will report the elapsed time when the video is playing. Just for fun, we are providing two reporting mechanisms β a `<span>` containing the elapsed time in minutes and seconds, and an extra `<div>` that we will use to create a horizontal indicator bar that gets longer as the time elapses. To get an idea of what the finished product will look like, check out our finished version.
#### Exploring the CSS
Now open the CSS file and have a look inside. The CSS for the example is not too complicated, but we'll highlight the most interesting bits here. First of all, notice the `.controls` styling:
```css
.controls {
visibility: hidden;
opacity: 0.5;
width: 400px;
border-radius: 10px;
position: absolute;
bottom: 20px;
left: 50%;
margin-left: -200px;
background-color: black;
box-shadow: 3px 3px 5px black;
transition: 1s all;
display: flex;
}
.player:hover .controls,
.player:focus-within .controls {
opacity: 1;
}
```
* We start off with the `visibility` of the custom controls set to `hidden`. In our JavaScript later on, we will set the controls to `visible`, and remove the `controls` attribute from the `<video>` element. This is so that, if the JavaScript doesn't load for some reason, users can still use the video with the native controls.
* We give the controls an `opacity` of 0.5 by default, so that they are less distracting when you are trying to watch the video. Only when you are hovering/focusing over the player do the controls appear at full opacity.
* We lay out the buttons inside the control bar using Flexbox (`display`: flex), to make things easier.
Next, let's look at our button icons:
```css
@font-face {
font-family: "HeydingsControlsRegular";
src: url("fonts/heydings\_controls-webfont.eot");
src:
url("fonts/heydings\_controls-webfont.eot?#iefix") format("embedded-opentype"),
url("fonts/heydings\_controls-webfont.woff") format("woff"),
url("fonts/heydings\_controls-webfont.ttf") format("truetype");
font-weight: normal;
font-style: normal;
}
button:before {
font-family: HeydingsControlsRegular;
font-size: 20px;
position: relative;
content: attr(data-icon);
color: #aaa;
text-shadow: 1px 1px 0px black;
}
```
First of all, at the top of the CSS we use a `@font-face` block to import a custom web font. This is an icon font β all the characters of the alphabet equate to common icons you might want to use in an application.
Next, we use generated content to display an icon on each button:
* We use the `::before` selector to display the content before each `<button>` element.
* We use the `content` property to set the content to be displayed in each case to be equal to the contents of the `data-icon` attribute. In the case of our play button, `data-icon` contains a capital "P".
* We apply the custom web font to our buttons using `font-family`. In this font, "P" is actually a "play" icon, so therefore the play button has a "play" icon displayed on it.
Icon fonts are very cool for many reasons β cutting down on HTTP requests because you don't need to download those icons as image files, great scalability, and the fact that you can use text properties to style them β like `color` and `text-shadow`.
Last but not least, let's look at the CSS for the timer:
```css
.timer {
line-height: 38px;
font-size: 10px;
font-family: monospace;
text-shadow: 1px 1px 0px black;
color: white;
flex: 5;
position: relative;
}
.timer div {
position: absolute;
background-color: rgb(255 255 255 / 20%);
left: 0;
top: 0;
width: 0;
height: 38px;
z-index: 2;
}
.timer span {
position: absolute;
z-index: 3;
left: 19px;
}
```
* We set the outer `.timer` element to have `flex: 5`, so it takes up most of the width of the controls bar. We also give it `position``: relative`, so that we can position elements inside it conveniently according to its boundaries, and not the boundaries of the `<body>` element.
* The inner `<div>` is absolutely positioned to sit directly on top of the outer `<div>`. It is also given an initial width of 0, so you can't see it at all. As the video plays, the width will be increased via JavaScript as the video elapses.
* The `<span>` is also absolutely positioned to sit near the left-hand side of the timer bar.
* We also give our inner `<div>` and `<span>` the right amount of `z-index` so that the timer will be displayed on top, and the inner `<div>` below that. This way, we make sure we can see all the information β one box is not obscuring another.
### Implementing the JavaScript
We've got a fairly complete HTML and CSS interface already; now we just need to wire up all the buttons to get the controls working.
1. Create a new JavaScript file in the same directory level as your index.html file. Call it `custom-player.js`.
2. At the top of this file, insert the following code:
```js
const media = document.querySelector("video");
const controls = document.querySelector(".controls");
const play = document.querySelector(".play");
const stop = document.querySelector(".stop");
const rwd = document.querySelector(".rwd");
const fwd = document.querySelector(".fwd");
const timerWrapper = document.querySelector(".timer");
const timer = document.querySelector(".timer span");
const timerBar = document.querySelector(".timer div");
```
Here we are creating constants to hold references to all the objects we want to manipulate. We have three groups:
* The `<video>` element, and the controls bar.
* The play/pause, stop, rewind, and fast forward buttons.
* The outer timer wrapper `<div>`, the digital timer readout `<span>`, and the inner `<div>` that gets wider as the time elapses.
3. Next, insert the following at the bottom of your code:
```js
media.removeAttribute("controls");
controls.style.visibility = "visible";
```
These two lines remove the default browser controls from the video, and make the custom controls visible.
#### Playing and pausing the video
Let's implement probably the most important control β the play/pause button.
1. First of all, add the following to the bottom of your code, so that the `playPauseMedia()` function is invoked when the play button is clicked:
```js
play.addEventListener("click", playPauseMedia);
```
2. Now to define `playPauseMedia()` β add the following, again at the bottom of your code:
```js
function playPauseMedia() {
if (media.paused) {
play.setAttribute("data-icon", "u");
media.play();
} else {
play.setAttribute("data-icon", "P");
media.pause();
}
}
```
Here we use an `if` statement to check whether the video is paused. The `HTMLMediaElement.paused` property returns true if the media is paused, which is any time the video is not playing, including when it is set at 0 duration after it first loads. If it is paused, we set the `data-icon` attribute value on the play button to "u", which is a "paused" icon, and invoke the `HTMLMediaElement.play()` method to play the media.
On the second click, the button will be toggled back again β the "play" icon will be shown again, and the video will be paused with `HTMLMediaElement.pause()`.
#### Stopping the video
1. Next, let's add functionality to handle stopping the video. Add the following `addEventListener()` lines below the previous one you added:
```js
stop.addEventListener("click", stopMedia);
media.addEventListener("ended", stopMedia);
```
The `click` event is obvious β we want to stop the video by running our `stopMedia()` function when the stop button is clicked. We do however also want to stop the video when it finishes playing β this is marked by the `ended` event firing, so we also set up a listener to run the function on that event firing too.
2. Next, let's define `stopMedia()` β add the following function below `playPauseMedia()`:
```js
function stopMedia() {
media.pause();
media.currentTime = 0;
play.setAttribute("data-icon", "P");
}
```
there is no `stop()` method on the HTMLMediaElement API β the equivalent is to `pause()` the video, and set its `currentTime` property to 0. Setting `currentTime` to a value (in seconds) immediately jumps the media to that position.
All there is left to do after that is to set the displayed icon to the "play" icon. Regardless of whether the video was paused or playing when the stop button is pressed, you want it to be ready to play afterwards.
#### Seeking back and forth
There are many ways that you can implement rewind and fast-forward functionality; here we are showing you a relatively complex way of doing it, which doesn't break when the different buttons are pressed in an unexpected order.
1. First of all, add the following two `addEventListener()` lines below the previous ones:
```js
rwd.addEventListener("click", mediaBackward);
fwd.addEventListener("click", mediaForward);
```
2. Now on to the event handler functions β add the following code below your previous functions to define `mediaBackward()` and `mediaForward()`:
```js
let intervalFwd;
let intervalRwd;
function mediaBackward() {
clearInterval(intervalFwd);
fwd.classList.remove("active");
if (rwd.classList.contains("active")) {
rwd.classList.remove("active");
clearInterval(intervalRwd);
media.play();
} else {
rwd.classList.add("active");
media.pause();
intervalRwd = setInterval(windBackward, 200);
}
}
function mediaForward() {
clearInterval(intervalRwd);
rwd.classList.remove("active");
if (fwd.classList.contains("active")) {
fwd.classList.remove("active");
clearInterval(intervalFwd);
media.play();
} else {
fwd.classList.add("active");
media.pause();
intervalFwd = setInterval(windForward, 200);
}
}
```
You'll notice that first, we initialize two variables β `intervalFwd` and `intervalRwd` β you'll find out what they are for later on.
Let's step through `mediaBackward()` (the functionality for `mediaForward()` is exactly the same, but in reverse):
1. We clear any classes and intervals that are set on the fast forward functionality β we do this because if we press the `rwd` button after pressing the `fwd` button, we want to cancel any fast forward functionality and replace it with the rewind functionality. If we tried to do both at once, the player would break.
2. We use an `if` statement to check whether the `active` class has been set on the `rwd` button, indicating that it has already been pressed. The `classList` is a rather handy property that exists on every element β it contains a list of all the classes set on the element, as well as methods for adding/removing classes, etc. We use the `classList.contains()` method to check whether the list contains the `active` class. This returns a boolean `true`/`false` result.
3. If `active` has been set on the `rwd` button, we remove it using `classList.remove()`, clear the interval that has been set when the button was first pressed (see below for more explanation), and use `HTMLMediaElement.play()` to cancel the rewind and start the video playing normally.
4. If it hasn't yet been set, we add the `active` class to the `rwd` button using `classList.add()`, pause the video using `HTMLMediaElement.pause()`, then set the `intervalRwd` variable to equal a `setInterval()` call. When invoked, `setInterval()` creates an active interval, meaning that it runs the function given as the first parameter every x milliseconds, where x is the value of the 2nd parameter. So here we are running the `windBackward()` function every 200 milliseconds β we'll use this function to wind the video backwards constantly. To stop a `setInterval()` running, you have to call `clearInterval()`, giving it the identifying name of the interval to clear, which in this case is the variable name `intervalRwd` (see the `clearInterval()` call earlier on in the function).
3. Finally, we need to define the `windBackward()` and `windForward()` functions invoked in the `setInterval()` calls. Add the following below your two previous functions:
```js
function windBackward() {
if (media.currentTime <= 3) {
rwd.classList.remove("active");
clearInterval(intervalRwd);
stopMedia();
} else {
media.currentTime -= 3;
}
}
function windForward() {
if (media.currentTime >= media.duration - 3) {
fwd.classList.remove("active");
clearInterval(intervalFwd);
stopMedia();
} else {
media.currentTime += 3;
}
}
```
Again, we'll just run through the first one of these functions as they work almost identically, but in reverse to one another. In `windBackward()` we do the following β bear in mind that when the interval is active, this function is being run once every 200 milliseconds.
1. We start off with an `if` statement that checks to see whether the current time is less than 3 seconds, i.e., if rewinding by another three seconds would take it back past the start of the video. This would cause strange behavior, so if this is the case we stop the video playing by calling `stopMedia()`, remove the `active` class from the rewind button, and clear the `intervalRwd` interval to stop the rewind functionality. If we didn't do this last step, the video would just keep rewinding forever.
2. If the current time is not within 3 seconds of the start of the video, we remove three seconds from the current time by executing `media.currentTime -= 3`. So in effect, we are rewinding the video by 3 seconds, once every 200 milliseconds.
#### Updating the elapsed time
The very last piece of our media player to implement is the time-elapsed displays. To do this we'll run a function to update the time displays every time the `timeupdate` event is fired on the `<video>` element. The frequency with which this event fires depends on your browser, CPU power, etc. (see this StackOverflow post).
Add the following `addEventListener()` line just below the others:
```js
media.addEventListener("timeupdate", setTime);
```
Now to define the `setTime()` function. Add the following at the bottom of your file:
```js
function setTime() {
const minutes = Math.floor(media.currentTime / 60);
const seconds = Math.floor(media.currentTime - minutes \* 60);
const minuteValue = minutes.toString().padStart(2, "0");
const secondValue = seconds.toString().padStart(2, "0");
const mediaTime = `${minuteValue}:${secondValue}`;
timer.textContent = mediaTime;
const barLength =
timerWrapper.clientWidth \* (media.currentTime / media.duration);
timerBar.style.width = `${barLength}px`;
}
```
This is a fairly long function, so let's go through it step by step:
1. First of all, we work out the number of minutes and seconds in the `HTMLMediaElement.currentTime` value.
2. Then we initialize two more variables β `minuteValue` and `secondValue`. We use `padStart()` to make each value 2 characters long, even if the numeric value is only a single digit.
3. The actual time value to display is set as `minuteValue` plus a colon character plus `secondValue`.
4. The `Node.textContent` value of the timer is set to the time value, so it displays in the UI.
5. The length we should set the inner `<div>` to is worked out by first working out the width of the outer `<div>` (any element's `clientWidth` property will contain its length), and then multiplying it by the `HTMLMediaElement.currentTime` divided by the total `HTMLMediaElement.duration` of the media.
6. We set the width of the inner `<div>` to equal the calculated bar length, plus "px", so it will be set to that number of pixels.
#### Fixing play and pause
There is one problem left to fix. If the play/pause or stop buttons are pressed while the rewind or fast forward functionality is active, they just don't work. How can we fix it so that they cancel the `rwd`/`fwd` button functionality and play/stop the video as you'd expect? This is fairly easy to fix.
First of all, add the following lines inside the `stopMedia()` function β anywhere will do:
```js
rwd.classList.remove("active");
fwd.classList.remove("active");
clearInterval(intervalRwd);
clearInterval(intervalFwd);
```
Now add the same lines again, at the very start of the `playPauseMedia()` function (just before the start of the `if` statement).
At this point, you could delete the equivalent lines from the `windBackward()` and `windForward()` functions, as that functionality has been implemented in the `stopMedia()` function instead.
Note: You could also further improve the efficiency of the code by creating a separate function that runs these lines, then calling that anywhere it is needed, rather than repeating the lines multiple times in the code. But we'll leave that one up to you.
Summary
-------
I think we've taught you enough in this article. The `HTMLMediaElement` API makes a wealth of functionality available for creating simple video and audio players, and that's only the tip of the iceberg. See the "See also" section below for links to more complex and interesting functionality.
Here are some suggestions for ways you could enhance the existing example we've built up:
1. The time display currently breaks if the video is an hour long or more (well, it won't display hours; just minutes and seconds). Can you figure out how to change the example to make it display hours?
2. Because `<audio>` elements have the same `HTMLMediaElement` functionality available to them, you could easily get this player to work for an `<audio>` element too. Try doing so.
3. Can you work out a way to turn the timer inner `<div>` element into a true seek bar/scroller β i.e., when you click somewhere on the bar, it jumps to that relative position in the video playback? As a hint, you can find out the X and Y values of the element's left/right and top/bottom sides via the `getBoundingClientRect()` method, and you can find the coordinates of a mouse click via the event object of the click event, called on the `Document` object. For example:
```js
document.onclick = function (e) {
console.log(e.x, e.y);
};
```
See also
--------
* `HTMLMediaElement`
* Video and audio content β simple guide to `<video>` and `<audio>` HTML.
* Audio and video delivery β detailed guide to delivering media inside the browser, with many tips, tricks, and links to further more advanced tutorials.
* Audio and video manipulation β detailed guide to manipulating audio and video, e.g. with Canvas API, Web Audio API, and more.
* `<video>` and `<audio>` reference pages.
* Guide to media types and formats on the web
* Previous
* Overview: Client-side web APIs
* Next |
Introduction to web APIs - Learn web development | Introduction to web APIs
========================
* Overview: Client-side web APIs
* Next
First up, we'll start by looking at APIs from a high level β what are they, how do they work, how to use them in your code, and how are they structured? We'll also take a look at what the different main classes of APIs are, and what kind of uses they have.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of
HTML,
CSS, and JavaScript basics (see
first steps,
building blocks,
JavaScript objects).
|
| Objective: |
To gain familiarity with APIs, what they can do, and how you can use
them in your code.
|
What are APIs?
--------------
Application Programming Interfaces (APIs) are constructs made available in programming languages to allow developers to create complex functionality more easily. They abstract more complex code away from you, providing some easier syntax to use in its place.
As a real-world example, think about the electricity supply in your house, apartment, or other dwellings. If you want to use an appliance in your house, you plug it into a plug socket and it works. You don't try to wire it directly into the power supply β to do so would be really inefficient and, if you are not an electrician, difficult and dangerous to attempt.
![Two multi-plug holders are plugged into two different plug outlet sockets. Each multi-plug holder has a plug slot on it's top and to it's front side. Two plugs are plugged into each multi-plug holder.](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction/plug-socket.png)
*Image source: Overloaded plug socket by The Clear Communication People, on Flickr.*
In the same way, if you want to say, program some 3D graphics, it is a lot easier to do it using an API written in a higher-level language such as JavaScript or Python, rather than try to directly write low-level code (say C or C++) that directly controls the computer's GPU or other graphics functions.
**Note:** See also the API glossary entry for further description.
### APIs in client-side JavaScript
Client-side JavaScript, in particular, has many APIs available to it β these are not part of the JavaScript language itself, rather they are built on top of the core JavaScript language, providing you with extra superpowers to use in your JavaScript code. They generally fall into two categories:
* **Browser APIs** are built into your web browser and are able to expose data from the browser and surrounding computer environment and do useful complex things with it. For example, the Web Audio API provides JavaScript constructs for manipulating audio in the browser β taking an audio track, altering its volume, applying effects to it, etc. In the background, the browser is actually using some complex lower-level code (e.g. C++ or Rust) to do the actual audio processing. But again, this complexity is abstracted away from you by the API.
* **Third-party APIs** are not built into the browser by default, and you generally have to retrieve their code and information from somewhere on the Web. For example, the Twitter API allows you to do things like displaying your latest tweets on your website. It provides a special set of constructs you can use to query the Twitter service and return specific information.
![A screenshot of the browser with the home page of firefox browser open. There are APIs built into the browser by default. Third party APIs are not built into the browser by default. Their code and information has to be retrieved from somewhere on the web to utilize them.](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction/browser.png)
### Relationship between JavaScript, APIs, and other JavaScript tools
So above, we talked about what client-side JavaScript APIs are, and how they relate to the JavaScript language. Let's recap this to make it clearer, and also mention where other JavaScript tools fit in:
* JavaScript β A high-level scripting language built into browsers that allows you to implement functionality on web pages/apps. Note that JavaScript is also available in other programming environments, such as Node.
* Browser APIs β constructs built into the browser that sits on top of the JavaScript language and allows you to implement functionality more easily.
* Third-party APIs β constructs built into third-party platforms (e.g. Twitter, Facebook) that allow you to use some of those platform's functionality in your own web pages (for example, display your latest Tweets on your web page).
* JavaScript libraries β Usually one or more JavaScript files containing custom functions that you can attach to your web page to speed up or enable writing common functionality. Examples include jQuery, Mootools and React.
* JavaScript frameworks β The next step up from libraries, JavaScript frameworks (e.g. Angular and Ember) tend to be packages of HTML, CSS, JavaScript, and other technologies that you install and then use to write an entire web application from scratch. The key difference between a library and a framework is "Inversion of Control". When calling a method from a library, the developer is in control. With a framework, the control is inverted: the framework calls the developer's code.
What can APIs do?
-----------------
There are a huge number of APIs available in modern browsers that allow you to do a wide variety of things in your code. You can see this by taking a look at the MDN APIs index page.
### Common browser APIs
In particular, the most common categories of browser APIs you'll use (and which we'll cover in this module in greater detail) are:
* **APIs for manipulating documents** loaded into the browser. The most obvious example is the DOM (Document Object Model) API, which allows you to manipulate HTML and CSS β creating, removing and changing HTML, dynamically applying new styles to your page, etc. Every time you see a popup window appear on a page or some new content displayed, for example, that's the DOM in action. Find out more about these types of API in Manipulating documents.
* **APIs that fetch data from the server** to update small sections of a webpage on their own are very commonly used. This seemingly small detail has had a huge impact on the performance and behavior of sites β if you just need to update a stock listing or list of available new stories, doing it instantly without having to reload the whole entire page from the server can make the site or app feel much more responsive and "snappy". The main API used for this is the Fetch API, although older code might still use the `XMLHttpRequest` API. You may also come across the term **Ajax**, which describes this technique. Find out more about such APIs in Fetching data from the server.
* **APIs for drawing and manipulating graphics** are widely supported in browsers β the most popular ones are Canvas and WebGL, which allow you to programmatically update the pixel data contained in an HTML `<canvas>` element to create 2D and 3D scenes. For example, you might draw shapes such as rectangles or circles, import an image onto the canvas, and apply a filter to it such as sepia or grayscale using the Canvas API, or create a complex 3D scene with lighting and textures using WebGL. Such APIs are often combined with APIs for creating animation loops (such as `window.requestAnimationFrame()`) and others to make constantly updating scenes like cartoons and games.
* **Audio and Video APIs** like `HTMLMediaElement`, the Web Audio API, and WebRTC allow you to do really interesting things with multimedia such as creating custom UI controls for playing audio and video, displaying text tracks like captions and subtitles along with your videos, grabbing video from your web camera to be manipulated via a canvas (see above) or displayed on someone else's computer in a web conference, or adding effects to audio tracks (such as gain, distortion, panning, etc.).
* **Device APIs** enable you to interact with device hardware: for example, accessing the device GPS to find the user's position using the Geolocation API.
* **Client-side storage APIs** enable you to store data on the client-side, so you can create an app that will save its state between page loads, and perhaps even work when the device is offline. There are several options available, e.g. simple name/value storage with the Web Storage API, and more complex database storage with the IndexedDB API.
### Common third-party APIs
Third-party APIs come in a large variety; some of the more popular ones that you are likely to make use of sooner or later are:
* The Twitter API, which allows you to do things like displaying your latest tweets on your website.
* Map APIs, like Mapquest and the Google Maps API, which allow you to do all sorts of things with maps on your web pages.
* The Facebook suite of APIs, which enables you to use various parts of the Facebook ecosystem to benefit your app, such as by providing app login using Facebook login, accepting in-app payments, rolling out targeted ad campaigns, etc.
* The Telegram APIs, which allows you to embed content from Telegram channels on your website, in addition to providing support for bots.
* The YouTube API, which allows you to embed YouTube videos on your site, search YouTube, build playlists, and more.
* The Pinterest API, which provides tools to manage Pinterest boards and pins to include them in your website.
* The Twilio API, which provides a framework for building voice and video call functionality into your app, sending SMS/MMS from your apps, and more.
* The Mastodon API, which enables you to manipulate features of the Mastodon social network programmatically.
How do APIs work?
-----------------
Different JavaScript APIs work in slightly different ways, but generally, they have common features and similar themes to how they work.
### They are based on objects
Your code interacts with APIs using one or more JavaScript objects, which serve as containers for the data the API uses (contained in object properties), and the functionality the API makes available (contained in object methods).
**Note:** If you are not already familiar with how objects work, you should go back and work through our JavaScript objects module before continuing.
Let's return to the example of the Web Audio API β this is a fairly complex API, which consists of a number of objects. The most obvious ones are:
* `AudioContext`, which represents an audio graph that can be used to manipulate audio playing inside the browser, and has a number of methods and properties available to manipulate that audio.
* `MediaElementAudioSourceNode`, which represents an `<audio>` element containing sound you want to play and manipulate inside the audio context.
* `AudioDestinationNode`, which represents the destination of the audio, i.e. the device on your computer that will actually output it β usually your speakers or headphones.
So how do these objects interact? If you look at our simple web audio example (see it live also), you'll first see the following HTML:
```html
<audio src="outfoxing.mp3"></audio>
<button class="paused">Play</button>
<br />
<input type="range" min="0" max="1" step="0.01" value="1" class="volume" />
```
We, first of all, include an `<audio>` element with which we embed an MP3 into the page. We don't include any default browser controls. Next, we include a `<button>` that we'll use to play and stop the music, and an `<input>` element of type range, which we'll use to adjust the volume of the track while it's playing.
Next, let's look at the JavaScript for this example.
We start by creating an `AudioContext` instance inside which to manipulate our track:
```js
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioCtx = new AudioContext();
```
Next, we create constants that store references to our `<audio>`, `<button>`, and `<input>` elements, and use the `AudioContext.createMediaElementSource()` method to create a `MediaElementAudioSourceNode` representing the source of our audio β the `<audio>` element will be played from:
```js
const audioElement = document.querySelector("audio");
const playBtn = document.querySelector("button");
const volumeSlider = document.querySelector(".volume");
const audioSource = audioCtx.createMediaElementSource(audioElement);
```
Next up we include a couple of event handlers that serve to toggle between play and pause when the button is pressed and reset the display back to the beginning when the song has finished playing:
```js
// play/pause audio
playBtn.addEventListener("click", () => {
// check if context is in suspended state (autoplay policy)
if (audioCtx.state === "suspended") {
audioCtx.resume();
}
// if track is stopped, play it
if (playBtn.getAttribute("class") === "paused") {
audioElement.play();
playBtn.setAttribute("class", "playing");
playBtn.textContent = "Pause";
// if track is playing, stop it
} else if (playBtn.getAttribute("class") === "playing") {
audioElement.pause();
playBtn.setAttribute("class", "paused");
playBtn.textContent = "Play";
}
});
// if track ends
audioElement.addEventListener("ended", () => {
playBtn.setAttribute("class", "paused");
playBtn.textContent = "Play";
});
```
**Note:** Some of you may notice that the `play()` and `pause()` methods being used to play and pause the track are not part of the Web Audio API; they are part of the `HTMLMediaElement` API, which is different but closely-related.
Next, we create a `GainNode` object using the `AudioContext.createGain()` method, which can be used to adjust the volume of audio fed through it, and create another event handler that changes the value of the audio graph's gain (volume) whenever the slider value is changed:
```js
// volume
const gainNode = audioCtx.createGain();
volumeSlider.addEventListener("input", () => {
gainNode.gain.value = volumeSlider.value;
});
```
The final thing to do to get this to work is to connect the different nodes in the audio graph up, which is done using the `AudioNode.connect()` method available on every node type:
```js
audioSource.connect(gainNode).connect(audioCtx.destination);
```
The audio starts in the source, which is then connected to the gain node so the audio's volume can be adjusted. The gain node is then connected to the destination node so the sound can be played on your computer (the `AudioContext.destination` property represents whatever is the default `AudioDestinationNode` available on your computer's hardware, e.g. your speakers).
### They have recognizable entry points
When using an API, you should make sure you know where the entry point is for the API. In The Web Audio API, this is pretty simple β it is the `AudioContext` object, which needs to be used to do any audio manipulation whatsoever.
The Document Object Model (DOM) API also has a simple entry point β its features tend to be found hanging off the `Document` object, or an instance of an HTML element that you want to affect in some way, for example:
```js
const em = document.createElement("em"); // create a new em element
const para = document.querySelector("p"); // reference an existing p element
em.textContent = "Hello there!"; // give em some text content
para.appendChild(em); // embed em inside para
```
The Canvas API also relies on getting a context object to use to manipulate things, although in this case, it's a graphical context rather than an audio context. Its context object is created by getting a reference to the `<canvas>` element you want to draw on, and then calling its `HTMLCanvasElement.getContext()` method:
```js
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
```
Anything that we want to do to the canvas is then achieved by calling properties and methods of the context object (which is an instance of `CanvasRenderingContext2D`), for example:
```js
Ball.prototype.draw = function () {
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc(this.x, this.y, this.size, 0, 2 \* Math.PI);
ctx.fill();
};
```
**Note:** You can see this code in action in our bouncing balls demo (see it running live also).
### They often use events to handle changes in state
We already discussed events earlier on in the course in our Introduction to events article, which looks in detail at what client-side web events are and how they are used in your code. If you are not already familiar with how client-side web API events work, you should go and read this article first before continuing.
Some web APIs contain no events, but most contain at least a few. The handler properties that allow us to run functions when events fire are generally listed in our reference material in separate "Event handlers" sections.
We already saw a number of event handlers in use in our Web Audio API example above:
```js
// play/pause audio
playBtn.addEventListener("click", () => {
// check if context is in suspended state (autoplay policy)
if (audioCtx.state === "suspended") {
audioCtx.resume();
}
// if track is stopped, play it
if (playBtn.getAttribute("class") === "paused") {
audioElement.play();
playBtn.setAttribute("class", "playing");
playBtn.textContent = "Pause";
// if track is playing, stop it
} else if (playBtn.getAttribute("class") === "playing") {
audioElement.pause();
playBtn.setAttribute("class", "paused");
playBtn.textContent = "Play";
}
});
// if track ends
audioElement.addEventListener("ended", () => {
playBtn.setAttribute("class", "paused");
playBtn.textContent = "Play";
});
```
### They have additional security mechanisms where appropriate
WebAPI features are subject to the same security considerations as JavaScript and other web technologies (for example same-origin policy), but they sometimes have additional security mechanisms in place. For example, some of the more modern WebAPIs will only work on pages served over HTTPS due to them transmitting potentially sensitive data (examples include Service Workers and Push).
In addition, some WebAPIs request permission to be enabled from the user once calls to them are made in your code. As an example, the Notifications API asks for permission using a pop-up dialog box:
![A screenshot of the notifications pop-up dialog provided by the Notifications API of the browser. 'mdn.github.io' website is asking for permissions to push notifications to the user-agent with an X to close the dialog and drop-down menu of options with 'always receive notifications' selected by default.](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction/notification-permission.png)
The Web Audio and `HTMLMediaElement` APIs are subject to a security mechanism called autoplay policy β this basically means that you can't automatically play audio when a page loads β you've got to allow your users to initiate audio play through a control like a button. This is done because autoplaying audio is usually really annoying and we really shouldn't be subjecting our users to it.
**Note:** Depending on how strict the browser is, such security mechanisms might even stop the example from working locally, i.e. if you load the local example file in your browser instead of running it from a web server. At the time of writing, our Web Audio API example wouldn't work locally on Google Chrome β we had to upload it to GitHub before it would work.
Summary
-------
At this point, you should have a good idea of what APIs are, how they work, and what you can do with them in your JavaScript code. You are probably excited to start actually doing some fun things with specific APIs, so let's go! Next up, we'll look at manipulating documents with the Document Object Model (DOM).
* Overview: Client-side web APIs
* Next |
Manipulating documents - Learn web development | Manipulating documents
======================
* Previous
* Overview: Client-side web APIs
* Next
When writing web pages and apps, one of the most common things you'll want to do is manipulate the document structure in some way. This is usually done by using the Document Object Model (DOM), a set of APIs for controlling HTML and styling information that makes heavy use of the `Document` object. In this article we'll look at how to use the DOM in detail, along with some other interesting APIs that can alter your environment in interesting ways.
| | |
| --- | --- |
| Prerequisites: |
A basic understanding of HTML, CSS, and
JavaScript β including JavaScript objects.
|
| Objective: |
To gain familiarity with the core DOM APIs, and the other APIs commonly
associated with DOM and document manipulation.
|
The important parts of a web browser
------------------------------------
Web browsers are very complicated pieces of software with a lot of moving parts, many of which can't be controlled or manipulated by a web developer using JavaScript. You might think that such limitations are a bad thing, but browsers are locked down for good reasons, mostly centering around security. Imagine if a website could get access to your stored passwords or other sensitive information, and log into websites as if it were you?
Despite the limitations, Web APIs still give us access to a lot of functionality that enable us to do a great many things with web pages. There are a few really obvious bits you'll reference regularly in your code β consider the following diagram, which represents the main parts of a browser directly involved in viewing web pages:
![Important parts of web browser; the document is the web page. The window includes the entire document and also the tab. The navigator is the browser, which includes the window (which includes the document) and all other windows.](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents/document-window-navigator.png)
* The window is the browser tab that a web page is loaded into; this is represented in JavaScript by the `Window` object. Using methods available on this object you can do things like return the window's size (see `Window.innerWidth` and `Window.innerHeight`), manipulate the document loaded into that window, store data specific to that document on the client-side (for example using a local database or other storage mechanism), attach an event handler to the current window, and more.
* The navigator represents the state and identity of the browser (i.e. the user-agent) as it exists on the web. In JavaScript, this is represented by the `Navigator` object. You can use this object to retrieve things like the user's preferred language, a media stream from the user's webcam, etc.
* The document (represented by the DOM in browsers) is the actual page loaded into the window, and is represented in JavaScript by the `Document` object. You can use this object to return and manipulate information on the HTML and CSS that comprises the document, for example get a reference to an element in the DOM, change its text content, apply new styles to it, create new elements and add them to the current element as children, or even delete it altogether.
In this article we'll focus mostly on manipulating the document, but we'll show a few other useful bits besides.
The document object model
-------------------------
The document currently loaded in each one of your browser tabs is represented by a document object model. This is a "tree structure" representation created by the browser that enables the HTML structure to be easily accessed by programming languages β for example the browser itself uses it to apply styling and other information to the correct elements as it renders a page, and developers like you can manipulate the DOM with JavaScript after the page has been rendered.
We have created a simple example page at dom-example.html (see it live also). Try opening this up in your browser β it is a very simple page containing a `<section>` element inside which you can find an image, and a paragraph with a link inside. The HTML source code looks like this:
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>Simple DOM example</title>
</head>
<body>
<section>
<img
src="dinosaur.png"
alt="A red Tyrannosaurus Rex: A two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth." />
<p>
Here we will add a link to the
<a href="https://www.mozilla.org/">Mozilla homepage</a>
</p>
</section>
</body>
</html>
```
The DOM on the other hand looks like this:
![Tree structure representation of Document Object Model: The top node is the doctype and HTML element. Child nodes of the HTML include head and body. Each child element is a branch. All text, even white space, is shown as well.](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents/dom-screenshot.png)
**Note:** This DOM tree diagram was created using Ian Hickson's Live DOM viewer.
Each entry in the tree is called a **node**. You can see in the diagram above that some nodes represent elements (identified as `HTML`, `HEAD`, `META` and so on) and others represent text (identified as `#text`). There are other types of nodes as well, but these are the main ones you'll encounter.
Nodes are also referred to by their position in the tree relative to other nodes:
* **Root node**: The top node in the tree, which in the case of HTML is always the `HTML` node (other markup vocabularies like SVG and custom XML will have different root elements).
* **Child node**: A node *directly* inside another node. For example, `IMG` is a child of `SECTION` in the above example.
* **Descendant node**: A node *anywhere* inside another node. For example, `IMG` is a child of `SECTION` in the above example, and it is also a descendant. `IMG` is not a child of `BODY`, as it is two levels below it in the tree, but it is a descendant of `BODY`.
* **Parent node**: A node which has another node inside it. For example, `BODY` is the parent node of `SECTION` in the above example.
* **Sibling nodes**: Nodes that sit on the same level in the DOM tree. For example, `IMG` and `P` are siblings in the above example.
It is useful to familiarize yourself with this terminology before working with the DOM, as a number of the code terms you'll come across make use of them. You may have also come across them if you have studied CSS (e.g. descendant selector, child selector).
Active learning: Basic DOM manipulation
---------------------------------------
To start learning about DOM manipulation, let's begin with a practical example.
1. Take a local copy of the dom-example.html page and the image that goes along with it.
2. Add a `<script></script>` element just above the closing `</body>` tag.
3. To manipulate an element inside the DOM, you first need to select it and store a reference to it inside a variable. Inside your script element, add the following line:
```js
const link = document.querySelector("a");
```
4. Now we have the element reference stored in a variable, we can start to manipulate it using properties and methods available to it (these are defined on interfaces like `HTMLAnchorElement` in the case of `<a>` element, its more general parent interface `HTMLElement`, and `Node` β which represents all nodes in a DOM). First of all, let's change the text inside the link by updating the value of the `Node.textContent` property. Add the following line below the previous one:
```js
link.textContent = "Mozilla Developer Network";
```
5. We should also change the URL the link is pointing to, so that it doesn't go to the wrong place when it is clicked on. Add the following line, again at the bottom:
```js
link.href = "https://developer.mozilla.org";
```
Note that, as with many things in JavaScript, there are many ways to select an element and store a reference to it in a variable. `Document.querySelector()` is the recommended modern approach. It is convenient because it allows you to select elements using CSS selectors. The above `querySelector()` call will match the first `<a>` element that appears in the document. If you wanted to match and do things to multiple elements, you could use `Document.querySelectorAll()`, which matches every element in the document that matches the selector, and stores references to them in an array-like object called a `NodeList`.
There are older methods available for grabbing element references, such as:
* `Document.getElementById()`, which selects an element with a given `id` attribute value, e.g. `<p id="myId">My paragraph</p>`. The ID is passed to the function as a parameter, i.e. `const elementRef = document.getElementById('myId')`.
* `Document.getElementsByTagName()`, which returns an array-like object containing all the elements on the page of a given type, for example `<p>`s, `<a>`s, etc. The element type is passed to the function as a parameter, i.e. `const elementRefArray = document.getElementsByTagName('p')`.
These two work better in older browsers than the modern methods like `querySelector()`, but are not as convenient. Have a look and see what others you can find!
### Creating and placing new nodes
The above has given you a little taste of what you can do, but let's go further and look at how we can create new elements.
1. Going back to the current example, let's start by grabbing a reference to our `<section>` element β add the following code at the bottom of your existing script (do the same with the other lines too):
```js
const sect = document.querySelector("section");
```
2. Now let's create a new paragraph using `Document.createElement()` and give it some text content in the same way as before:
```js
const para = document.createElement("p");
para.textContent = "We hope you enjoyed the ride.";
```
3. You can now append the new paragraph at the end of the section using `Node.appendChild()`:
```js
sect.appendChild(para);
```
4. Finally for this part, let's add a text node to the paragraph the link sits inside, to round off the sentence nicely. First we will create the text node using `Document.createTextNode()`:
```js
const text = document.createTextNode(
" β the premier source for web development knowledge.",
);
```
5. Now we'll grab a reference to the paragraph the link is inside, and append the text node to it:
```js
const linkPara = document.querySelector("p");
linkPara.appendChild(text);
```
That's most of what you need for adding nodes to the DOM β you'll make a lot of use of these methods when building dynamic interfaces (we'll look at some examples later).
### Moving and removing elements
There may be times when you want to move nodes, or delete them from the DOM altogether. This is perfectly possible.
If we wanted to move the paragraph with the link inside it to the bottom of the section, we could do this:
```js
sect.appendChild(linkPara);
```
This moves the paragraph down to the bottom of the section. You might have thought it would make a second copy of it, but this is not the case β `linkPara` is a reference to the one and only copy of that paragraph. If you wanted to make a copy and add that as well, you'd need to use `Node.cloneNode()` instead.
Removing a node is pretty simple as well, at least when you have a reference to the node to be removed and its parent. In our current case, we just use `Node.removeChild()`, like this:
```js
sect.removeChild(linkPara);
```
When you want to remove a node based only on a reference to itself, which is fairly common, you can use `Element.remove()`:
```js
linkPara.remove();
```
This method is not supported in older browsers. They have no method to tell a node to remove itself, so you'd have to do the following.
```js
linkPara.parentNode.removeChild(linkPara);
```
Have a go at adding the above lines to your code.
### Manipulating styles
It is possible to manipulate CSS styles via JavaScript in a variety of ways.
To start with, you can get a list of all the stylesheets attached to a document using `Document.stylesheets`, which returns an array-like object with `CSSStyleSheet` objects. You can then add/remove styles as wished. However, we're not going to expand on those features because they are a somewhat archaic and difficult way to manipulate style. There are much easier ways.
The first way is to add inline styles directly onto elements you want to dynamically style. This is done with the `HTMLElement.style` property, which contains inline styling information for each element in the document. You can set properties of this object to directly update element styles.
1. As an example, try adding these lines to our ongoing example:
```js
para.style.color = "white";
para.style.backgroundColor = "black";
para.style.padding = "10px";
para.style.width = "250px";
para.style.textAlign = "center";
```
2. Reload the page and you'll see that the styles have been applied to the paragraph. If you look at that paragraph in your browser's Page Inspector/DOM inspector, you'll see that these lines are indeed adding inline styles to the document:
```html
<p
style="color: white; background-color: black; padding: 10px; width: 250px; text-align: center;">
We hope you enjoyed the ride.
</p>
```
**Note:** Notice how the JavaScript property versions of the CSS styles are written in lower camel case whereas the CSS versions are hyphenated (kebab-case) (e.g. `backgroundColor` versus `background-color`). Make sure you don't get these mixed up, otherwise it won't work.
There is another common way to dynamically manipulate styles on your document, which we'll look at now.
1. Delete the previous five lines you added to the JavaScript.
2. Add the following inside your HTML `<head>`:
```html
<style>
.highlight {
color: white;
background-color: black;
padding: 10px;
width: 250px;
text-align: center;
}
</style>
```
3. Now we'll turn to a very useful method for general HTML manipulation β `Element.setAttribute()` β this takes two arguments, the attribute you want to set on the element, and the value you want to set it to. In this case we will set a class name of highlight on our paragraph:
```js
para.setAttribute("class", "highlight");
```
4. Refresh your page, and you'll see no change β the CSS is still applied to the paragraph, but this time by giving it a class that is selected by our CSS rule, not as inline CSS styles.
Which method you choose is up to you; both have their advantages and disadvantages. The first method takes less setup and is good for simple uses, whereas the second method is more purist (no mixing CSS and JavaScript, no inline styles, which are seen as a bad practice). As you start building larger and more involved apps, you will probably start using the second method more, but it is really up to you.
At this point, we haven't really done anything useful! There is no point using JavaScript to create static content β you might as well just write it into your HTML and not use JavaScript. It is more complex than HTML, and creating your content with JavaScript also has other issues attached to it (such as not being readable by search engines).
In the next section we will look at a more practical use of DOM APIs.
**Note:** You can find our finished version of the dom-example.html demo on GitHub (see it live also).
Active learning: A dynamic shopping list
----------------------------------------
In this challenge we want to make a simple shopping list example that allows you to dynamically add items to the list using a form input and button. When you add an item to the input and press the button:
* The item should appear in the list.
* Each item should be given a button that can be pressed to delete that item off the list.
* The input should be emptied and focused ready for you to enter another item.
The finished demo will look something like this:
![Demo layout of a shopping list. A 'my shopping list' header followed by 'Enter a new item' with an input field and 'add item' button. The list of already added items is below, each with a corresponding delete button. ](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents/shopping-list.png)
To complete the exercise, follow the steps below, and make sure that the list behaves as described above.
1. To start with, download a copy of our shopping-list.html starting file and make a copy of it somewhere. You'll see that it has some minimal CSS, a div with a label, input, and button, and an empty list and `<script>` element. You'll be making all your additions inside the script.
2. Create three variables that hold references to the list (`<ul>`), `<input>`, and `<button>` elements.
3. Create a function that will run in response to the button being clicked.
4. Inside the function body, start off by storing the current value of the input element in a variable.
5. Next, empty the input element by setting its value to an empty string β `''`.
6. Create three new elements β a list item (`<li>`), `<span>`, and `<button>`, and store them in variables.
7. Append the span and the button as children of the list item.
8. Set the text content of the span to the input element value you saved earlier, and the text content of the button to 'Delete'.
9. Append the list item as a child of the list.
10. Attach an event handler to the delete button so that, when clicked, it will delete the entire list item (`<li>...</li>`).
11. Finally, use the `focus()` method to focus the input element ready for entering the next shopping list item.
**Note:** If you get really stuck, have a look at our finished shopping list (see it running live also).
Summary
-------
We have reached the end of our study of document and DOM manipulation. At this point you should understand what the important parts of a web browser are with respect to controlling documents and other aspects of the user's web experience. Most importantly, you should understand what the Document Object Model is, and how to manipulate it to create useful functionality.
See also
--------
There are lots more features you can use to manipulate your documents. Check out some of our references and see what you can discover:
* `Document`
* `Window`
* `Node`
* `HTMLElement`, `HTMLInputElement`, `HTMLImageElement`, etc.
(See our Web API index for the full list of Web APIs documented on MDN!)
* Previous
* Overview: Client-side web APIs
* Next |
Fetching data from the server - Learn web development | Fetching data from the server
=============================
* Previous
* Overview: Client-side web APIs
* Next
Another very common task in modern websites and applications is retrieving individual data items from the server to update sections of a webpage without having to load an entire new page. This seemingly small detail has had a huge impact on the performance and behavior of sites, so in this article, we'll explain the concept and look at technologies that make it possible: in particular, the Fetch API.
| | |
| --- | --- |
| Prerequisites: |
JavaScript basics (see
first steps,
building blocks,
JavaScript objects),
the
basics of Client-side APIs |
| Objective: |
To learn how to fetch data from the server and use it to update the
contents of a web page.
|
What is the problem here?
-------------------------
A web page consists of an HTML page and (usually) various other files, such as stylesheets, scripts, and images. The basic model of page loading on the Web is that your browser makes one or more HTTP requests to the server for the files needed to display the page, and the server responds with the requested files. If you visit another page, the browser requests the new files, and the server responds with them.
![Traditional page loading](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data/traditional-loading.svg)
This model works perfectly well for many sites. But consider a website that's very data-driven. For example, a library website like the Vancouver Public Library. Among other things you could think of a site like this as a user interface to a database. It might let you search for a particular genre of book, or might show you recommendations for books you might like, based on books you've previously borrowed. When you do this, it needs to update the page with the new set of books to display. But note that most of the page content β including items like the page header, sidebar, and footer β stays the same.
The trouble with the traditional model here is that we'd have to fetch and load the entire page, even when we only need to update one part of it. This is inefficient and can result in a poor user experience.
So instead of the traditional model, many websites use JavaScript APIs to request data from the server and update the page content without a page load. So when the user searches for a new product, the browser only requests the data which is needed to update the page β the set of new books to display, for instance.
![Using fetch to update pages](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data/fetch-update.svg)
The main API here is the Fetch API. This enables JavaScript running in a page to make an HTTP request to a server to retrieve specific resources. When the server provides them, the JavaScript can use the data to update the page, typically by using DOM manipulation APIs. The data requested is often JSON, which is a good format for transferring structured data, but can also be HTML or just text.
This is a common pattern for data-driven sites such as Amazon, YouTube, eBay, and so on. With this model:
* Page updates are a lot quicker and you don't have to wait for the page to refresh, meaning that the site feels faster and more responsive.
* Less data is downloaded on each update, meaning less wasted bandwidth. This may not be such a big issue on a desktop on a broadband connection, but it's a major issue on mobile devices and in countries that don't have ubiquitous fast internet service.
**Note:** In the early days, this general technique was known as Asynchronous JavaScript and XML (Ajax), because it tended to request XML data. This is normally not the case these days (you'd be more likely to request JSON), but the result is still the same, and the term "Ajax" is still often used to describe the technique.
To speed things up even further, some sites also store assets and data on the user's computer when they are first requested, meaning that on subsequent visits they use the local versions instead of downloading fresh copies every time the page is first loaded. The content is only reloaded from the server when it has been updated.
The Fetch API
-------------
Let's walk through a couple of examples of the Fetch API.
### Fetching text content
For this example, we'll request data out of a few different text files and use them to populate a content area.
This series of files will act as our fake database; in a real application, we'd be more likely to use a server-side language like PHP, Python, or Node to request our data from a database. Here, however, we want to keep it simple and concentrate on the client-side part of this.
To begin this example, make a local copy of fetch-start.html and the four text files β verse1.txt, verse2.txt, verse3.txt, and verse4.txt β in a new directory on your computer. In this example, we will fetch a different verse of the poem (which you may well recognize) when it's selected in the drop-down menu.
Just inside the `<script>` element, add the following code. This stores references to the `<select>` and `<pre>` elements and adds a listener to the `<select>` element, so that when the user selects a new value, the new value is passed to the function named `updateDisplay()` as a parameter.
```js
const verseChoose = document.querySelector("select");
const poemDisplay = document.querySelector("pre");
verseChoose.addEventListener("change", () => {
const verse = verseChoose.value;
updateDisplay(verse);
});
```
Let's define our `updateDisplay()` function. First of all, put the following beneath your previous code block β this is the empty shell of the function.
```js
function updateDisplay(verse) {
}
```
We'll start our function by constructing a relative URL pointing to the text file we want to load, as we'll need it later. The value of the `<select>` element at any time is the same as the text inside the selected `<option>` (unless you specify a different value in a value attribute) β so for example "Verse 1". The corresponding verse text file is "verse1.txt", and is in the same directory as the HTML file, therefore just the file name will do.
However, web servers tend to be case-sensitive, and the file name doesn't have a space in it. To convert "Verse 1" to "verse1.txt" we need to convert the 'V' to lower case, remove the space, and add ".txt" on the end. This can be done with `replace()`, `toLowerCase()`, and template literal. Add the following lines inside your `updateDisplay()` function:
```js
verse = verse.replace(" ", "").toLowerCase();
const url = `${verse}.txt`;
```
Finally we're ready to use the Fetch API:
```js
// Call `fetch()`, passing in the URL.
fetch(url)
// fetch() returns a promise. When we have received a response from the server,
// the promise's `then()` handler is called with the response.
.then((response) => {
// Our handler throws an error if the request did not succeed.
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
// Otherwise (if the response succeeded), our handler fetches the response
// as text by calling response.text(), and immediately returns the promise
// returned by `response.text()`.
return response.text();
})
// When response.text() has succeeded, the `then()` handler is called with
// the text, and we copy it into the `poemDisplay` box.
.then((text) => {
poemDisplay.textContent = text;
})
// Catch any errors that might happen, and display a message
// in the `poemDisplay` box.
.catch((error) => {
poemDisplay.textContent = `Could not fetch verse: ${error}`;
});
```
There's quite a lot to unpack in here.
First, the entry point to the Fetch API is a global function called `fetch()`, that takes the URL as a parameter (it takes another optional parameter for custom settings, but we're not using that here).
Next, `fetch()` is an asynchronous API which returns a `Promise`. If you don't know what that is, read the module on asynchronous JavaScript, and in particular the article on promises, then come back here. You'll find that article also talks about the `fetch()` API!
So because `fetch()` returns a promise, we pass a function into the `then()` method of the returned promise. This method will be called when the HTTP request has received a response from the server. In the handler, we check that the request succeeded, and throw an error if it didn't. Otherwise, we call `response.text()`, to get the response body as text.
It turns out that `response.text()` is *also* asynchronous, so we return the promise it returns, and pass a function into the `then()` method of this new promise. This function will be called when the response text is ready, and inside it we will update our `<pre>` block with the text.
Finally, we chain a `catch()` handler at the end, to catch any errors thrown in either of the asynchronous functions we called or their handlers.
One problem with the example as it stands is that it won't show any of the poem when it first loads. To fix this, add the following two lines at the bottom of your code (just above the closing `</script>` tag) to load verse 1 by default, and make sure the `<select>` element always shows the correct value:
```js
updateDisplay("Verse 1");
verseChoose.value = "Verse 1";
```
#### Serving your example from a server
Modern browsers will not run HTTP requests if you just run the example from a local file. This is because of security restrictions (for more on web security, read Website security).
To get around this, we need to test the example by running it through a local web server. To find out how to do this, read our guide to setting up a local testing server.
### The can store
In this example we have created a sample site called The Can Store β it's a fictional supermarket that only sells canned goods. You can find this example live on GitHub, and see the source code.
![A fake e-commerce site showing search options in the left hand column, and product search results in the right-hand column.](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data/can-store.png)
By default, the site displays all the products, but you can use the form controls in the left-hand column to filter them by category, or search term, or both.
There is quite a lot of complex code that deals with filtering the products by category and search terms, manipulating strings so the data displays correctly in the UI, etc. We won't discuss all of it in the article, but you can find extensive comments in the code (see can-script.js).
We will, however, explain the Fetch code.
The first block that uses Fetch can be found at the start of the JavaScript:
```js
fetch("products.json")
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json();
})
.then((json) => initialize(json))
.catch((err) => console.error(`Fetch problem: ${err.message}`));
```
The `fetch()` function returns a promise. If this completes successfully, the function inside the first `.then()` block contains the `response` returned from the network.
Inside this function we:
* check that the server didn't return an error (such as `404 Not Found`). If it did, we throw the error.
* call `json()` on the response. This will retrieve the data as a JSON object. We return the promise returned by `response.json()`.
Next we pass a function into the `then()` method of that returned promise. This function will be passed an object containing the response data as JSON, which we pass into the `initialize()` function. This function which starts the process of displaying all the products in the user interface.
To handle errors, we chain a `.catch()` block onto the end of the chain. This runs if the promise fails for some reason. Inside it, we include a function that is passed as a parameter, an `err` object. This `err` object can be used to report the nature of the error that has occurred, in this case we do it with a simple `console.error()`.
However, a complete website would handle this error more gracefully by displaying a message on the user's screen and perhaps offering options to remedy the situation, but we don't need anything more than a simple `console.error()`.
You can test the failure case yourself:
1. Make a local copy of the example files.
2. Run the code through a web server (as described above, in Serving your example from a server).
3. Modify the path to the file being fetched, to something like 'produc.json' (make sure it is misspelled).
4. Now load the index file in your browser (via `localhost:8000`) and look in your browser developer console. You'll see a message similar to "Fetch problem: HTTP error: 404".
The second Fetch block can be found inside the `fetchBlob()` function:
```js
fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.blob();
})
.then((blob) => showProduct(blob, product))
.catch((err) => console.error(`Fetch problem: ${err.message}`));
```
This works in much the same way as the previous one, except that instead of using `json()`, we use `blob()`. In this case we want to return our response as an image file, and the data format we use for that is Blob (the term is an abbreviation of "Binary Large Object" and can basically be used to represent large file-like objects, such as images or video files).
Once we've successfully received our blob, we pass it into our `showProduct()` function, which displays it.
The XMLHttpRequest API
----------------------
Sometimes, especially in older code, you'll see another API called `XMLHttpRequest` (often abbreviated as "XHR") used to make HTTP requests. This predated Fetch, and was really the first API widely used to implement AJAX. We recommend you use Fetch if you can: it's a simpler API and has more features than `XMLHttpRequest`. We won't go through an example that uses `XMLHttpRequest`, but we will show you what the `XMLHttpRequest` version of our first can store request would look like:
```js
const request = new XMLHttpRequest();
try {
request.open("GET", "products.json");
request.responseType = "json";
request.addEventListener("load", () => initialize(request.response));
request.addEventListener("error", () => console.error("XHR error"));
request.send();
} catch (error) {
console.error(`XHR error ${request.status}`);
}
```
There are five stages to this:
1. Create a new `XMLHttpRequest` object.
2. Call its `open()` method to initialize it.
3. Add an event listener to its `load` event, which fires when the response has completed successfully. In the listener we call `initialize()` with the data.
4. Add an event listener to its `error` event, which fires when the request encounters an error
5. Send the request.
We also have to wrap the whole thing in the try...catch block, to handle any errors thrown by `open()` or `send()`.
Hopefully you think the Fetch API is an improvement over this. In particular, see how we have to handle errors in two different places.
Summary
-------
This article shows how to start working with Fetch to fetch data from the server.
See also
--------
There are however a lot of different subjects discussed in this article, which has only really scratched the surface. For a lot more detail on these subjects, try the following articles:
* Using Fetch
* Promises
* Working with JSON data
* An overview of HTTP
* Server-side website programming
* Previous
* Overview: Client-side web APIs
* Next |
Cross browser testing - Learn web development | Cross browser testing
=====================
This module focuses on testing web projects across different browsers. We look at identifying your target audience (e.g. what users, browsers, and devices do you most need to worry about?), how to go about doing testing, the main issues that you'll face with different types of code and how to mitigate them, what tools are most useful in helping you test and fix problems, and how to use automation to speed up testing.
#### Looking to become a front-end web developer?
We have put together a course that includes all the essential information you need to
work towards your goal.
**Get started**
Prerequisites
-------------
You should really learn the basics of the core HTML, CSS, and JavaScript languages first before attempting to use the tools detailed here.
Guides
------
Introduction to cross browser testing
This article starts the module off by providing an overview of the topic of cross browser testing, answering questions such as "what is cross browser testing?", "what are the most common types of problems you'll encounter?", and "what are the main approaches for testing, identifying, and fixing problems?"
Strategies for carrying out testing
Next, we drill down into carrying out testing, looking at identifying a target audience (e.g. what browsers, devices, and other segments should you make sure are tested), lo-fi testing strategies (get yourself a range of devices and some virtual machines and do ad hoc tests when needed), higher tech strategies (automation, using dedicated testing apps), and testing with user groups.
Handling common HTML and CSS problems
With the scene set, we'll now look specifically at the common cross-browser problems you will come across in HTML and CSS code, and what tools can be used to prevent problems from happening, or fix problems that occur. This includes linting code, handling CSS prefixes, using browser dev tools to track down problems, using polyfills to add support into browsers, tackling responsive design problems, and more.
Handling common JavaScript problems
Now we'll look at common cross-browser JavaScript problems and how to fix them. This includes information on using browser dev tools to track down and fix problems, using polyfills and libraries to work around problems, getting modern JavaScript features working in older browsers, and more.
Handling common accessibility problems
Next we turn our attention to accessibility, providing information on common problems, how to do simple testing, and how to make use of auditing/automation tools for finding accessibility issues.
Implementing feature detection
Feature detection involves working out whether a browser supports a certain block of code, and running different code dependent on whether it does (or doesn't), so that the browser can always provide a working experience rather than crashing/erroring in some browsers. This article details how to write your own simple feature detection, how to use a library to speed up implementation, and native features for feature detection such as `@supports`.
Introduction to automated testing
Manually running tests on several browsers and devices, several times per day, can get tedious and time-consuming. To handle this efficiently, you should become familiar with automation tools. In this article, we look at what is available, how to use task runners, and the basics of how to use commercial browser test automation apps such as Sauce Labs and Browser Stack.
Setting up your own test automation environment
In this article, we will teach you how to install your own automation environment and run your own tests using Selenium/WebDriver and a testing library such as selenium-webdriver for Node. We will also look at how to integrate your local testing environment with commercial apps like the ones discussed in the previous article. |
Git and GitHub - Learn web development | Git and GitHub
==============
All developers will use some kind of **version control system** (**VCS**), a tool to allow them to collaborate with other developers on a project without the danger of them overwriting each other's work, and roll back to previous versions of the code base if a problem is discovered later on. The most popular VCS (at least among web developers) is **Git**, along with **GitHub**, a site that provides hosting for your repositories and several tools for working with them. This module aims to teach you what you need to know about both of them.
Overview
--------
VCSes are essential for software development:
* It is rare that you will work on a project completely on your own, and as soon as you start working with other people you start to run the risk of conflicting with each other's work β this is when both of you try to update the same piece of code at the same time. You need to have some kind of mechanism in place to manage the occurrences, and help avoid loss of work as a result.
* When working on a project on your own or with others, you'll want to be able to back up the code in a central place, so it is not lost if your computer breaks.
* You will also want to be able to roll back to earlier versions if a problem is later discovered. You might have started doing this in your own work by creating different versions of the same file, e.g. `myCode.js`, `myCode_v2.js`, `myCode_v3.js`, `myCode_final.js`, `myCode_really_really_final.js`, etc., but this is really error-prone and unreliable.
* Different team members will commonly want to create their own separate versions of the code (called **branches** in Git), work on a new feature in that version, and then get it merged in a controlled manner (in GitHub we use **pull requests**) with the master version when they are done with it.
VCSes provide tools to meet the above needs. Git is an example of a VCS, and GitHub is a website + infrastructure that provides a Git server plus a number of really useful tools for working with git repositories individually or in teams, such as reporting issues with the code, reviewing tools, project management features such as assigning tasks and task statuses, and more.
**Note:** Git is actually a *distributed* version control system, meaning that a complete copy of the repository containing the codebase is made on your computer (and everyone else's). You make changes to your own copy and then push those changes back up to the server, where an administrator will decide whether to merge your changes with the master copy.
#### Looking to become a front-end web developer?
We have put together a course that includes all the essential information you need to
work towards your goal.
**Get started**
Prerequisites
-------------
To use Git and GitHub, you need:
* A desktop computer with Git installed on it (see the Git downloads page).
* A tool to use Git. Depending on how you like to work, you could use a Git GUI client (we'd recommend GitHub Desktop, SourceTree or Git Kraken) or just stick to using a terminal window. In fact, it is probably useful for you to get to know at least the basics of git terminal commands, even if you intend to use a GUI.
* A GitHub account. If you haven't already got one, sign up now using the provided link.
In terms of prerequisite knowledge, you don't need to know anything about web development, Git/GitHub, or VCSes to start this module. However, it is recommended that you know some coding so that you have reasonable computer literacy, and some code to store in your repositories!
It is also preferable that you have some basic terminal knowledge, so for example moving between directories, creating files, and modifying the system `PATH`.
**Note:** GitHub is not the only site/toolset you can use with Git. There are other alternatives such as GitLab that you could try, and you could also try setting your own Git server up and using it instead of GitHub. We've only stuck with GitHub in this course to provide a single way that works.
Guides
------
Note that the links below take you to resources on external sites. Eventually, we are aiming to have our own dedicated Git/GitHub course, but for now, these will help you get to grips with the subject at hand.
Hello, World (from GitHub)
This is a good place to start β this practical guide gets you to jump right into using GitHub, learning the basics of Git such as creating repositories and branches, making commits, and opening and merging pull requests.
Git Handbook (from GitHub)
This Git Handbook goes into a little more depth, explaining what a VCS is, what a repository is, how the basic GitHub model works, Git commands and examples, and more.
Forking Projects (from GitHub)
Forking projects is essential when you want to contribute to someone else's code. This guide explains how.
About Pull Requests (from GitHub)
A useful guide to managing pull requests, the way that your suggested code changes are delivered to people's repositories for consideration.
Mastering issues (from GitHub)
Issues are like a forum for your GitHub project, where people can ask questions and report problems, and you can manage updates (for example assigning people to fix issues, clarifying the issue, letting people know things are fixed). This article tells you what you need to know about issues.
**Note:** There is **a lot more** that you can do with Git and GitHub, but we feel that the above represents the minimum you need to know to start using Git effectively. As you get deeper into Git, you'll start to realize that it is easy to go wrong when you start using more complicated commands. Don't worry, even professional web developers find Git confusing sometimes, and often solve problems by searching for solutions on the web, or consulting sites like Flight rules for Git and Dangit, git!
See also
--------
* Understanding the GitHub flow
* Git command list
* Mastering markdown (the text format you write in on PR, issue comments, and `.md` files).
* Getting Started with GitHub Pages (how to publish demos and websites on GitHub).
* Learn Git branching
* Flight rules for Git (a very useful compendium of ways to achieve specific things in Git, including how to correct things when you went wrong).
* Dangit, git! (another useful compendium, specifically of ways to correct things when you went wrong). |
Understanding client-side web development tools - Learn web development | Understanding client-side web development tools
===============================================
Client-side tooling can be intimidating, but this series of articles aims to illustrate the purpose of some of the most common client-side tool types, explain the tools you can chain together, how to install them using package managers, and control them using the command line. We finish up by providing a complete toolchain example showing you how to get productive.
Prerequisites
-------------
You should really learn the basics of the core HTML, CSS, and JavaScript languages first before attempting to use the tools detailed here.
#### Looking to become a front-end web developer?
We have put together a course that includes all the essential information you need to
work towards your goal.
**Get started**
Guides
------
1. Client-side tooling overview
In this article we provide an overview of modern web tooling, what kinds of tools are available and where you'll meet them in the lifecycle of web app development, and how to find help with individual tools.
2. Command line crash course
In your development process you'll undoubtedly be required to run some command in the terminal (or on the "command line" β these are effectively the same thing). This article provides an introduction to the terminal, the essential commands you'll need to enter into it, how to chain commands together, and how to add your own command line interface (CLI) tools.
3. Package management basics
In this article we'll look at package managers in some detail to understand how we can use them in our own projects β to install project tool dependencies, keep them up-to-date, and more.
4. Introducing a complete toolchain
In the final couple of articles in the series we will solidify your tooling knowledge by walking you through the process of building up a sample case study toolchain. We'll go all the way from setting up a sensible development environment and putting transformation tools in place to actually deploying your app on Netlify. In this article we'll introduce the case study, set up our development environment, and set up our code transformation tools.
5. Deploying our app
In the final article in our series, we take the example toolchain we built up in the previous article and add to it so that we can deploy our sample app. We push the code to GitHub, deploy it using Netlify, and even show you how to add a simple test into the process. |
Understanding client-side JavaScript frameworks - Learn web development | Understanding client-side JavaScript frameworks
===============================================
JavaScript frameworks are an essential part of modern front-end web development, providing developers with tried and tested tools for building scalable, interactive web applications. Many modern companies use frameworks as a standard part of their tooling, so many front-end development jobs now require framework experience. In this set of articles, we are aiming to give you a comfortable starting point to help you begin learning frameworks.
As an aspiring front-end developer, it can be hard to work out where to begin when learning frameworks β there are so many frameworks to choose from, new ones appear all the time, they mostly work in a similar way but do some things differently, and there are some specific things to be careful about when using frameworks.
We are not aiming to exhaustively teach you everything you need to know about React/ReactDOM, or Vue, or some other specific framework; the framework teams' own docs (and other resources) do that job already. Instead, we want to back up and first answer more fundamental questions such as:
* Why should I use a framework? What problems do they solve for me?
* What questions should I ask when trying to choose a framework? Do I even need to use a framework?
* What features do frameworks have? How do they work in general, and how do frameworks' implementations of these features differ?
* How do they relate to "vanilla" JavaScript or HTML?
After that, we'll provide some tutorials covering the essentials of some of the different framework choices, to provide you with enough context and familiarity to start going into greater depth yourself. We want you to go forward and learn about frameworks in a pragmatic way that doesn't forget about web platform fundamental best practices such as accessibility.
**Get started now, with "Introduction to client-side frameworks"**
Prerequisites
-------------
You should really learn the basics of the core web languages first before attempting to move on to learning client-side frameworks β HTML, CSS, and especially JavaScript.
Your code will be richer and more professional as a result, and you'll be able to troubleshoot problems with more confidence if you understand the fundamental web platform features that the frameworks are building on top of.
#### Looking to become a front-end web developer?
We have put together a course that includes all the essential information you need to
work towards your goal.
**Get started**
Introductory guides
-------------------
1. Introduction to client-side frameworks
We begin our look at frameworks with a general overview of the area, looking at a brief history of JavaScript and frameworks, why frameworks exist and what they give us, how to start thinking about choosing a framework to learn, and what alternatives there are to client-side frameworks.
2. Framework main features
Each major JavaScript framework has a different approach to updating the DOM, handling browser events, and providing an enjoyable developer experience. This article will explore the main features of "the big 4" frameworks, looking at how frameworks tend to work from a high level and the differences between them.
React tutorials
---------------
**Note:** React tutorials last tested in January 2023, with React/ReactDOM 18.2.0 and create-react-app 5.0.1.
If you need to check your code against our version, you can find a finished version of the sample React app code in our todo-react repository. For a running live version, see https://mdn.github.io/todo-react/.
1. Getting started with React
In this article we will say hello to React. We'll discover a little bit of detail about its background and use cases, set up a basic React toolchain on our local computer, and create and play with a simple starter app, learning a bit about how React works in the process.
2. Beginning our React todo list
Let's say that we've been tasked with creating a proof-of-concept in React β an app that allows users to add, edit, and delete tasks they want to work on, and also mark tasks as complete without deleting them. This article will walk you through putting the basic `App` component structure and styling in place, ready for individual component definition and interactivity, which we'll add later.
3. Componentizing our React app
At this point, our app is a monolith. Before we can make it do things, we need to break it apart into manageable, descriptive components. React doesn't have any hard rules for what is and isn't a component β that's up to you! In this article, we will show you a sensible way to break our app up into components.
4. React interactivity: Events and state
With our component plan worked out, it's now time to start updating our app from a completely static UI to one that actually allows us to interact and change things. In this article we'll do this, digging into events and state along the way.
5. React interactivity: Editing, filtering, conditional rendering
As we near the end of our React journey (for now at least), we'll add the finishing touches to the main areas of functionality in our Todo list app. This includes allowing you to edit existing tasks and filtering the list of tasks between all, completed, and incomplete tasks. We'll look at conditional UI rendering along the way.
6. Accessibility in React
In our final tutorial article, we'll focus on (pun intended) accessibility, including focus management in React, which can improve usability and reduce confusion for both keyboard-only and screen reader users.
7. React resources
Our final article provides you with a list of React resources that you can use to go further in your learning.
Ember tutorials
---------------
**Note:** Ember tutorials last tested in May 2020, with Ember/Ember CLI version 3.18.0.
If you need to check your code against our version, you can find a finished version of the sample Ember app code in the ember-todomvc-tutorial repository. For a running live version, see https://nullvoxpopuli.github.io/ember-todomvc-tutorial/ (this also includes a few additional features not covered in the tutorial).
1. Getting started with Ember
In our first Ember article we will look at how Ember works and what it's useful for, install the Ember toolchain locally, create a sample app, and then do some initial setup to get it ready for development.
2. Ember app structure and componentization
In this article we'll get right on with planning out the structure of our TodoMVC Ember app, adding in the HTML for it, and then breaking that HTML structure into components.
3. Ember interactivity: Events, classes and state
At this point we'll start adding some interactivity to our app, providing the ability to add and display new todo items. Along the way, we'll look at using events in Ember, creating component classes to contain JavaScript code to control interactive features, and setting up a service to keep track of the data state of our app.
4. Ember Interactivity: Footer functionality, conditional rendering
Now it's time to start tackling the footer functionality in our app. Here we'll get the todo counter to update to show the correct number of todos still to complete, and correctly apply styling to completed todos (i.e. where the checkbox has been checked). We'll also wire up our "Clear completed" button. Along the way, we'll learn about using conditional rendering in our templates.
5. Routing in Ember
In this article we learn about routing or URL-based filtering as it is sometimes referred to. We'll use it to provide a unique URL for each of the three todo views β "All", "Active", and "Completed".
6. Ember resources and troubleshooting
Our final Ember article provides you with a list of resources that you can use to go further in your learning, plus some useful troubleshooting and other information.
Vue tutorials
-------------
**Note:** Vue tutorial last tested in January 2023, with Vue 3.2.45.
If you need to check your code against our version, you can find a finished version of the sample Vue app code in our todo-vue repository. For a running live version, see https://mdn.github.io/todo-vue/.
1. Getting started with Vue
Now let's introduce Vue, the third of our frameworks. In this article, we'll look at a little bit of Vue background, learn how to install it and create a new project, study the high-level structure of the whole project and an individual component, see how to run the project locally, and get it prepared to start building our example.
2. Creating our first Vue component
Now it's time to dive deeper into Vue, and create our own custom component β we'll start by creating a component to represent each item in the todo list. Along the way, we'll learn about a few important concepts such as calling components inside other components, passing data to them via props and saving data state.
3. Rendering a list of Vue components
At this point we've got a fully working component; we're now ready to add multiple `ToDoItem` components to our app. In this article we'll look at adding a set of todo item data to our `App.vue` component, which we'll then loop through and display inside `ToDoItem` components using the `v-for` directive.
4. Adding a new todo form: Vue events, methods, and models
We now have sample data in place and a loop that takes each bit of data and renders it inside a `ToDoItem` in our app. What we really need next is the ability to allow our users to enter their own todo items into the app, and for that, we'll need a text `<input>`, an event to fire when the data is submitted, a method to fire upon submission to add the data and rerender the list, and a model to control the data. This is what we'll cover in this article.
5. Styling Vue components with CSS
The time has finally come to make our app look a bit nicer. In this article, we'll explore the different ways of styling Vue components with CSS.
6. Using Vue computed properties
In this article we'll add a counter that displays the number of completed todo items, using a feature of Vue called computed properties. These work similarly to methods but only re-run when one of their dependencies changes.
7. Vue conditional rendering: editing existing todos
Now it is time to add one of the major parts of functionality that we're still missing β the ability to edit existing todo items. To do this, we will take advantage of Vue's conditional rendering capabilities β namely `v-if` and `v-else` β to allow us to toggle between the existing todo item view and an edit view where you can update todo item labels. We'll also look at adding functionality to delete todo items.
8. Focus management with Vue refs
We are nearly done with Vue. The last bit of functionality to look at is focus management, or put another way, how we can improve our app's keyboard accessibility. We'll look at using Vue refs to handle this β an advanced feature that allows you to have direct access to the underlying DOM nodes below the virtual DOM, or direct access from one component to the internal DOM structure of a child component.
9. Vue resources
Now we'll round off our study of Vue by giving you a list of resources that you can use to go further in your learning, plus some other useful tips.
Svelte tutorials
----------------
**Note:** Svelte tutorials last tested in August 2020, with Svelte 3.24.1.
If you need to check your code against our version, you can find a finished version of the sample Svelte app code as it should be after each article, in our mdn-svelte-tutorial repo. For a running live version, see our Svelte REPL at https://svelte.dev/repl/378dd79e0dfe4486a8f10823f3813190?version=3.23.2.
1. Getting started with Svelte
In this article we'll provide a quick introduction to the Svelte framework. We will see how Svelte works and what sets it apart from the rest of the frameworks and tools we've seen so far. Then we will learn how to set up our development environment, create a sample app, understand the structure of the project, and see how to run it locally and build it for production.
2. Starting our Svelte Todo list app
Now that we have a basic understanding of how things work in Svelte, we can start building our example app: a todo list. In this article we will first have a look at the desired functionality of our app, then we'll create a `Todos.svelte` component and put static markup and styles in place, leaving everything ready to start developing our To-Do list app features, which we'll go on to in subsequent articles.
3. Dynamic behavior in Svelte: working with variables and props
Now that we have our markup and styles ready we can start developing the required features for our Svelte To-Do list app. In this article we'll be using variables and props to make our app dynamic, allowing us to add and delete todos, mark them as complete, and filter them by status.
4. Componentizing our Svelte app
The central objective of this article is to look at how to break our app into manageable components and share information between them. We'll componentize our app, then add more functionality to allow users to update existing components.
5. Advanced Svelte: Reactivity, lifecycle, accessibility
In this article we will add the app's final features and further componentize our app. We will learn how to deal with reactivity issues related to updating objects and arrays. To avoid common pitfalls, we'll have to dig a little deeper into Svelte's reactivity system. We'll also look at solving some accessibility focus issues, and more besides.
6. Working with Svelte stores
In this article we will show another way to handle state management in Svelte β Stores. Stores are global data repositories that hold values. Components can subscribe to stores and receive notifications when their values change.
7. TypeScript support in Svelte
We will now learn how to use TypeScript in Svelte applications. First we'll learn what TypeScript is and what benefits it can bring us. Then we'll see how to configure our project to work with TypeScript files. Finally we will go over our app and see what modifications we have to make to fully take advantage of TypeScript features.
8. Deployment and next steps
In this final article we will look at how to deploy your application and get it online, and also share some of the resources that you should go on to, to continue your Svelte learning journey.
Angular tutorials
-----------------
**Note:** Angular tutorials last tested in April 2021, with Angular CLI (NG) 11.2.5.
1. Getting started with Angular
In this article we look at what Angular has to offer, install the prerequisites and set up a sample app, and look at Angular's basic architecture.
2. Beginning our Angular todo list app
At this point, we are ready to start creating our to-do list application using Angular. The finished application will display a list of to-do items and includes editing, deleting, and adding features. In this article you will get to know your application structure, and work up to displaying a basic list of to-do items.
3. Styling our Angular app
Now that we've got our basic application structure set up and started displaying something useful, let's switch gears and spend an article looking at how Angular handles styling of applications.
4. Creating an item component
Components provide a way for you to organize your application. This article walks you through creating a component to handle the individual items in the list, and adding check, edit, and delete functionality. The Angular event model is covered here.
5. Filtering our to-do items
Now let's move on to adding functionality to allow users to filter their to-do items, so they can view active, completed, or all items.
6. Building Angular applications and further resources
This final Angular article covers how to build an app ready for production, and provides further resources for you to continue your learning journey.
Which frameworks did we choose?
-------------------------------
We are publishing our initial set of articles with guides focusing on five frameworks. Four of them are very popular and well-established β React/ReactDOM, Ember, Vue, and Angular β whereas Svelte is a comparative newcomer that shows a lot of promise and has gained a lot of recent popularity.
There is a variety of reasons for this:
* They are popular choices that will be around for a while β like with any software tool, it is good to stick with actively-developed choices that are likely to not be discontinued next week, and which will be desirable additions to your skill set when looking for a job.
* They have strong communities and good documentation. It is very important to be able to get help with learning a complex subject, especially when you are just starting out.
* We don't have the resources to cover *all* modern frameworks. That list would be very difficult to keep up-to-date anyway, as new ones appear all the time.
* As a beginner, trying to choose what to focus on out of the huge number of choices available is a very real problem. Keeping the list short is therefore helpful.
We want to say this upfront β we've **not** chosen the frameworks we are focusing on because we think they are the best, or because we endorse them in any way. We just think they score highly on the above criteria.
Note that we were hoping to have more frameworks included upon initial publication, but we decided to release the content and then add more framework guides later, rather than delay it longer. If your favorite framework is not represented in this content and you'd like to help change that, feel free to discuss it with us! |
Adding a new todo form: Vue events, methods, and models - Learn web development | Adding a new todo form: Vue events, methods, and models
=======================================================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
We now have sample data in place, and a loop that takes each bit of data and renders it inside a `ToDoItem` in our app. What we really need next is the ability to allow our users to enter their own todo items into the app, and for that we'll need a text `<input>`, an event to fire when the data is submitted, a method to fire upon submission to add the data and rerender the list, and a model to control the data. This is what we'll cover in this article.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with node + npm installed.
|
| Objective: |
To learn about handling forms in Vue, and by association, events,
models, and methods.
|
Creating a New To-Do form
-------------------------
We now have an app that displays a list of to-do items. However, we can't update our list of items without manually changing our code! Let's fix that. Let's create a new component that will allow us to add a new to-do item.
1. In your components folder, create a new file called `ToDoForm.vue`.
2. Add a blank `<template>` and a `<script>` tag like before:
```html
<template></template>
<script>
export default {};
</script>
```
3. Let's add in an HTML form that lets you enter a new todo item and submit it into the app. We need a `<form>` with a `<label>`, an `<input>`, and a `<button>`. Update your template as follows:
```html
<template>
<form>
<label for="new-todo-input"> What needs to be done? </label>
<input
type="text"
id="new-todo-input"
name="new-todo"
autocomplete="off" />
<button type="submit">Add</button>
</form>
</template>
```
So we now have a form component into which we can enter the title of a new todo item (which will become a label for the corresponding `ToDoItem` when it is eventually rendered).
4. Let's load this component into our app. Go back to `App.vue` and add the following `import` statement just below the previous one, inside your `<script>` element:
```js
import ToDoForm from "./components/ToDoForm";
```
5. You also need to register the new component in your `App` component β update the `components` property of the component object so that it looks like this:
```js
components: {
ToDoItem, ToDoForm,
}
```
6. Finally for this section, render your `ToDoForm` component inside your app by adding the `<to-do-form />` element inside your `App`'s `<template>`, like so:
```html
<template>
<div id="app">
<h1>My To-Do List</h1>
<to-do-form></to-do-form>
<ul>
<li v-for="item in ToDoItems" :key="item.id">
<to-do-item
:label="item.label"
:done="item.done"
:id="item.id"></to-do-item>
</li>
</ul>
</div>
</template>
```
Now when you view your running site, you should see the new form displayed.
![Our todo list app rendered with a text input to enter new todos](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_methods_events_models/rendered-form-with-text-input.png)
If you fill it out and click the "Add" button, the page will post the form back to the server, but this isn't really what we want. What we actually want to do is run a method on the `submit` event that will add the new todo to the `ToDoItem` data list defined inside `App`. To do that, we'll need to add a method to the component instance.
Creating a method & binding it to an event with v-on
----------------------------------------------------
To make a method available to the `ToDoForm` component, we need to add it to the component object, and this is done inside a `methods` property to our component, which goes in the same place as `data()`, `props`, etc. The `methods` property holds any methods we might need to call in our component. When referenced, methods are fully run, so it's not a good idea to use them to display information inside the template. For displaying data that comes from calculations, you should use a `computed` property, which we'll cover later.
1. In this component, we need to add an `onSubmit()` method to a `methods` property inside the `ToDoForm` component object. We'll use this to handle the submit action.
Add this like so:
```js
export default {
methods: {
onSubmit() {
console.log("form submitted");
},
},
};
```
2. Next we need to bind the method to our `<form>` element's `submit` event handler. Much like how Vue uses the `v-bind` syntax for binding attributes, Vue has a special directive for event handling: `v-on`. The `v-on` directive works via the `v-on:event="method"` syntax. And much like `v-bind`, there's also a shorthand syntax: `@event="method"`.
We'll use the shorthand syntax here for consistency. Add the `submit` handler to your `<form>` element like so:
```html
<form @submit="onSubmit">β¦</form>
```
3. When you run this, the app still posts the data to the server, causing a refresh. Since we're doing all of our processing on the client, there's no server to handle the postback. We also lose all local state on page refresh. To prevent the browser from posting to the server, we need to stop the event's default action while bubbling up through the page (`Event.preventDefault()`, in vanilla JavaScript). Vue has a special syntax called **event modifiers** that can handle this for us right in our template.
Modifiers are appended to the end of an event with a dot like so: `@event.modifier`. Here is a list of event modifiers:
* `.stop`: Stops the event from propagating. Equivalent to `Event.stopPropagation()` in regular JavaScript events.
* `.prevent`: Prevents the event's default behavior. Equivalent to `Event.preventDefault()`.
* `.self`: Triggers the handler only if the event was dispatched from this exact element.
* `{.key}`: Triggers the event handler only via the specified key. MDN has a list of valid key values; multi-word keys just need to be converted to kebab-case (e.g. `page-down`).
* `.native`: Listens for a native event on the root (outer-most wrapping) element on your component.
* `.once`: Listens for the event until it's been triggered once, and then no more.
* `.left`: Only triggers the handler via the left mouse button event.
* `.right`: Only triggers the handler via the right mouse button event.
* `.middle`: Only triggers the handler via the middle mouse button event.
* `.passive`: Equivalent to using the `{ passive: true }` parameter when creating an event listener in vanilla JavaScript using `addEventListener()`.In this case, we need to use the `.prevent` modifier to stop the browser's default submit action. Add `.prevent` to the `@submit` handler in your template like so:
```html
<form @submit.prevent="onSubmit">β¦</form>
```
If you try submitting the form now, you'll notice that the page doesn't reload. If you open the console, you can see the results of the `console.log()` we added inside our `onSubmit()` method.
Binding data to inputs with v-model
-----------------------------------
Next up, we need a way to get the value from the form's `<input>` so we can add the new to-do item to our `ToDoItems` data list.
The first thing we need is a `data` property in our form to track the value of the to-do.
1. Add a `data()` method to our `ToDoForm` component object that returns a `label` field. We can set the initial value of the `label` to an empty string.
Your component object should now look something like this:
```js
export default {
methods: {
onSubmit() {
console.log("form submitted");
},
},
data() {
return {
label: "",
};
},
};
```
2. We now need some way to attach the value of the `new-todo-input` element's field to the `label` field. Vue has a special directive for this: `v-model`. `v-model` binds to the data property you set on it and keeps it in sync with the `<input>`. `v-model` works across all the various input types, including checkboxes, radios, and select inputs. To use `v-model`, you add an attribute with the structure `v-model="variable"` to the `<input>`.
So in our case, we would add it to our `new-todo-input` field as seen below. Do this now:
```html
<input
type="text"
id="new-todo-input"
name="new-todo"
autocomplete="off"
v-model="label" />
```
**Note:** You can also sync data with `<input>` values through a combination of events and `v-bind` attributes. In fact, this is what `v-model` does behind the scenes. However, the exact event and attribute combination varies depending on input types and will take more code than just using the `v-model` shortcut.
3. Let's test out our use of `v-model` by logging the value of the data submitted in our `onSubmit()` method. In components, data attributes are accessed using the `this` keyword. So we access our `label` field using `this.label`.
Update your `onSubmit()` method to look like this:
```js
methods: {
onSubmit() {
console.log('Label value: ', this.label);
}
},
```
4. Now go back to your running app, add some text to the `<input>` field, and click the "Add" button. You should see the value you entered logged to your console, for example:
```
Label value: My value
```
Changing v-model behavior with modifiers
----------------------------------------
In a similar fashion to event modifiers, we can also add modifiers to change the behavior of `v-model`. In our case, there are two worth considering. The first, `.trim`, will remove whitespace from before or after the input. We can add the modifier to our `v-model` statement like so: `v-model.trim="label"`.
The second modifier we should consider is called `.lazy`. This modifier changes when `v-model` syncs the value for text inputs. As mentioned earlier, `v-model` syncing works by updating the variable using events. For text inputs, this sync happens using the `input` event. Often, this means that Vue is syncing the data after every keystroke. The `.lazy` modifier causes `v-model` to use the `change` event instead. This means that Vue will only sync data when the input loses focus or the form is submitted. For our purposes, this is much more reasonable since we only need the final data.
To use both the `.lazy` modifier and the `.trim` modifier together, we can chain them, e.g. `v-model.lazy.trim="label"`.
Update your `v-model` attribute to chain `lazy` and `trim` as shown above, and then test your app again. Try for example, submitting a value with whitespace at each end.
Passing data to parents with custom events
------------------------------------------
We now are very close to being able to add new to-do items to our list. The next thing we need to be able to do is pass the newly-created to-do item to our `App` component. To do that, we can have our `ToDoForm` emit a custom event that passes the data, and have `App` listen for it. This works very similarly to native events on HTML elements: a child component can emit an event which can be listened to via `v-on`.
In the `onSubmit` event handler of our `ToDoForm`, let's add a `todo-added` event. Custom events are emitted like this: `this.$emit("event-name")`. It's important to know that event handlers are case sensitive and cannot include spaces. Vue templates also get converted to lowercase, which means Vue templates cannot listen for events named with capital letters.
1. Replace the `console.log()` in the `onSubmit()` method with the following:
```js
this.$emit("todo-added");
```
2. Next, go back to `App.vue` and add a `methods` property to your component object containing an `addToDo()` method, as shown below. For now, this method can just log `To-do added` to the console.
```js
export default {
name: "app",
components: {
ToDoItem,
ToDoForm,
},
data() {
return {
ToDoItems: [
{ id: uniqueId("todo-"), label: "Learn Vue", done: false },
{
id: uniqueId("todo-"),
label: "Create a Vue project with the CLI",
done: true,
},
{ id: uniqueId("todo-"), label: "Have fun", done: true },
{ id: uniqueId("todo-"), label: "Create a to-do list", done: false },
],
};
},
methods: {
addToDo() {
console.log("To-do added");
},
},
};
```
3. Next, add an event listener for the `todo-added` event to the `<to-do-form></to-do-form>`, which calls the `addToDo()` method when the event fires. Using the `@` shorthand, the listener would look like this: `@todo-added="addToDo"`:
```html
<to-do-form @todo-added="addToDo"></to-do-form>
```
4. When you submit your `ToDoForm`, you should see the console log from the `addToDo()` method. This is good, but we're still not passing any data back into the `App.vue` component. We can do that by passing additional arguments to the `this.$emit()` function back in the `ToDoForm` component.
In this case, when we fire the event we want to pass the `label` data along with it. This is done by including the data you want to pass as another parameter in the `$emit()` method: `this.$emit("todo-added", this.label)`. This is similar to how native JavaScript events include data, except custom Vue events include no event object by default. This means that the emitted event will directly match whatever object you submit. So in our case, our event object will just be a string.
Update your `onSubmit()` method like so:
```js
onSubmit() {
this.$emit('todo-added', this.label)
}
```
5. To actually pick up this data inside `App.vue`, we need to add a parameter to our `addToDo()` method that includes the `label` of the new to-do item.
Go back to `App.vue` and update this now:
```js
methods: {
addToDo(toDoLabel) {
console.log('To-do added:', toDoLabel);
}
}
```
If you test your form again, you'll see whatever text you enter logged in your console upon submission. Vue automatically passes the arguments after the event name in `this.$emit()` to your event handler.
Adding the new todo into our data
---------------------------------
Now that we have the data from `ToDoForm` available in `App.vue`, we need to add an item representing it to the `ToDoItems` array. This can be done by pushing a new to-do item object to the array containing our new data.
1. Update your `addToDo()` method like so:
```js
addToDo(toDoLabel) {
this.ToDoItems.push({id:uniqueId('todo-'), label: toDoLabel, done: false});
}
```
2. Try testing your form again, and you should see new to-do items get appended to the end of the list.
3. Let's make a further improvement before we move on. If you submit the form while the input is empty, todo items with no text still get added to the list. To fix that, we can prevent the todo-added event from firing when name is empty. Since name is already being trimmed by the `.trim` modifier, we only need to test for the empty string.
Go back to your `ToDoForm` component, and update the `onSubmit()` method like so. If the label value is empty, let's not emit the `todo-added` event.
```js
onSubmit() {
if (this.label === "") {
return;
}
this.$emit('todo-added', this.label);
}
```
4. Try your form again. Now you will not be able to add empty items to the to-do list.
![Our todo list app rendered with a text input to enter new todos](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_methods_events_models/rendered-form-with-new-items.png)
Using v-model to update an input value
--------------------------------------
There's one more thing to fix in our `ToDoForm` component β after submitting, the `<input>` still contains the old value. But this is easy to fix β because we're using `v-model` to bind the data to the `<input>` in `ToDoForm`, if we set the name parameter to equal an empty string, the input will update as well.
Update your `ToDoForm` component's `onSubmit()` method to this:
```js
onSubmit() {
if (this.label === "") {
return;
}
this.$emit('todo-added', this.label);
this.label = "";
}
```
Now when you click the "Add" button, the "new-todo-input" will clear itself.
Summary
-------
Excellent. We can now add todo items to our form! Our app is now starting to feel interactive, but one issue is that we've completely ignored its look and feel up to now. In the next article, we'll concentrate on fixing this, looking at the different ways Vue provides to style components.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Getting started with React - Learn web development | Getting started with React
==========================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
In this article we will say hello to React. We'll discover a little bit of detail about its background and use cases, set up a basic React toolchain on our local computer, and create and play with a simple starter app β learning a bit about how React works in the process.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
React uses an HTML-in-JavaScript syntax called JSX (JavaScript and
XML). Familiarity with both HTML and JavaScript will help you to learn
JSX, and better identify whether bugs in your application are related
to JavaScript or to the more specific domain of React.
|
| Objective: |
To set up a local React development environment, create a start app, and
understand the basics of how it works.
|
Hello React
-----------
As its official tagline states, React is a library for building user interfaces. React is not a framework β it's not even exclusive to the web. It's used with other libraries to render to certain environments. For instance, React Native can be used to build mobile applications.
To build for the web, developers use React in tandem with ReactDOM. React and ReactDOM are often discussed in the same spaces as β and utilized to solve the same problems as β other true web development frameworks. When we refer to React as a "framework", we're working with that colloquial understanding.
React's primary goal is to minimize the bugs that occur when developers are building UIs. It does this through the use of components β self-contained, logical pieces of code that describe a portion of the user interface. These components can be composed together to create a full UI, and React abstracts away much of the rendering work, leaving you to concentrate on the UI design.
Use cases
---------
Unlike the other frameworks covered in this module, React does not enforce strict rules around code conventions or file organization. This allows teams to set conventions that work best for them, and to adopt React in any way they would like to. React can handle a single button, a few pieces of an interface, or an app's entire user interface.
While React *can* be used for small pieces of an interface, it's not as easy to "drop into" an application as a library like jQuery, or even a framework like Vue β it is more approachable when you build your entire app with React.
In addition, many of the developer-experience benefits of a React app, such as writing interfaces with JSX, require a compilation process. Adding a compiler like Babel to a website makes the code on it run slowly, so developers often set up such tooling with a build step. React arguably has a heavy tooling requirement, but it can be learned.
This article is going to focus on the use case of using React to render the entire user interface of an application with the support of Vite, a modern front-end build tool.
How does React use JavaScript?
------------------------------
React utilizes features of modern JavaScript for many of its patterns. Its biggest departure from JavaScript comes with the use of JSX syntax. JSX extends JavaScript's syntax so that HTML-like code can live alongside it. For example:
```jsx
const heading = <h1>Mozilla Developer Network</h1>;
```
This heading constant is known as a **JSX expression**. React can use it to render that `<h1>` tag in our app.
Suppose we wanted to wrap our heading in a `<header>` tag, for semantic reasons? The JSX approach allows us to nest our elements within each other, just like we do with HTML:
```jsx
const header = (
<header>
<h1>Mozilla Developer Network</h1>
</header>
);
```
**Note:** The parentheses in the previous snippet aren't unique to JSX, and don't have any effect on your application. They're a signal to you (and your computer) that the multiple lines of code inside are part of the same expression. You could just as well write the header expression like this:
```jsx
const header = <header>
<h1>Mozilla Developer Network</h1>
</header>;
```
However, this looks kind of awkward, because the `<header>` tag that starts the expression is not indented to the same position as its corresponding closing tag.
Of course, your browser can't read JSX without help. When compiled (using a tool like Babel or Parcel), our header expression would look like this:
```jsx
const header = React.createElement(
"header",
null,
React.createElement("h1", null, "Mozilla Developer Network"),
);
```
It's *possible* to skip the compilation step and use `React.createElement()` to write your UI yourself. In doing this, however, you lose the declarative benefit of JSX, and your code becomes harder to read. Compilation is an extra step in the development process, but many developers in the React community think that the readability of JSX is worthwhile. Plus, modern front-end development almost always involves a build process anyway β you have to downlevel modern syntax to be compatible with older browsers, and you may want to minify your code to optimize loading performance. Popular tooling like Babel already comes with JSX support out-of-the-box, so you don't have to configure compilation yourself unless you want to.
Because JSX is a blend of HTML and JavaScript, some developers find it intuitive. Others say that its blended nature makes it confusing. Once you're comfortable with it, however, it will allow you to build user interfaces more quickly and intuitively, and allow others to better understand your codebase at a glance.
To read more about JSX, check out the React team's Writing Markup with JSX article.
Setting up your first React app
-------------------------------
There are many ways to create a new React application. We're going to use Vite to create a new application via the command line.
It's possible to add React to an existing project by copying some `<script>` elements into an HTML file, but using Vite will allow you to spend more time building your app and less time fussing with setup.
### Requirements
In order to use Vite, you need to have Node.js installed. As of Vite 5.0, at least Node version 18 or later is required, and it's a good idea to run the latest long term support (LTS) version when you can. As of 24th October 2023, Node 20 is the latest LTS version. Node includes npm (the Node package manager).
To check your version of Node, run the following in your terminal:
```bash
node -v
```
If Node is installed, you'll see a version number. If it isn't, you'll see an error message. To install Node, follow the instructions on the Node.js website.
You may use the Yarn package manager as an alternative to npm but we'll assume you're using npm in this set of tutorials. See Package management basics for more information on npm and yarn.
If you're using Windows, you will need to install some software to give you parity with Unix/macOS terminal in order to use the terminal commands mentioned in this tutorial. **Gitbash** (which comes as part of the git for Windows toolset) or **Windows Subsystem for Linux** (**WSL**) are both suitable. See Command line crash course for more information on these, and on terminal commands in general.
Also bear in mind that React and ReactDOM produce apps that only work on a fairly modern set of browsers like Firefox, Microsoft Edge, Safari, or Chrome when working through these tutorials.
See the following for more information:
* "About npm" on the npm blog
* "Introducing npx" on the npm blog
* Vite's documentation
### Initializing your app
The npm package manager comes with a `create` command that allows you to create new projects from templates. We can use it to create a new app from Vite's standard React template. Make sure you `cd` to the place you'd like your app to live on your machine, then run the following in your terminal:
```bash
npm create vite@latest moz-todo-react -- --template react
```
This creates a `moz-todo-react` directory using Vite's `react` template.
**Note:** The `--` is necessary to pass arguments to npm commands such as `create`, and the `--template react` argument tells Vite to use its React template.
Your terminal will have printed some messages if this command was successful. You should see text prompting you to `cd` to your new directory, install the app's dependencies, and run the app locally. Let's start with two of those commands. Run the following in your terminal:
```bash
cd moz-todo-react && npm install
```
Once the process is complete, we need to start a local development server to run our app. Here, we're going to add some command line flags to Vite's default suggestion to open the app in our browser as soon as the server starts, and use port 3000.
Run the following in your terminal:
```bash
npm run dev -- --open --port 3000
```
Once the server starts, you should see a new browser tab containing your React app:
![Screenshot of Firefox MacOS open to localhost:3000, showing an application made from Vite's React template](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started/default-vite.png)
### Application structure
Vite gives us everything we need to develop a React application. Its initial file structure looks like this:
```
moz-todo-react
βββ README.md
βββ index.html
βββ node_modules
βββ package-lock.json
βββ package.json
βββ public
β βββ vite.svg
βββ src
β βββ App.css
β βββ App.jsx
β βββ assets
β β βββ react.svg
β βββ index.css
β βββ main.jsx
βββ vite.config.js
```
**`index.html`** is the most important top-level file. Vite injects your code into this file so that your browser can run it. You won't need to edit this file during our tutorial, but you should change the text inside the `<title>` element in this file to reflect the title of your application. Accurate page titles are important for accessibility.
The **`public`** directory contains static files that will be served directly to your browser without being processed by Vite's build tooling. Right now, it only contains a Vite logo.
The **`src`** directory is where we'll spend most of our time, as it's where the source code for our application lives. You'll notice that some JavaScript files in this directory end in the extension `.jsx`. This extension is necessary for any file that contains JSX β it tells Vite to turn the JSX syntax into JavaScript that your browser can understand. The `src/assets` directory contains the React logo you saw in the browser.
The `package.json` and `package-lock.json` files contain metadata about our project. These files are not unique to React applications: Vite populated `package.json` for us, and npm created `package-lock.json` for when we installed the app's dependencies. You don't need to understand these files at all to complete this tutorial. However, if you'd like to learn more about them, you can read about `package.json` and `package-lock.json` in the npm docs. We also talk about `package.json` in our Package management basics tutorial.
### Customizing our dev script
Before we move on, you might want to change your `package.json` file a little bit so that you don't have to pass the `--open` and `--port` flags every time you run `npm run dev`. Open `package.json` in your text editor and find the `scripts` object. Change the `"dev"` key so that it looks like this:
```diff
- "dev": "vite",
+ "dev": "vite --open --port 3000",
```
With this in place, your app will open in your browser at `http://localhost:3000` every time you run `npm run dev`.
**Note:** You *don't* need the extra `--` here because we're passing arguments directly to `vite`, rather than to a pre-defined npm script.
Exploring our first React component β `<App />`
-----------------------------------------------
In React, a **component** is a reusable module that renders a part of our overall application. Components can be big or small, but they are usually clearly defined: they serve a single, obvious purpose.
Let's open `src/App.jsx`, since our browser is prompting us to edit it. This file contains our first component, `<App />`:
```jsx
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import viteLogo from "/vite.svg";
import "./App.css";
function App() {
const [count, setCount] = useState(0);
return (
<>
<div>
<a href="https://vitejs.dev" target="\_blank">
<img src={viteLogo} className="logo" alt="Vite logo" />
</a>
<a href="https://react.dev" target="\_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
<p>
Edit <code>src/App.jsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
</>
);
}
export default App;
```
The `App.jsx` file consists of three main parts: some `import` statements at the top, the `App()` function in the middle, and an `export` statement at the bottom. Most React components follow this pattern.
### Import statements
The `import` statements at the top of the file allow `App.jsx` to use code that has been defined elsewhere. Let's look at these statements more closely.
```jsx
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import viteLogo from "/vite.svg";
import "./App.css";
```
The first statement imports the `useState` hook from the `react` library. Hooks are a way of using React's features inside a component. We'll talk more about hooks later in this tutorial.
After that, we import `reactLogo` and `viteLogo`. Note that their import paths start with `./` and `/` respectively and that they end with the `.svg` extension at the end. This tells us that these imports are *local*, referencing our own files rather than npm packages.
The final statement imports the CSS related to our `<App />` component. Note that there is no variable name and no `from` directive. This is called a *side-effect import* β it doesn't import any value into the JavaScript file, but it tells Vite to add the referenced CSS file to the final code output, so that it can be used in the browser.
### The `App()` function
After the imports, we have a function named `App()`, which defines the structure of the `App` component. Whereas most of the JavaScript community prefers lower camel case names like `helloWorld`, React components use Pascal case (or upper camel case) variable names, like `HelloWorld`, to make it clear that a given JSX element is a React component and not a regular HTML tag. If you were to rename the `App()` function to `app()`, your browser would throw an error.
Let's look at `App()` more closely.
```jsx
function App() {
const [count, setCount] = useState(0);
return (
<>
<div>
<a href="https://vitejs.dev" target="\_blank">
<img src={viteLogo} className="logo" alt="Vite logo" />
</a>
<a href="https://react.dev" target="\_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
<p>
Edit <code>src/App.jsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
</>
);
}
```
The `App()` function returns a JSX expression. This expression defines what your browser ultimately renders to the DOM.
Just under the `return` keyword is a special bit of syntax: `<>`. This is a fragment. React components have to return a single JSX element, and fragments allow us to do that without rendering arbitrary `<div>`s in the browser. You'll see fragments in many React applications.
### The `export` statement
There's one more line of code after the `App()` function:
```jsx
export default App;
```
This export statement makes our `App()` function available to other modules. We'll talk more about this later.
Moving on to `main`
-------------------
Let's open `src/main.jsx`, because that's where the `<App />` component is being used. This file is the entry point for our app, and it initially looks like this:
```jsx
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.jsx";
import "./index.css";
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
```
As with `App.jsx`, the file starts by importing all the JS modules and other assets it needs to run.
The first two statements import the `React` and `ReactDOM` libraries because they are referenced later in the file. We don't write a path or extension when importing these libraries because they are not local files. In fact, they are listed as dependencies in our `package.json` file. Be careful of this distinction as you work through this lesson!
We then import our `App()` function and `index.css`, which holds global styles that are applied to our whole app.
We then call the `ReactDOM.createRoot()` function, which defines the root node of our application. This takes as an argument the DOM element inside which we want our React app to be rendered. In this case, that's the DOM element with an ID of `root`. Finally, we chain the `render()` method onto the `createRoot()` call, passing it the JSX expression that we want to render inside our root. By writing `<App />` as this JSX expression, we're telling React to call the `App()` *function* which renders the `App` *component* inside the root node.
**Note:** `<App />` is rendered inside a special `<React.StrictMode>` component. This component helps developers catch potential problems in their code.
You can read up on these React APIs, if you'd like:
* `ReactDOM.createRoot()`
* `React.StrictMode`
Starting fresh
--------------
Before we start building our app, we're going to delete some of the boilerplate code that Vite provided for us.
First, as an experiment, change the `<h1>` element in `App.jsx` so that it reads "Hello, World!", then save your file. You'll notice that this change is immediately rendered in the development server running at `http://localhost:3000` in your browser. Bear this in mind as you work on your app.
We won't be using the rest of the code! Replace the contents of `App.jsx` with the following:
```jsx
import "./App.css";
function App() {
return (
<>
<header>
<h1>Hello, World!</h1>
</header>
</>
);
}
export default App;
```
Practice with JSX
-----------------
Next, we'll use our JavaScript skills to get a bit more comfortable writing JSX and working with data in React. We'll talk about how to add attributes to JSX elements, how to write comments, how to render content from variables and other expressions, and how to pass data into components with props.
### Adding attributes to JSX elements
JSX elements can have attributes, just like HTML elements. Try adding a `<button>` below the `<h1>` element in your `App.jsx` file, like this:
```jsx
<button type="button">Click me!</button>
```
When you save your file, you'll see a button with the words `Click me!`. The button doesn't do anything yet, but we'll learn about adding interactivity to our app soon.
Some attributes are different than their HTML counterparts. For example, the `class` attribute in HTML translates to `className` in JSX. This is because `class` is a reserved word in JavaScript, and JSX is a JavaScript extension. If you wanted to add a `primary` class to your button, you'd write it like this:
```jsx
<button type="button" className="primary">
Click me!
</button>
```
### JavaScript expressions as content
Unlike HTML, JSX allows us to write variables and other JavaScript expressions right alongside our other content. Let's declare a variable called `subject` just above the `App()` function:
```jsx
const subject = "React";
function App() {
// code omitted for brevity
}
```
Next, replace the word "World" in the `<h1>` element with `{subject}`:
```jsx
<h1>Hello, {subject}!</h1>
```
Save your file and check your browser. You should see "Hello, React!" rendered.
The curly braces around `subject` are another feature of JSX's syntax. The curly braces tell React that we want to read the value of the `subject` variable, rather than render the literal string `"subject"`. You can put any valid JavaScript expression inside curly braces in JSX; React will evaluate it and render the *result* of the expression as the final content. Following is a series of examples, with comments above explaining what each expression will render:
```jsx
{/\* Hello, React :)! \*/}
<h1>Hello, {subject + ' :)'}!</h1>
{/\* Hello, REACT \*/}
<h1>Hello, {subject.toUpperCase()}</h1>
{/\* Hello, 4 \*/}
<h1>Hello, {2 + 2}!</h1>
```
Even comments in JSX are written inside curly braces! This is because comments, too, are technically JavaScript expressions. The `/* block comment syntax */` is necessary for your program to know where the comment starts and ends.
### Component props
**Props** are a means of passing data into a React component. Their syntax is identical to that of attributes, in fact: `prop="value"`. The difference is that whereas attributes are passed into plain elements, props are passed into React components.
In React, the flow of data is unidirectional: props can only be passed from parent components down to child components.
Let's open `main.jsx` and give our `<App />` component its first prop.
Add a prop of `subject` to the `<App />` component call, with a value of `Clarice`. When you are done, it should look something like this:
```jsx
<App subject="Clarice" />
```
Back in `App.jsx`, let's revisit the `App()` function. Change the signature of `App()` so that it accepts `props` as a parameter and log `props` to the console so you can inspect it. Also delete the `subject` const; we don't need it anymore. Your `App.jsx` file should look like this:
```jsx
function App(props) {
console.log(props);
return (
// code omitted for brevity
);
}
```
Save your file and check your browser. You'll see a blank background with no content. This is because we're trying to read a `subject` variable that's no longer defined. Fix this by commenting out the `<h1>Hello {subject}!</h1>` line.
**Note:** If your code editor understands how to parse JSX (most modern editors do!), you can use its built-in commenting shortcut β `Ctrl + /` (on Windows) or `Cmd + /` (on macOS) β to create comments more quickly.
Save the file with that line commented out. This time, you should see your
"Click me!" button rendered by itself. If you open your browser's developer console, you'll see a message that looks like this:
```
Object { subject: "Clarice" }
```
The object property `subject` corresponds to the `subject` prop we added to our `<App />` component call, and the string `Clarice` corresponds to its value. Component props in React are always collected into objects in this fashion.
Let's use this `subject` prop to fix the error in our app. Uncomment the `<h1>Hello, {subject}!</h1>` line and change it to `<h1>Hello, {props.subject}!</h1>`, then delete the `console.log()` statement. Your code should look like this:
```jsx
function App(props) {
return (
<>
<header>
<h1>Hello, {props.subject}!</h1>
<button type="button" className="primary">
Click me!
</button>
</header>
</>
);
}
```
When you save, the app should now greet you with "Hello, Clarice!". If you return to `main.jsx`, edit the value of `subject`, and save, your text will change.
For additional practice, you could try adding an additional `greeting` prop to the `<App />` component call inside `main.jsx` and using it alongside the `subject` prop inside `App.jsx`.
Summary
-------
This brings us to the end of our initial look at React, including how to install it locally, creating a starter app, and how the basics work. In the next article, we'll start building our first proper application β a todo list. Before we do that, however, let's recap some of the things we've learned.
In React:
* Components can import modules they need and must export themselves at the bottom of their files.
* Component functions are named with `PascalCase`.
* You can render JavaScript expressions in JSX by putting them between curly braces, like `{so}`.
* Some JSX attributes are different than HTML attributes so that they don't conflict with JavaScript reserved words. For example, `class` in HTML translates to `className` in JSX.
* Props are written just like attributes inside component calls and are passed into components.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Focus management with Vue refs - Learn web development | Focus management with Vue refs
==============================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
We are nearly done with Vue. The last bit of functionality to look at is focus management, or put another way, how we can improve our app's keyboard accessibility. We'll look at using **Vue refs** to handle this β an advanced feature that allows you to have direct access to the underlying DOM nodes below the virtual DOM, or direct access from one component to the internal DOM structure of a child component.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with node + npm installed.
|
| Objective: | To learn how to handle focus management using Vue refs. |
The focus management problem
----------------------------
While we do have working edit functionality, we aren't providing a great experience for non-mouse users. Specifically, when a user activates the "Edit" button, we remove the "Edit" button from the DOM, but we don't move the user's focus anywhere, so in effect it just disappears. This can be disorienting for keyboard and non-visual users.
To understand what's currently happening:
1. Reload your page, then press `Tab`. You should see a focus outline on the input for adding new to-do items.
2. Press `Tab` again. The focus should move to the "Add" button.
3. Hit it again, and it'll be on the first checkbox. One more time, and focus should be on the first "Edit" button.
4. Activate the "Edit" button by pressing `Enter`.
The checkbox will be replaced with our edit component, but the focus outline will be gone.
This behavior can be jarring. In addition, what happens when you press `Tab` again varies depending on the browser you're using. Similarly, if you save or cancel your edit, focus will disappear again as you move back to the non-edit view.
To give users a better experience, we'll add code to control the focus so that it gets set to the edit field when the edit form is shown. We'll also want to put focus back on the "Edit" button when a user cancels or saves their edit. In order to set focus, we need to understand a little bit more about how Vue works internally.
Virtual DOM and refs
--------------------
Vue, like some other frameworks, uses a virtual DOM (VDOM) to manage elements. This means that Vue keeps a representation of all of the nodes in our app in memory. Any updates are first performed on the in-memory nodes, and then all the changes that need to be made to the actual nodes on the page are synced in a batch.
Since reading and writing actual DOM nodes is often more expensive than virtual nodes, this can result in better performance. However, it also means you often should not edit your HTML elements directly through native browser APIs (like `Document.getElementById`) when using frameworks, because it results in the VDOM and real DOM going out of sync.
Instead, if you need to access the underlying DOM nodes (like when setting focus), you can use Vue refs. For custom Vue components, you can also use refs to directly access the internal structure of a child component, however this should be done with caution as it can make code harder to reason about and understand.
To use a ref in a component, you add a `ref` attribute to the element that you want to access, with a string identifier for the value of the attribute. It's important to note that a ref needs to be unique within a component. No two elements rendered at the same time should have the same ref.
### Adding a ref to our app
So, let's attach a ref to our "Edit" button in `ToDoItem.vue`. Update it like this:
```html
<button
type="button"
class="btn"
ref="editButton"
@click="toggleToItemEditForm">
Edit
<span class="visually-hidden">{{label}}</span>
</button>
```
To access the value associated with our ref, we use the `$refs` property provided on our component instance. To see the value of the ref when we click our "Edit" button, add a `console.log()` to our `toggleToItemEditForm()` method, like so:
```js
toggleToItemEditForm() {
console.log(this.$refs.editButton);
this.isEditing = true;
}
```
If you activate the "Edit" button at this point, you should see an HTML `<button>` element referenced in your console.
Vue's $nextTick() method
------------------------
We want to set focus on the "Edit" button when a user saves or cancels their edit. To do that, we need to handle focus in the `ToDoItem` component's `itemEdited()` and `editCancelled()` methods.
For convenience, create a new method which takes no arguments called `focusOnEditButton()`. Inside it, assign your `ref` to a variable, and then call the `focus()` method on the ref.
```js
focusOnEditButton() {
const editButtonRef = this.$refs.editButton;
editButtonRef.focus();
}
```
Next, add a call to `this.focusOnEditButton()` at the end of the `itemEdited()` and `editCancelled()` methods:
```js
itemEdited(newItemName) {
this.$emit("item-edited", newItemName);
this.isEditing = false;
this.focusOnEditButton();
},
editCancelled() {
this.isEditing = false;
this.focusOnEditButton();
},
```
Try editing and then saving/cancelling a to-do item via your keyboard. You'll notice that focus isn't being set, so we still have a problem to solve. If you open your console, you'll see an error raised along the lines of *"can't access property "focus", editButtonRef is undefined"*. This seems weird. Your button ref was defined when you activated the "Edit" button, but now it's not. What is going on?
Well, remember that when we change `isEditing` to `true`, we no longer render the section of the component featuring the "Edit" button. This means there's no element to bind the ref to, so it becomes `undefined`.
You might now be thinking "hey, don't we set `isEditing=false` before we try to access the `ref`, so therefore shouldn't the `v-if` now be displaying the button?" This is where the virtual DOM comes into play. Because Vue is trying to optimize and batch changes, it won't immediately update the DOM when we set `isEditing` to `false`. So when we call `focusOnEditButton()`, the "Edit" button has not been rendered yet.
Instead, we need to wait until after Vue undergoes the next DOM update cycle. To do that, Vue components have a special method called `$nextTick()`. This method accepts a callback function, which then executes after the DOM updates.
Since the `focusOnEditButton()` method needs to be invoked after the DOM has updated, we can wrap the existing function body inside a `$nextTick()` call.
```js
focusOnEditButton() {
this.$nextTick(() => {
const editButtonRef = this.$refs.editButton;
editButtonRef.focus();
});
}
```
Now when you activate the "Edit" button and then cancel or save your changes via the keyboard, focus should be returned to the "Edit" button. Success!
Vue lifecycle methods
---------------------
Next, we need to move focus to the edit form's `<input>` element when the "Edit" button is clicked. However, because our edit form is in a different component to our "Edit" button, we can't just set focus inside the "Edit" button's click event handler. Instead, we can use the fact that we remove and re-mount our `ToDoItemEditForm` component whenever the "Edit" button is clicked to handle this.
So how does this work? Well, Vue components undergo a series of events, known as a **lifecycle**. This lifecycle spans from all the way before elements are *created* and added to the VDOM (*mounted*), until they are removed from the VDOM (*destroyed*).
Vue lets you run methods at various stages of this lifecycle using **lifecycle methods**. This can be useful for things like data fetching, where you may need to get your data before your component renders, or after a property changes. The list of lifecycle methods are below, in the order that they fire.
1. `beforeCreate()` β Runs before the instance of your component is created. Data and events are not yet available.
2. `created()` β Runs after your component is initialized but before the component is added to the VDOM. This is often where data fetching occurs.
3. `beforeMount()` β Runs after your template is compiled, but before your component is rendered to the actual DOM.
4. `mounted()` β Runs after your component is mounted to the DOM. Can access `refs` here.
5. `beforeUpdate()` β Runs whenever data in your component changes, but before the changes are rendered to the DOM.
6. `updated()` β Runs whenever data in your component has changed and after the changes are rendered to the DOM.
7. `beforeDestroy()` β Runs before a component is removed from the DOM.
8. `destroyed()` β Runs after a component has been removed from the DOM.
9. `activated()` β Only used in components wrapped in a special `keep-alive` tag. Runs after the component is activated.
10. `deactivated()` β Only used in components wrapped in a special `keep-alive` tag. Runs after the component is deactivated.
**Note:** The Vue Docs provide a nice diagram for visualizing when these hooks happen. This article from the Digital Ocean Community Blog dives into the lifecycle methods more deeply.
Now that we've gone over the lifecycle methods, let's use one to trigger focus when our `ToDoItemEditForm` component is mounted.
In `ToDoItemEditForm.vue`, attach `ref="labelInput"` to the `<input>` element, like so:
```html
<input
:id="id"
ref="labelInput"
type="text"
autocomplete="off"
v-model.lazy.trim="newName" />
```
Next, add a `mounted()` property just inside your component object β **note that this should not be put inside the `methods` property, but rather at the same hierarchy level as `props`, `data()`, and `methods`.** Lifecycle methods are special methods that sit on their own, not alongside the user-defined methods. This should take no inputs. Note that you cannot use an arrow function here since we need access to `this` to access our `labelInput` ref.
```js
mounted() {
}
```
Inside your `mounted()` method, assign your `labelInput` ref to a variable, and then call the `focus()` function of the ref. You don't have to use `$nextTick()` here because the component has already been added to the DOM when `mounted()` is called.
```js
mounted() {
const labelInputRef = this.$refs.labelInput;
labelInputRef.focus();
}
```
Now when you activate the "Edit" button with your keyboard, focus should immediately be moved to the edit `<input>`.
Handling focus when deleting to-do items
----------------------------------------
There's one more place we need to consider focus management: when a user deletes a to-do. When clicking the "Edit" button, it makes sense to move focus to the edit name text box, and back to the "Edit" button when canceling or saving from the edit screen.
However, unlike with the edit form, we don't have a clear location for focus to move to when an element is deleted. We also need a way to provide assistive technology users with information that confirms that an element was deleted.
We're already tracking the number of elements in our list heading β the `<h2>` in `App.vue` β and it's associated with our list of to-do items. This makes it a reasonable place to move focus to when we delete a node.
First, we need to add a ref to our list heading. We also need to add a `tabindex="-1"` to it β this makes the element programmatically focusable (i.e. it can be focused via JavaScript), when by default it is not.
Inside `App.vue`, update your `<h2>` as follows:
```html
<h2 id="list-summary" ref="listSummary" tabindex="-1">{{listSummary}}</h2>
```
**Note:** `tabindex` is a really powerful tool for handling certain accessibility problems. However, it should be used with caution. Over-using `tabindex="-1"` can cause problems for all sorts of users, so only use it exactly where you need to. You should also almost never use `tabindex` > = `0`, as it can cause problems for users since it can make the DOM flow and the tab-order mismatch, and/or add non-interactive elements to the tab order. This can be confusing to users, especially those using screen readers and other assistive technology.
Now that we have a `ref` and have let browsers know that we can programmatically focus the `<h2>`, we need to set focus on it. At the end of `deleteToDo()`, use the `listSummary` ref to set focus on the `<h2>`. Since the `<h2>` is always rendered in the app, you do not need to worry about using `$nextTick()` or lifecycle methods to handle focusing it.
```js
deleteToDo(toDoId) {
const itemIndex = this.ToDoItems.findIndex((item) => item.id === toDoId);
this.ToDoItems.splice(itemIndex, 1);
this.$refs.listSummary.focus();
}
```
Now, when you delete an item from your list, focus should be moved up to the list heading. This should provide a reasonable focus experience for all of our users.
Summary
-------
So that's it for focus management, and for our app! Congratulations for working your way through all our Vue tutorials. In the next article we'll round things off with some further resources to take your Vue learning further.
**Note:** If you need to check your code against our version, you can find a finished version of the sample Vue app code in our todo-vue repository. For a running live version, see https://mdn.github.io/todo-vue/.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Styling our Angular app - Learn web development | Styling our Angular app
=======================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
Now that we've got our basic application structure set up and started displaying something useful, let's switch gears and spend an article looking at how Angular handles styling of applications.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
|
| Objective: | To learn how to style an Angular app. |
Adding some style to Angular
----------------------------
The Angular CLI generates two types of style files:
* Component styles: The Angular CLI gives each component its own file for styles.
The styles in this file apply only to its component.
* `styles.css`: In the `src` directory, the styles in this file apply to your entire application unless you specify styles at the component level.
Depending on whether you are using a CSS preprocessor, the extension on your CSS files can vary.
Angular supports plain CSS, SCSS, Sass, Less, and Stylus.
In `src/styles.css`, paste the following styles:
```css
body {
font-family: Helvetica, Arial, sans-serif;
}
.btn-wrapper {
/\* flexbox \*/
display: flex;
flex-wrap: nowrap;
justify-content: space-between;
}
.btn {
color: #000;
background-color: #fff;
border: 2px solid #cecece;
padding: 0.35rem 1rem 0.25rem 1rem;
font-size: 1rem;
}
.btn:hover {
background-color: #ecf2fd;
}
.btn:active {
background-color: #d1e0fe;
}
.btn:focus {
outline: none;
border: black solid 2px;
}
.btn-primary {
color: #fff;
background-color: #000;
width: 100%;
padding: 0.75rem;
font-size: 1.3rem;
border: black solid 2px;
margin: 1rem 0;
}
.btn-primary:hover {
background-color: #444242;
}
.btn-primary:focus {
color: #000;
outline: none;
border: #000 solid 2px;
background-color: #d7ecff;
}
.btn-primary:active {
background-color: #212020;
}
```
The CSS in `src/styles.css` apply to the entire application, however, these styles don't affect everything on the page.
The next step is to add styles that apply specifically to the `AppComponent`.
In `app.component.css`, add the following styles:
```css
.main {
max-width: 500px;
width: 85%;
margin: 2rem auto;
padding: 1rem;
text-align: center;
box-shadow:
0 2px 4px 0 rgb(0 0 0 / 20%),
0 2.5rem 5rem 0 rgb(0 0 0 / 10%);
}
@media screen and (min-width: 600px) {
.main {
width: 70%;
}
}
label {
font-size: 1.5rem;
font-weight: bold;
display: block;
padding-bottom: 1rem;
}
.lg-text-input {
width: 100%;
padding: 1rem;
border: 2px solid #000;
display: block;
box-sizing: border-box;
font-size: 1rem;
}
.btn-wrapper {
margin-bottom: 2rem;
}
.btn-menu {
flex-basis: 32%;
}
.active {
color: green;
}
ul {
padding-inline-start: 0;
}
ul li {
list-style: none;
}
```
The last step is to revisit your browser and look at how the styling has updated. Things now make a bit more sense.
Summary
-------
Now that our brief tour of styling in Angular is done with, let's return to creating our app functionality. In the next article we will create a proper component for to-do items, and make it so that you can check, edit, and delete to-do items.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Creating an item component - Learn web development | Creating an item component
==========================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
Components provide a way for you to organize your application. This article walks you through creating a component to handle the individual items in the list, and adding check, edit, and delete functionality. The Angular event model is covered here.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
|
| Objective: |
To learn more about components, including how events work to handle
updates. To add check, edit, and delete functionality.
|
Creating the new component
--------------------------
At the command line, create a component named `item` with the following CLI command:
```bash
ng generate component item
```
The `ng generate component` command creates a component and folder with the name you specify.
Here, the folder and component name is `item`.
You can find the `item` directory within the `app` folder.
Just as with the `AppComponent`, the `ItemComponent` is made up of the following files:
* `item.component.html` for HTML
* `item.component.ts` for logic
* `item.component.css` for styles
You can see a reference to the HTML and CSS files in the `@Component()` decorator metadata in `item.component.ts`.
```js
@Component({
selector: 'app-item',
templateUrl: './item.component.html',
styleUrls: ['./item.component.css'],
})
```
Add HTML for the ItemComponent
------------------------------
The `ItemComponent` can take over the task of giving the user a way to check items off as done, edit them, or delete them.
Add markup for managing items by replacing the placeholder content in `item.component.html` with the following:
```html
<div class="item">
<input
[id]="item.description"
type="checkbox"
(change)="item.done = !item.done"
[checked]="item.done" />
<label [for]="item.description">{{item.description}}</label>
<div class="btn-wrapper" \*ngIf="!editable">
<button class="btn" (click)="editable = !editable">Edit</button>
<button class="btn btn-warn" (click)="remove.emit()">Delete</button>
</div>
<!-- This section shows only if user clicks Edit button -->
<div \*ngIf="editable">
<input
class="sm-text-input"
placeholder="edit item"
[value]="item.description"
#editedItem
(keyup.enter)="saveItem(editedItem.value)" />
<div class="btn-wrapper">
<button class="btn" (click)="editable = !editable">Cancel</button>
<button class="btn btn-save" (click)="saveItem(editedItem.value)">
Save
</button>
</div>
</div>
</div>
```
The first input is a checkbox so users can check off items when an item is complete.
The double curly braces, `{{}}`, in the `<label>` for the checkbox signifies Angular's interpolation.
Angular uses `{{item.description}}` to retrieve the description of the current `item` from the `items` array.
The next section explains how components share data in detail.
The next two buttons for editing and deleting the current item are within a `<div>`.
On this `<div>` is an `*ngIf`, a built-in Angular directive that you can use to dynamically change the structure of the DOM.
This `*ngIf` means that if `editable` is `false`, this `<div>` is in the DOM. If `editable` is `true`, Angular removes this `<div>` from the DOM.
```html
<div class="btn-wrapper" \*ngIf="!editable">
<button class="btn" (click)="editable = !editable">Edit</button>
<button class="btn btn-warn" (click)="remove.emit()">Delete</button>
</div>
```
When a user clicks the **Edit** button, `editable` becomes true, which removes this `<div>` and its children from the DOM.
If, instead of clicking **Edit**, a user clicks **Delete**, the `ItemComponent` raises an event that notifies the `AppComponent` of the deletion.
An `*ngIf` is also on the next `<div>`, but is set to an `editable` value of `true`.
In this case, if `editable` is `true`, Angular puts the `<div>` and its child `<input>` and `<button>` elements in the DOM.
```html
<!-- This section shows only if user clicks Edit button -->
<div \*ngIf="editable">
<input
class="sm-text-input"
placeholder="edit item"
[value]="item.description"
#editedItem
(keyup.enter)="saveItem(editedItem.value)" />
<div class="btn-wrapper">
<button class="btn" (click)="editable = !editable">Cancel</button>
<button class="btn btn-save" (click)="saveItem(editedItem.value)">
Save
</button>
</div>
</div>
```
With `[value]="item.description"`, the value of the `<input>` is bound to the `description` of the current item.
This binding makes the item's `description` the value of the `<input>`.
So if the `description` is `eat`, the `description` is already in the `<input>`.
This way, when the user edits the item, the value of the `<input>` is already `eat`.
The template variable, `#editedItem`, on the `<input>` means that Angular stores whatever a user types in this `<input>` in a variable called `editedItem`.
The `keyup` event calls the `saveItem()` method and passes in the `editedItem` value if the user chooses to press enter instead of click **Save**.
When a user clicks the **Cancel** button, `editable` toggles to `false`, which removes the input and buttons for editing from the DOM.
When `editable` is `false`, Angular puts `<div>` with the **Edit** and **Delete** buttons back in the DOM.
Clicking the **Save** button calls the `saveItem()` method.
The `saveItem()` method takes the value from the `#editedItem` element and changes the item's `description` to `editedItem.value` string.
Prepare the AppComponent
------------------------
In the next section, you will add code that relies on communication between the `AppComponent` and the `ItemComponent`.
Add the following line near the top of the `app.component.ts` file to import the `Item`:
```ts
import { Item } from "./item";
```
Then, configure the AppComponent by adding the following to the same file's class:
```js
remove(item: Item) {
this.allItems.splice(this.allItems.indexOf(item), 1);
}
```
The `remove()` method uses the JavaScript `Array.splice()` method to remove one item at the `indexOf` the relevant item.
In plain English, this means that the `splice()` method removes the item from the array.
For more information on the `splice()` method, see the MDN Web Docs article on `Array.prototype.splice()`.
Add logic to ItemComponent
--------------------------
To use the `ItemComponent` UI, you must add logic to the component such as functions, and ways for data to go in and out.
In `item.component.ts`, edit the JavaScript imports as follows:
```js
import { Component, Input, Output, EventEmitter } from "@angular/core";
import { Item } from "../item";
```
The addition of `Input`, `Output`, and `EventEmitter` allows `ItemComponent` to share data with `AppComponent`.
By importing `Item`, `ItemComponent` can understand what an `item` is.
Further down `item.component.ts`, replace the generated `ItemComponent` class with the following:
```js
export class ItemComponent {
editable = false;
@Input() item!: Item;
@Output() remove = new EventEmitter<Item>();
saveItem(description: string) {
if (!description) return;
this.editable = false;
this.item.description = description;
}
}
```
The `editable` property helps toggle a section of the template where a user can edit an item.
`editable` is the same property in the HTML as in the `*ngIf` statement, `*ngIf="editable"`.
When you use a property in the template, you must also declare it in the class.
`@Input()`, `@Output()`, and `EventEmitter` facilitate communication between your two components.
An `@Input()` serves as a doorway for data to come into the component, and an `@Output()` acts as a doorway for data to go out of the component.
An `@Output()` has to be of type `EventEmitter`, so that a component can raise an event when there's data ready to share with another component.
>
> **Note**: The `!` in the class's property declaration is called a definite assignment assertion. This operator tells Typescript that the `item` field is always initialized and not `undefined`, even when TypeScript cannot tell from the constructor's definition. If this operator is not included in your code and you have strict TypeScript compilation settings, the app will fail to compile.
>
>
>
Use `@Input()` to specify that the value of a property can come from outside of the component.
Use `@Output()` in conjunction with `EventEmitter` to specify that the value of a property can leave the component so that another component can receive that data.
The `saveItem()` method takes as an argument a `description` of type `string`.
The `description` is the text that the user enters into the HTML `<input>` when editing an item in the list.
This `description` is the same string from the `<input>` with the `#editedItem` template variable.
If the user doesn't enter a value but clicks **Save**, `saveItem()` returns nothing and does not update the `description`.
If you didn't have this `if` statement, the user could click **Save** with nothing in the HTML `<input>`, and the `description` would become an empty string.
If a user enters text and clicks save, `saveItem()` sets `editable` to false, which causes the `*ngIf` in the template to remove the edit feature and render the **Edit** and **Delete** buttons again.
Though the application should compile at this point, you need to use the `ItemComponent` in `AppComponent` so you can see the new features in the browser.
Use the ItemComponent in the AppComponent
-----------------------------------------
Including one component within another in the context of a parent-child relationship gives you the flexibility of using components wherever you need them.
The `AppComponent` serves as a shell for the application where you can include other components.
To use the `ItemComponent` in `AppComponent`, put the `ItemComponent` selector in the `AppComponent` template.
Angular specifies the selector of a component in the metadata of the `@Component()` decorator.
In this example, the selector is `app-item`:
```js
@Component({
selector: 'app-item',
templateUrl: './item.component.html',
styleUrls: ['./item.component.css']
})
```
To use the `ItemComponent` selector within the `AppComponent`, you add the element, `<app-item>`, which corresponds to the selector you defined for the component class to `app.component.html`.
Replace the current unordered list in `app.component.html` with the following updated version:
```html
<h2>
{{items.length}}
<span \*ngIf="items.length === 1; else elseBlock">item</span>
<ng-template #elseBlock>items</ng-template>
</h2>
<ul>
<li \*ngFor="let i of items">
<app-item (remove)="remove(i)" [item]="i"></app-item>
</li>
</ul>
```
The double curly brace syntax, `{{}}`, in the `<h2>` interpolates the length of the `items` array and displays the number.
The `<span>` in the `<h2>` uses an `*ngIf` and `else` to determine whether the `<h2>` should say "item" or "items".
If there is only a single item in the list, the `<span>` containing "item" displays.
Otherwise, if the length of the `items` array is anything other than `1`, the `<ng-template>`, which we've named `elseBlock`, with the syntax `#elseBlock`, shows instead of the `<span>`.
You can use Angular's `<ng-template>` when you don't want content to render by default.
In this case, when the length of the `items` array is not `1`, the `*ngIf` shows the `elseBlock` and not the `<span>`.
The `<li>` uses Angular's repeater directive, `*ngFor`, to iterate over all of the items in the `items` array.
Angular's `*ngFor` like `*ngIf`, is another directive that helps you change the structure of the DOM while writing less code.
For each `item`, Angular repeats the `<li>` and everything within it, which includes `<app-item>`.
This means that for each item in the array, Angular creates another instance of `<app-item>`.
For any number of items in the array, Angular would create that many `<li>` elements.
You can use an `*ngFor` on other elements, too, such as `<div>`, `<span>`, or `<p>`, to name a few.
The `AppComponent` has a `remove()` method for removing the item, which is bound to the `remove` property in the `ItemComponent`.
The `item` property in the square brackets, `[]`, binds the value of `i` between the `AppComponent` and the `ItemComponent`.
Now you should be able to edit and delete items from the list.
When you add or delete items, the count of the items should also change.
To make the list more user-friendly, add some styles to the `ItemComponent`.
Add styles to ItemComponent
---------------------------
You can use a component's style sheet to add styles specific to that component.
The following CSS adds basic styles, flexbox for the buttons, and custom checkboxes.
Paste the following styles into `item.component.css`.
```css
.item {
padding: 0.5rem 0 0.75rem 0;
text-align: left;
font-size: 1.2rem;
}
.btn-wrapper {
margin-top: 1rem;
margin-bottom: 0.5rem;
}
.btn {
/\* menu buttons flexbox styles \*/
flex-basis: 49%;
}
.btn-save {
background-color: #000;
color: #fff;
border-color: #000;
}
.btn-save:hover {
background-color: #444242;
}
.btn-save:focus {
background-color: #fff;
color: #000;
}
.checkbox-wrapper {
margin: 0.5rem 0;
}
.btn-warn {
background-color: #b90000;
color: #fff;
border-color: #9a0000;
}
.btn-warn:hover {
background-color: #9a0000;
}
.btn-warn:active {
background-color: #e30000;
border-color: #000;
}
.sm-text-input {
width: 100%;
padding: 0.5rem;
border: 2px solid #555;
display: block;
box-sizing: border-box;
font-size: 1rem;
margin: 1rem 0;
}
/\* Custom checkboxes
Adapted from https://css-tricks.com/the-checkbox-hack/#custom-designed-radio-buttons-and-checkboxes \*/
/\* Base for label styling \*/
[type="checkbox"]:not(:checked),
[type="checkbox"]:checked {
position: absolute;
left: -9999px;
}
[type="checkbox"]:not(:checked) + label,
[type="checkbox"]:checked + label {
position: relative;
padding-left: 1.95em;
cursor: pointer;
}
/\* checkbox aspect \*/
[type="checkbox"]:not(:checked) + label:before,
[type="checkbox"]:checked + label:before {
content: "";
position: absolute;
left: 0;
top: 0;
width: 1.25em;
height: 1.25em;
border: 2px solid #ccc;
background: #fff;
}
/\* checked mark aspect \*/
[type="checkbox"]:not(:checked) + label:after,
[type="checkbox"]:checked + label:after {
content: "\2713\0020";
position: absolute;
top: 0.15em;
left: 0.22em;
font-size: 1.3em;
line-height: 0.8;
color: #0d8dee;
transition: all 0.2s;
font-family: "Lucida Sans Unicode", "Arial Unicode MS", Arial;
}
/\* checked mark aspect changes \*/
[type="checkbox"]:not(:checked) + label:after {
opacity: 0;
transform: scale(0);
}
[type="checkbox"]:checked + label:after {
opacity: 1;
transform: scale(1);
}
/\* accessibility \*/
[type="checkbox"]:checked:focus + label:before,
[type="checkbox"]:not(:checked):focus + label:before {
border: 2px dotted blue;
}
```
Summary
-------
You should now have a styled Angular to-do list application that can add, edit, and remove items.
The next step is to add filtering so that you can look at items that meet specific criteria.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Getting started with Vue - Learn web development | Getting started with Vue
========================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
Now let's introduce Vue, the third of our frameworks. In this article we'll look at a little bit of Vue background, learn how to install it and create a new project, study the high-level structure of the whole project and an individual component, see how to run the project locally, and get it prepared to start building our example.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with node + npm installed.
|
| Objective: |
To setup a local Vue development environment, create a starter app, and
understand the basics of how it works.
|
A clearer Vue
-------------
Vue is a modern JavaScript framework that provides useful facilities for progressive enhancement β unlike many other frameworks, you can use Vue to enhance existing HTML. This lets you use Vue as a drop-in replacement for a library like jQuery.
That being said, you can also use Vue to write entire Single Page Applications (SPAs). This allows you to create markup managed entirely by Vue, which can improve developer experience and performance when dealing with complex applications. It also allows you to take advantage of libraries for client-side routing and state management when you need to. Additionally, Vue takes a "middle ground" approach to tooling like client-side routing and state management. While the Vue core team maintains suggested libraries for these functions, they are not directly bundled into Vue. This allows you to select a different routing/state management library if they better fit your application.
In addition to allowing you to progressively integrate Vue into your applications, Vue also provides a progressive approach to writing markup. Like most frameworks, Vue lets you create reusable blocks of markup via components. Most of the time, Vue components are written using a special HTML template syntax. When you need more control than the HTML syntax allows, you can write JSX or plain JavaScript functions to define your components.
As you work through this tutorial, you might want to keep the Vue guide and API documentation open in other tabs, so you can refer to them if you want more information on any sub topic.
For a good (but potentially biased) comparison between Vue and many of the other frameworks, see Vue Docs: Comparison with Other Frameworks.
Installation
------------
To use Vue in an existing site, you can drop one of the following `<script>` elements onto a page. This allows you to start using Vue on existing sites, which is why Vue prides itself on being a progressive framework. This is a great option when migrating an existing project using a library like jQuery to Vue. With this method, you can use a lot of the core features of Vue, such as the attributes, custom components, and data-management.
* Development Script (not optimized, but includes console warnings which is great for development.)
```html
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
```
* Production Script (Optimized version, minimal console warnings. It is recommended that you specify a version number when including Vue on your site so that any framework updates do not break your live site without you knowing.)
```html
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
```
However, this approach has some limitations. To build more complex apps, you'll want to use the Vue npm package. This will let you use advanced features of Vue and take advantage of bundlers like WebPack. To make building apps with Vue easier, there is a CLI to streamline the development process. To use the npm package & the CLI you will need:
1. Node.js 8.11+ installed.
2. npm or yarn.
**Note:** If you don't have the above installed, find out more about installing npm and Node.js here.
To install the CLI, run the following command in your terminal:
```bash
npm install --global @vue/cli
```
Or if you'd prefer to use yarn:
```bash
yarn global add @vue/cli
```
Once installed, to initialize a new project you can then open a terminal in the directory you want to create the project in, and run `vue create <project-name>`. The CLI will then give you a list of project configurations you can use. There are a few preset ones, and you can make your own. These options let you configure things like TypeScript, linting, vue-router, testing, and more.
We'll look at using this below.
Initializing a new project
--------------------------
To explore various features of Vue, we will be building up a sample todo list app. We'll begin by using the Vue CLI to create a new app framework to build our app into.
In terminal, `cd` to where you'd like to create your sample app, then run `vue create moz-todo-vue`.
You can choose the default option `Default ([Vue 3] babel, eslint)` by pressing `Enter` to proceed.
The CLI will now begin scaffolding out your project, and installing all of your dependencies.
If you've never run the Vue CLI before, you'll get one more question β you'll be asked to choose a package manager which defaults to `yarn`.
The Vue CLI will default to this package manager from now on. If you need to use a different package manager after this, you can pass in a flag `--packageManager=<package-manager>`, when you run `vue create`. So if you wanted to create the `moz-todo-vue` project with npm and you'd previously chosen yarn, you'd run `vue create moz-todo-vue --packageManager=npm`.
**Note:** We've not gone over all of the options here, but you can find more information on the CLI in the Vue docs.
Project structure
-----------------
If everything went successfully, the CLI should have created a series of files and directories for your project. The most significant ones are as follows:
* `package.json`: This file contains the list of dependencies for your project, as well as some metadata and `eslint` configuration.
* `yarn.lock`: If you chose `yarn` as your package manager, this file will be generated with a list of all the dependencies and sub-dependencies that your project needs.
* `babel.config.js`: This is the config file for Babel, which transforms modern JavaScript features being used in development code into older syntax that is more cross-browser compatible in production code. You can register additional babel plugins in this file.
* `jsconfig.json`: This is a config file for Visual Studio Code and gives context for VS Code on your project structure and assists auto-completion.
* `public`: This directory contains static assets that are published, but not processed by Webpack during build (with one exception; `index.html` gets some processing).
+ `favicon.ico`: This is the favicon for your app. Currently, it's the Vue logo.
+ `index.html`: This is the template for your app. Your Vue app is run from this HTML page, and you can use lodash template syntax to interpolate values into it.
**Note:** this is not the template for managing the layout of your application β this template is for managing static HTML that sits outside of your Vue app. Editing this file typically only occurs in advanced use cases.
* `src`: This directory contains the core of your Vue app.
+ `main.js`: this is the entry point to your application. Currently, this file initializes your Vue application and signifies which HTML element in the `index.html` file your app should be attached to. This file is often where you register global components or additional Vue libraries.
+ `App.vue`: this is the top-level component in your Vue app. See below for more explanation of Vue components.
+ `components`: this directory is where you keep your components. Currently, it just has one example component.
+ `assets`: this directory is for storing static assets like CSS and images. Because these files are in the source directory, they can be processed by Webpack. This means you can use pre-processors like Sass/SCSS or Stylus.
**Note:** Depending on the options you select when creating a new project, there might be other directories present (for example, if you choose a router, you will also have a `views` directory).
.vue files (single file components)
-----------------------------------
Like in many front-end frameworks, components are a central part of building apps in Vue. These components let you break a large application into discrete building blocks that can be created and managed separately, and transfer data between each other as required. These small blocks can help you reason about and test your code.
While some frameworks encourage you to separate your template, logic, and styling code into separate files, Vue takes the opposite approach. Using Single File Components (SFC), Vue lets you group your templates, corresponding script, and CSS all together in a single file ending in `.vue`. These files are processed by a JS build tool (such as Webpack), which means you can take advantage of build-time tooling in your project. This allows you to use tools like Babel, TypeScript, SCSS and more to create more sophisticated components.
As a bonus, projects created with the Vue CLI are configured to use `.vue` files with Webpack out of the box. In fact, if you look inside the `src` folder in the project we created with the CLI, you'll see your first `.vue` file: `App.vue`.
Let's explore this now.
### App.vue
Open your `App.vue` file β you'll see that it has three parts: `<template>`, `<script>`, and `<style>`, which contain the component's template, scripting, and styling information. All Single File Components share this same basic structure.
`<template>` contains all the markup structure and display logic of your component. Your template can contain any valid HTML, as well as some Vue-specific syntax that we'll cover later.
**Note:** By setting the `lang` attribute on the `<template>` tag, you can use Pug template syntax instead of standard HTML β `<template lang="pug">`. We'll stick to standard HTML through this tutorial, but it is worth knowing that this is possible.
`<script>` contains all of the non-display logic of your component. Most importantly, your `<script>` tag needs to have a default exported JS object. This object is where you locally register components, define component inputs (props), handle local state, define methods, and more. Your build step will process this object and transform it (with your template) into a Vue component with a `render()` function.
In the case of `App.vue`, our default export sets the name of the component to `App` and registers the `HelloWorld` component by adding it into the `components` property. When you register a component in this way, you're registering it locally. Locally registered components can only be used inside the components that register them, so you need to import and register them in every component file that uses them. This can be useful for bundle splitting/tree shaking since not every page in your app necessarily needs every component.
```js
import HelloWorld from "./components/HelloWorld.vue";
export default {
name: "App",
components: {
//You can register components locally here.
HelloWorld,
},
};
```
**Note:** If you want to use TypeScript syntax, you need to set the `lang` attribute on the `<script>` tag to signify to the compiler that you're using TypeScript β `<script lang="ts">`.
`<style>` is where you write your CSS for the component. If you add a `scoped` attribute β `<style scoped>` β Vue will scope the styles to the contents of your SFC. This works similar to CSS-in-JS solutions, but allows you to just write plain CSS.
**Note:** If you select a CSS pre-processor when creating the project via the CLI, you can add a `lang` attribute to the `<style>` tag so that the contents can be processed by Webpack at build time. For example, `<style lang="scss">` will allow you to use SCSS syntax in your styling information.
Running the app locally
-----------------------
The Vue CLI comes with a built-in development server. This allows you to run your app locally so you can test it easily without needing to configure a server yourself. The CLI adds a `serve` command to the project's `package.json` file as an npm script, so you can easily run it.
In your terminal, try running `npm run serve` (or `yarn serve` if you prefer yarn). Your terminal should output something like the following:
```
INFO Starting development server...
98% after emitting CopyPlugin
DONE Compiled successfully in 18121ms
App running at:
- Local: <http://localhost:8080/>
- Network: <http://192.168.1.9:8080/>
Note that the development build is not optimized.
To create a production build, run npm run build.
```
If you navigate to the "local" address in a new browser tab (this should be something like `http://localhost:8080` as stated above, but may vary based on your setup), you should see your app. Right now, it should contain a welcome message, a link to the Vue documentation, links to the plugins you added when you initialized the app with your CLI, and some other useful links to the Vue community and ecosystem.
![default Vue app render, with Vue logo, welcome message, and some documentation links](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started/vue-default-app.png)
Making a couple of changes
--------------------------
Let's make our first change to the app β we'll delete the Vue logo. Open the `App.vue` file, and delete the `<img>` element from the template section:
```html
<img alt="Vue logo" src="./assets/logo.png" />
```
If your server is still running, you should see the logo removed from the rendered site almost instantly. Let's also remove the `HelloWorld` component from our template.
First of all delete this line:
```html
<HelloWorld msg="Welcome to Your Vue.js App" />
```
If you save your `App.vue` file now, the rendered app will throw an error because we've registered the component but are not using it. We also need to remove the lines from inside the `<script>` element that import and register the component:
Delete these lines now:
```js
import HelloWorld from "./components/HelloWorld.vue";
```
```js
components: {
HelloWorld;
}
```
The `<template>` tag is empty now so you'll see an error saying `The template requires child element` in both the console and the rendered app.
You can fix this by adding some content inside the `<template>` tag and we can start with a new `<h1>` element inside a `<div>`.
Since we're going to be creating a todo list app below, let's set our heading to "To-Do List" like so:
```html
<template>
<div id="app">
<h1>To-Do List</h1>
</div>
</template>
```
`App.vue` will now show our heading, as you'd expect.
Summary
-------
Let's leave this here for now. We've learnt about some of the ideas behind Vue, created some scaffolding for our example app to live inside, inspected it, and made a few preliminary changes.
With a basic introduction out of the way, we'll now go further and build up our sample app, a basic Todo list application that allows us to store a list of items, check them off when done, and filter the list by all, complete, and incomplete todos.
In the next article we'll build our first custom component, and look at some important concepts such as passing props into it and saving its data state.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
React resources - Learn web development | React resources
===============
* Previous
* Overview: Client-side JavaScript frameworks
* Next
Our final article provides you with a list of React resources that you can use to go further in your learning.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
|
| Objective: | To provide further resources for learning more about React. |
Component-level styles
----------------------
While we kept all the CSS for our tutorial in a single `index.css` file, it's common for React applications to define per-component stylesheets. In an application powered by Vite, this can be done by creating a CSS file and importing it into its corresponding component module.
For example: we could have written a dedicated `Form.css` file to house the CSS related to the `<Form />` component, then imported the styles into `Form.jsx`, like this:
```jsx
import Form from "./Form";
import "./Form.css";
```
This approach makes it easy to identify and manage the CSS that belongs to a specific component and distinguish it from your app-wide styles. However, it also fragments your stylesheet across your codebase, and this fragmentation might not be worthwhile. For larger applications with hundreds of unique views and lots of moving parts, it makes sense to use component-level styles and thereby limit the amount of irrelevant code that's sent to your user at any one time.
You can read more about this and other approaches to styling React components in the Smashing Magazine article, Styling Components In React.
React DevTools
--------------
We used `console.log()` to check on the state and props of our application in this tutorial, and you'll also have seen some of the useful warnings and error message that React gives you both in the CLI and your browser's JavaScript console. But there's more we can do here.
The React DevTools utility allows you to inspect the internals of your React application directly in the browser. It adds a new panel to your browser's developer tools that allows you to inspect the state and props of various components, and even edit state and props to make immediate changes to your application.
This screenshot shows our finished application as it appears in React DevTools:
![Our project being shown in React devtools](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_resources/react-devtools.png)
On the left, we see all of the components that make up our application, including unique keys for the items that are rendered from arrays. On the right, we see the props and hooks that our App component uses. Notice, too, that the `Form`, `FilterButton`, and `Todo` components are indented to the right β this indicates that `App` is their parent. This view is great for understanding parent/child relationships at a glance and is invaluable for understanding more complex apps.
React DevTools is available in several forms:
* A Chrome browser extension.
* A Firefox browser extension.
* A Microsoft Edge browser extension.
* A stand-alone application you can install with npm or Yarn.
Try installing one of these, and then using it to inspect the app you've just built!
You can read more about React DevTools in the React docs.
The `useReducer()` hook
-----------------------
In this tutorial, we used the `useState()` hook to manage state across a small collection of event handler functions. This was fine for learning purposes, but it left our state management logic tied to our component's event handlers β especially those of the `<Todo />` component.
The `useReducer()` hook offers developers a way to consolidate different-but-related state management logic into a single function. It's a bit more complex than `useState()`, but it's a good tool to have in your belt. You can read more about `useReducer()` in the React docs.
The Context API
---------------
The application that we built in this tutorial utilized component props to pass data from its `App` component to the child components that needed it. Most of the time, props are an appropriate method for sharing data; for complex, deeply nested applications, however, they're not always best.
React provides the Context API as a way to provide data to components that need it *without* passing props down the component tree. There's also a useContext hook that facilitates this.
If you'd like to try this API for yourself, Smashing Magazine has written an introductory article about React context.
Class components
----------------
Although this tutorial doesn't mention them, it is possible to build React components using JavaScript classes β these are called class components. Until the arrival of hooks, classes were the only way to bring state into components or manage rendering side effects. They're still the only way to handle certain edge-cases, and they're common in legacy React projects. The official React docs maintain a reference for the `Component` base class, but recommend using hooks to manage state and side effects.
Testing
-------
Libraries such as React Testing Library make it possible to write unit tests for React components. There are many ways to *run* these tests. The testing framework Vitest is built on top of Vite, and is a great companion to your Vite-powered React applications. Jest is another popular testing framework that can be used with React.
Routing
-------
While routing is traditionally handled by a server and not an application on the user's computer, it is possible to configure a web application to read and update the browser's location, and render certain user interfaces. This is called *client-side routing*. It's possible to create many unique routes for your application (such as `/home`, `/dashboard`, or `/login`).
React Router is the most popular and most robust client-side routing library for React. It allows developers to define the routes of their application, and associate components with those routes . It also provides a number of useful hooks and components for managing the browser's location and history.
**Note:** Client-side routing can make your application feel fast, but it poses a number of accessibility problems, especially for people who rely on assistive techology. You can read more about this in Marcy Sutton's article, "The Implications of Client-Side Routing".
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
TypeScript support in Svelte - Learn web development | TypeScript support in Svelte
============================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
In the last article we learned about Svelte stores and even implemented our own custom store to persist the app's information to Web Storage. We also had a look at using the transition directive to implement animations on DOM elements in Svelte.
We will now learn how to use TypeScript in Svelte applications. First we'll learn what TypeScript is and what benefits it can bring us. Then we'll see how to configure our project to work with TypeScript files. Finally we will go over our app and see what modifications we have to make to fully take advantage of TypeScript features.
| | |
| --- | --- |
| Prerequisites: |
At minimum, it is recommended that you are familiar with the core
HTML,
CSS, and
JavaScript languages, and
have knowledge of the
terminal/command line.
You'll need a terminal with node and npm installed to compile and build
your app.
|
| Objective: |
Learn how to configure and use TypeScript when developing Svelte
applications.
|
Note that our application is fully functional, and porting it to TypeScript is completely optional. There are different opinions about it, and in this chapter we will talk briefly about the pros and cons of using TypeScript. Even if you are not planning to adopt it, this article will be useful for allowing you to learn what it has to offer and help you make your own decision. If you are not interested at all in TypeScript, you can skip to the next chapter, where we will look at different options for deploying our Svelte applications, further resources, and more.
Code along with us
------------------
### Git
Clone the GitHub repo (if you haven't already done it) with:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then to get to the current app state, run
```bash
cd mdn-svelte-tutorial/07-typescript-support
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/07-typescript-support
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
Unfortunately, TypeScript support is not yet available in the REPL.
TypeScript: optional static typing for JavaScript
-------------------------------------------------
TypeScript is a superset of JavaScript that provides features such as optional static typing, classes, interfaces, and generics. The goal of TypeScript is to help catch mistakes early through its type system and make JavaScript development more efficient. One of the big benefits is enabling IDEs to provide a richer environment for spotting common errors as you type the code.
Best of all, JavaScript code is valid TypeScript code; TypeScript is a superset of JavaScript. You can rename most of your `.js` files to `.ts` files and they will just work.
Our TypeScript code will be able to run everywhere JavaScript can run. How is that possible? TypeScript "transpiles" our code to vanilla JavaScript. That means that it parses TypeScript code and produces the equivalent vanilla JavaScript code for browsers to run.
**Note:** If you are curious about how TypeScript transpiles our code to JavaScript, you can have a look at the TypeScript Playground.
First-class TypeScript support has been Svelte's most requested feature for quite some time. Thanks to the hard work of the Svelte team, together with many contributors, we have an official solution ready to be put to the test. In this section we'll show you how to set up a Svelte project with TypeScript support to give it a try.
Why TypeScript?
---------------
TypeScript's main advantages are:
* Early spotted bugs: The compiler checks types at compile time and provides error reporting.
* Readability: Static typing gives the code more structure, making it self-documenting and more readable.
* Rich IDE support: Type information allows code editors and IDEs to offer features like code navigation, autocompletion, and smarter hints.
* Safer refactoring: Types allows IDEs to know more about your code, and assist you while refactoring large portions of your code base.
* Type inference: Enables you to take advantage of many TypeScript features even without declaring variable types.
* Availability of new and future JavaScript features: TypeScript transpiles many recent JavaScript features to plain old-school JavaScript, allowing you to use them even on user-agents that don't support them natively yet.
TypeScript also has some disadvantages:
* Not true static typing: Types are only checked at compile time, and they are removed from the generated code.
* Steep learning curve: Even though TypeScript is a superset of JavaScript and not a completely new language, there is a considerable learning curve, especially if you have no experience at all with static languages like Java or C#.
* More code: You have to write and maintain more code.
* No replacement for automatic tests: Even though types might help you catch several bugs, TypeScript is not a true replacement for a comprehensive suite of automated tests.
* Boilerplate code: Working with types, classes, interfaces, and generics can lead to over-engineered code bases.
There seems to be a broad consensus that TypeScript is particularly well suited for large-scale projects, with many developers working on the same codebase. And it is indeed being used by several large-scale projects, like Angular 2, Vue 3, Ionic, Visual Studio Code, Jest, and even the Svelte compiler. Nevertheless, some developers prefer to use it even on small projects like the one we are developing.
In the end, it's your decision. In the following sections we hope to give you more evidence to make up your mind about it.
Creating a Svelte TypeScript project from scratch
-------------------------------------------------
You can start a new Svelte TypeScript project using the standard template. All you have to do is run the following terminal commands (run them somewhere where you are storing your Svelte test projects β it creates a new directory):
```bash
npx degit sveltejs/template svelte-typescript-app
cd svelte-typescript-app
node scripts/setupTypeScript.js
```
This creates a starter project that includes TypeScript support, which you can then modify as you wish.
Then you'll have to tell npm to download dependencies and start the project in development mode, as we usually do:
```bash
npm install
npm run dev
```
Adding TypeScript support to an existing Svelte Project
-------------------------------------------------------
To add TypeScript support to an existing Svelte project, you can follow these instructions. Alternatively, you can download the `setupTypeScript.js` file to a `scripts` folder inside your project's root folder, and then run `node scripts/setupTypeScript.js`.
You can even use `degit` to download the script. That's what we will do to start porting our application to TypeScript.
**Note:** Remember that you can run `npx degit opensas/mdn-svelte-tutorial/07-typescript-support svelte-todo-typescript` to get the complete to-do list application in JavaScript before you start porting it to TypeScript.
Go to the root directory of the project and enter these commands:
```bash
npx degit sveltejs/template/scripts scripts # download script file to a scripts folder
node scripts/setupTypeScript.js # run it
Converted to TypeScript.
```
You will need to re-run your dependency manager to get started.
```bash
npm install # download new dependencies
npm run dev # start the app in development mode
```
These instructions apply to any Svelte project you'd like to convert to TypeScript. Just take into account that the Svelte community is constantly improving Svelte TypeScript support, so you should run `npm update` regularly to take advantage of the latest changes.
**Note:** if you find any trouble working with TypeScript inside a Svelte application, have a look at this troubleshooting/FAQ section about TypeScript support.
As we said before, TypeScript is a superset of JavaScript, so your application will run without modifications. Currently you will be running a regular JavaScript application with TypeScript support enabled, without taking advantage of any of the features that TypeScript provides. You can now start adding types progressively.
Once you have TypeScript configured, you can start using it from a Svelte component by just adding a `<script lang='ts'>` at the beginning of the script section. To use it from regular JavaScript files, just change the file extension from `.js` to `.ts`. You'll also have to update any corresponding import statements (don't include the `.ts` in your `import` statements; TypeScript chose to omit the extensions).
**Note:** Using TypeScript in component markup sections is not supported yet. You'll have to use JavaScript from the markup, and TypeScript in the `<script lang='ts'>` section.
Improved developer experience with TypeScript
---------------------------------------------
TypeScript provides code editors and IDEs with lots of information to allow them to deliver a friendlier development experience.
We'll use Visual Studio Code to do a quick test and see how we can get autocompletion hints and type-checking as we're writing components.
**Note:** If you don't wish to use VS Code, we also provide instructions for using TypeScript error checking from the terminal instead, slightly later on.
There is work in progress to support TypeScript in Svelte projects in several code editors; the most complete support so far is available in the Svelte for VS Code extension, which is developed and maintained by the Svelte team. This extension offers type checking, inspecting, refactoring, intellisense, hover-information, auto-completion, and other features. This kind of developer assistance is another good reason to start using TypeScript in your projects.
**Note:** Make sure you are using Svelte for VS Code and NOT the old "Svelte" by James Birtles, which has been discontinued. In case you have it installed, you should uninstall it and install the official Svelte extension instead.
Assuming you are inside the VS Code application, from the root of your project's folder, type `code .` (the trailing dot tells VS Code to open the current folder) to open the code editor. VS Code will tell you that there are recommended extensions to install.
![Dialog box saying this workspace has extension recommendations, with options to install or show a list](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript/01-vscode-extension-recommendations.png)
Clicking *Install all* will install Svelte for VS Code.
![Svelte for VS Code extension information](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript/02-svelte-for-vscode.png)
We can also see that the `setupTypeScript.js` file made a couple of changes to our project. The `main.js` file has been renamed to `main.ts`, which means that VS Code can provide hover-information on our Svelte components:
![VS Code screenshot showing that when you add type="ts" to a component, it gives you three dot alert hints](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript/03-vscode-hints-in-main-ts.png)
We also get type checking for free. If we pass an unknown property in the options parameter of the `App` constructor (for example a typo like `traget` instead of `target`), TypeScript will complain:
![Type checking in VS Code - App object has been given an unknown property target](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript/04-vscode-type-checking-in-main-ts.png)
In the `App.svelte` component, the `setupTypeScript.js` script has added the `lang="ts"` attribute to the `<script>` tag. Moreover, thanks to type inference, in many cases we won't even need to specify types to get code assistance. For example, if you start adding an `ms` property to the `Alert` component call, TypeScript will infer from the default value that the `ms` property should be a number:
![VS Code type inference and code hinting - ms variable should be a number](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript/05-vscode-type-inference-and-code-assistance.png)
And if you pass something that is not a number, it will complain about it:
![Type checking in VS Code - App object has been given an unknown property target](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript/06-vscode-type-checking-in-components.png)
The application template has a `check` script configured that runs `svelte-check` against your code. This package allows you to detect errors and warnings normally displayed by a code editor from the command line, which makes it pretty useful for running it in a continuous integration (CI) pipeline. Just run `npm run check` to check for unused CSS, and return A11y hints and TypeScript compile errors.
In this case, if you run `npm run check` (either in the VS Code console or terminal) you will get the following error:
![Check command being run inside VS Code showing type error, ms variable should be assigned a number](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript/07-vscode-svelte-check.png)
Even better, if you run it from the VS Code integrated terminal (you can open it with the `Ctrl` + ``` keyboard shortcut), `Cmd`/`Ctrl` clicking on the file name will take you to the line containing the error.
You can also run the `check` script in watch mode with `npm run check -- --watch`. In this case, the script will execute whenever you change any file. If you are running this in your regular terminal, keep it running in the background in a separate terminal window so that it can keep reporting errors but won't interfere with other terminal usage.
Creating a custom type
----------------------
TypeScript supports structural typing. Structural typing is a way of relating types based solely on their members, even if you do not explicitly define the type.
We'll define a `TodoType` type to see how TypeScript enforces that anything passed to a component expecting a `TodoType` will be structurally compatible with it.
1. Inside the `src` folder create a `types` folder.
2. Add a `todo.type.ts` file inside it.
3. Give `todo.type.ts` the following content:
```ts
export type TodoType = {
id: number;
name: string;
completed: boolean;
};
```
**Note:** The Svelte template uses svelte-preprocess 4.0.0 to support TypeScript. From that version onward you have to use `export`/`import` type syntax to import types and interfaces. Check this section of the troubleshooting guide for more information.
4. Now we'll use `TodoType` from our `Todo.svelte` component. First add the `lang="ts"` to our `<script>` tag.
5. Let's `import` the type and use it to declare the `todo` property. Replace the `export let todo` line with the following:
```ts
import type { TodoType } from "../types/todo.type";
export let todo: TodoType;
```
**Note:** Another reminder: When importing a `.ts` file, you have to omit the extension. Check the `import` section of the TypeScript manual for more information.
6. Now from `Todos.svelte` we will instantiate a `Todo` component with a literal object as its parameter before the call to the `MoreActions` component, like this:
```svelte
<hr />
<Todo todo={ { name: 'a new task with no id!', completed: false } } />
<!-- MoreActions -->
<MoreActions {todos}
```
7. Add the `lang='ts'` to the `<script>` tag of the `Todos.svelte` component so that it knows to use the type checking we have specified.
We will get the following error:
![Type error in VS Code, Todo Type object requires an id property.](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript/08-vscode-structural-typing.png)
By now you should get an idea about the kind of assistance we can get from TypeScript when building Svelte projects.
Now we will undo these changes in order to start porting our application to TypeScript, so we won't be bothered with all the check warnings.
1. Remove the flawed to-do and the `lang='ts'` attribute from the `Todos.svelte` file.
2. Also remove the import of `TodoType` and the `lang='ts'` from `Todo.svelte`.
We'll take care of them properly later on.
Porting our to-do list app to TypeScript
----------------------------------------
Now we are ready to start porting our to-do list application to take advantage of all the features that TypeScript offers to us.
Let's start by running the check script in watch mode inside the project root:
```bash
npm run check -- --watch
```
This should output something like the following:
```bash
svelte-check "--watch"
Loading svelte-check in workspace: ./svelte-todo-typescript
Getting Svelte diagnostics...
====================================
svelte-check found no errors and no warnings
```
Note that if you are using a supporting code editor like VS Code, a simple way to start porting a Svelte component is to just add the `<script lang='ts'>` at the top of your component and look for the three-dotted hints:
![VS Code screenshot showing that when you add type="ts" to a component, it gives you three dot alert hints](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript/09-vscode-alert-hints.png)
### Alert.svelte
Let's start with our `Alert.svelte` component.
1. Add `lang="ts"` into your `Alert.svelte` component's `<script>` tag. You'll see some warnings in the output of the `check` script:
```bash
npm run check -- --watch
```
```
> svelte-check "--watch"
./svelte-todo-typescript
Getting Svelte diagnostics...
====================================
./svelte-todo-typescript/src/components/Alert.svelte:8:7
Warn: Variable 'visible' implicitly has an 'any' type, but a better type may be inferred from usage. (ts)
let visible
./svelte-todo-typescript/src/components/Alert.svelte:9:7
Warn: Variable 'timeout' implicitly has an 'any' type, but a better type may be inferred from usage. (ts)
let timeout
./svelte-todo-typescript/src/components/Alert.svelte:11:28
Warn: Parameter 'message' implicitly has an 'any' type, but a better type may be inferred from usage. (ts)
Change = (message, ms) => {
./svelte-todo-typescript/src/components/Alert.svelte:11:37
Warn: Parameter 'ms' implicitly has an 'any' type, but a better type may be inferred from usage. (ts)
(message, ms) => {
```
2. You can fix these by specifying the corresponding types, like so:
```ts
export let ms = 3000
let visible: boolean
let timeout: number
const onMessageChange = (message: string, ms: number) => {
clearTimeout(timeout)
if (!message) { // hide Alert if message is empty
```
**Note:** There's no need to specify the `ms` type with `export let ms:number = 3000`, because TypeScript is already inferring it from its default value.
### MoreActions.svelte
Now we'll do the same for the `MoreActions.svelte` component.
1. Add the `lang='ts'` attribute, like before. TypeScript will warn us about the `todos` prop and the `t` variable in the call to `todos.filter((t) =>...)`.
```
Warn: Variable 'todos' implicitly has an 'any' type, but a better type may be inferred from usage. (ts)
export let todos
Warn: Parameter 't' implicitly has an 'any' type, but a better type may be inferred from usage. (ts)
$: completedTodos = todos.filter((t) => t.completed).length
```
2. We will use the `TodoType` we already defined to tell TypeScript that `todos` is a `TodoType` array. Replace the `export let todos` line with the following:
```ts
import type { TodoType } from "../types/todo.type";
export let todos: TodoType[];
```
Notice that now TypeScript can infer that the `t` variable in `todos.filter((t) => t.completed)` is of type `TodoType`. Nevertheless, if we think it makes our code easier to read, we could specify it like this:
```ts
$: completedTodos = todos.filter((t: TodoType) => t.completed).length;
```
Most of the time, TypeScript will be able to correctly infer the reactive variable type, but sometimes you might get an "implicitly has an 'any' type" error when working with reactive assignments. In those cases you can declare the typed variable in a different statement, like this:
```ts
let completedTodos: number;
$: completedTodos = todos.filter((t: TodoType) => t.completed).length;
```
You can't specify the type in the reactive assignment itself. The statement `$: completedTodos: number = todos.filter[...]` is invalid. For more information, read How do I type reactive assignments? / I get an "implicitly has type 'any' error".
### FilterButton.svelte
Now we'll take care of the `FilterButton` component.
1. Add the `lang='ts'` attribute to the `<script>` tag, as usual. You'll notice there are no warnings β TypeScript infers the type of the filter variable from the default value. But we know that there are only three valid values for the filter: all, active, and completed. So we can let TypeScript know about them by creating an enum Filter.
2. Create a `filter.enum.ts` file in the `types` folder.
3. Give it the following contents:
```ts
export enum Filter {
ALL = "all",
ACTIVE = "active",
COMPLETED = "completed",
}
```
4. Now we will use this from the `FilterButton` component. Replace the content of the `FilterButton.svelte` file with the following:
```svelte
<!-- components/FilterButton.svelte -->
<script lang="ts">
import { Filter } from "../types/filter.enum";
export let filter: Filter = Filter.ALL;
</script>
<div class="filters btn-group stack-exception">
<button class="btn toggle-btn" class:btn\_\_primary={filter === Filter.ALL} aria-pressed={filter === Filter.ALL} on:click={()=> filter = Filter.ALL} >
<span class="visually-hidden">Show</span>
<span>All</span>
<span class="visually-hidden">tasks</span>
</button>
<button class="btn toggle-btn" class:btn\_\_primary={filter === Filter.ACTIVE} aria-pressed={filter === Filter.ACTIVE} on:click={()=> filter = Filter.ACTIVE} >
<span class="visually-hidden">Show</span>
<span>Active</span>
<span class="visually-hidden">tasks</span>
</button>
<button class="btn toggle-btn" class:btn\_\_primary={filter === Filter.COMPLETED} aria-pressed={filter === Filter.COMPLETED} on:click={()=> filter = Filter.COMPLETED} >
<span class="visually-hidden">Show</span>
<span>Completed</span>
<span class="visually-hidden">tasks</span>
</button>
</div>
```
Here we are just importing the `Filter` enum and using it instead of the string values we used previously.
### Todos.svelte
We will also use the `Filter` enum in the `Todos.svelte` component.
1. First, add the `lang='ts'` attribute to it, as before.
2. Next, import the `Filter` enum. Add the following `import` statement below your existing ones:
```js
import { Filter } from "../types/filter.enum";
```
3. Now we will use it whenever we reference the current filter. Replace your two filter-related blocks with the following:
```ts
let filter: Filter = Filter.ALL;
const filterTodos = (filter: Filter, todos) =>
filter === Filter.ACTIVE
? todos.filter((t) => !t.completed)
: filter === Filter.COMPLETED
? todos.filter((t) => t.completed)
: todos;
$: {
if (filter === Filter.ALL) {
$alert = "Browsing all todos";
} else if (filter === Filter.ACTIVE) {
$alert = "Browsing active todos";
} else if (filter === Filter.COMPLETED) {
$alert = "Browsing completed todos";
}
}
```
4. `check` will still give us some warnings from `Todos.svelte`. Let's fix them.
Start by importing the `TodoType` and telling TypeScript that our `todos` variable is an array of `TodoType`. Replace `export let todos = []` with the following two lines:
```ts
import type { TodoType } from "../types/todo.type";
export let todos: TodoType[] = [];
```
5. Next we'll specify all the missing types. The variable `todosStatus`, which we used to programmatically access the methods exposed by the `TodosStatus` component, is of type `TodosStatus`. And each `todo` will be of type `TodoType`.
Update your `<script>` section to look like this:
```ts
import FilterButton from "./FilterButton.svelte";
import Todo from "./Todo.svelte";
import MoreActions from "./MoreActions.svelte";
import NewTodo from "./NewTodo.svelte";
import TodosStatus from "./TodosStatus.svelte";
import { alert } from "../stores";
import { Filter } from "../types/filter.enum";
import type { TodoType } from "../types/todo.type";
export let todos: TodoType[] = [];
let todosStatus: TodosStatus; // reference to TodosStatus instance
$: newTodoId =
todos.length > 0 ? Math.max(...todos.map((t) => t.id)) + 1 : 1;
function addTodo(name: string) {
todos = [...todos, { id: newTodoId, name, completed: false }];
$alert = `Todo '${name}' has been added`;
}
function removeTodo(todo: TodoType) {
todos = todos.filter((t) => t.id !== todo.id);
todosStatus.focus(); // give focus to status heading
$alert = `Todo '${todo.name}' has been deleted`;
}
function updateTodo(todo: TodoType) {
const i = todos.findIndex((t) => t.id === todo.id);
if (todos[i].name !== todo.name)
$alert = `todo '${todos[i].name}' has been renamed to '${todo.name}'`;
if (todos[i].completed !== todo.completed)
$alert = `todo '${todos[i].name}' marked as ${
todo.completed ? "completed" : "active"
}`;
todos[i] = { ...todos[i], ...todo };
}
let filter: Filter = Filter.ALL;
const filterTodos = (filter: Filter, todos: TodoType[]) =>
filter === Filter.ACTIVE
? todos.filter((t) => !t.completed)
: filter === Filter.COMPLETED
? todos.filter((t) => t.completed)
: todos;
$: {
if (filter === Filter.ALL) {
$alert = "Browsing all todos";
} else if (filter === Filter.ACTIVE) {
$alert = "Browsing active todos";
} else if (filter === Filter.COMPLETED) {
$alert = "Browsing completed todos";
}
}
const checkAllTodos = (completed: boolean) => {
todos = todos.map((t) => ({ ...t, completed }));
$alert = `${completed ? "Checked" : "Unchecked"} ${todos.length} todos`;
};
const removeCompletedTodos = () => {
$alert = `Removed ${todos.filter((t) => t.completed).length} todos`;
todos = todos.filter((t) => !t.completed);
};
```
### TodosStatus.svelte
We are encountering the following errors related to passing `todos` to the `TodosStatus.svelte` (and `Todo.svelte`) components:
```
./src/components/Todos.svelte:70:39
Error: Type 'TodoType[]' is not assignable to type 'undefined'. (ts)
<TodosStatus bind:this={todosStatus} {todos} />
./src/components/Todos.svelte:76:12
Error: Type 'TodoType' is not assignable to type 'undefined'. (ts)
<Todo {todo}
```
This is because the `todos` prop in the `TodosStatus` component has no default value, so TypeScript has inferred it to be of type `undefined`, which is not compatible with an array of `TodoType`. The same thing is happening with our Todo component.
Let's fix it.
1. Open the file `TodosStatus.svelte` and add the `lang='ts'` attribute.
2. Then import the `TodoType` and declare the `todos` prop as an array of `TodoType`. Replace the first line of the `<script>` section with the following:
```ts
import type { TodoType } from "../types/todo.type";
export let todos: TodoType[];
```
3. We will also specify the `headingEl`, which we used to bind to the heading tag, as an `HTMLElement`. Update the `let headingEl` line with the following:
```ts
let headingEl: HTMLElement;
```
4. Finally, you'll notice the following error reported, related to where we set the `tabindex` attribute. That's because TypeScript is type checking the `<h2>` element and expects `tabindex` to be of type `number`.
![Tabindex hint inside VS Code, tabindex expects a type of number, not string](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript/10-vscode-tabindex-hint.png)
To fix it, replace `tabindex="-1"` with `tabindex={-1}`, like this:
```svelte
<h2 id="list-heading" bind:this="{headingEl}" tabindex="{-1}">
{completedTodos} out of {totalTodos} items completed
</h2>
```
This way TypeScript can prevent us from incorrectly assigning it to a string variable.
### NewTodo.svelte
Next we will take care of `NewTodo.svelte`.
1. As usual, add the `lang='ts'` attribute.
2. The warning will indicate that we have to specify a type for the `nameEl` variable. Set its type to `HTMLElement` like this:
```ts
let nameEl: HTMLElement; // reference to the name input DOM node
```
3. Last for this file, we need to specify the correct type for our `autofocus` variable. Update its definition like this:
```ts
export let autofocus: boolean = false;
```
### Todo.svelte
Now the only warnings that `npm run check` emits are triggered by calling the `Todo.svelte` component. Let's fix them.
1. Open the `Todo.svelte` file, and add the `lang='ts'` attribute.
2. Let's import the `TodoType`, and set the type of the `todo` prop. Replace the `export let todo` line with the following:
```ts
import type { TodoType } from "../types/todo.type";
export let todo: TodoType;
```
3. The first warning we get is TypeScript telling us to define the type of the `update()` function's `updatedTodo` variable. This can be a little tricky because `updatedTodo` contains only the attributes of the `todo` that have been updated. That means it's not a complete `todo` β it only has a subset of a `todo`'s properties.
For these kinds of cases, TypeScript provides several utility types to make it easier to apply these common transformations. What we need right now is the `Partial<T>` utility, which allows us to represent all subsets of a given type. The partial utility returns a new type based on the type `T`, where every property of `T` is optional.
We'll use it in the `update()` function β update yours like so:
```ts
function update(updatedTodo: Partial<TodoType>) {
todo = { ...todo, ...updatedTodo }; // applies modifications to todo
dispatch("update", todo); // emit update event
}
```
With this we are telling TypeScript that the `updatedTodo` variable will hold a subset of the `TodoType` properties.
4. Now svelte-check tells us that we have to define the type of our action function parameters:
```bash
./07-next-steps/src/components/Todo.svelte:45:24
Warn: Parameter 'node' implicitly has an 'any' type, but a better type may be inferred from usage. (ts)
const focusOnInit = (node) => node && typeof node.focus === 'function' && node.focus()
./07-next-steps/src/components/Todo.svelte:47:28
Warn: Parameter 'node' implicitly has an 'any' type, but a better type may be inferred from usage. (ts)
const focusEditButton = (node) => editButtonPressed && node.focus()
```
We just have to define the node variable to be of type `HTMLElement`. In the two lines indicated above, replace the first instance of `node` with `node: HTMLElement`.
### actions.js
Next we'll take care of the `actions.js` file.
1. Rename it to `actions.ts` and add the type of the node parameter. It should end up looking like this:
```ts
// actions.ts
export function selectOnFocus(node: HTMLInputElement) {
if (node && typeof node.select === "function") {
// make sure node is defined and has a select() method
const onFocus = () => node.select(); // event handler
node.addEventListener("focus", onFocus); // when node gets focus call onFocus()
return {
destroy: () => node.removeEventListener("focus", onFocus), // this will be executed when the node is removed from the DOM
};
}
}
```
2. Now update `Todo.svelte` and `NewTodo.svelte` where we import the actions file. Remember that imports in TypeScript don't include the file extension. In each case it should end up like this:
```js
import { selectOnFocus } from "../actions";
```
### Migrating the stores to TypeScript
Now we have to migrate the `stores.js` and `localStore.js` files to TypeScript.
Tip: the script `npm run check`, which uses the `svelte-check` tool, will only check our application's `.svelte` files. If you want to also check the `.ts` files, you can run `npm run check && npx tsc --noemit`, which tells the TypeScript compiler to check for errors without generating the `.js` output files. You could even add a script to your `package.json` file that runs that command.
We'll start with `stores.js`.
1. Rename the file to `stores.ts`.
2. Set the type of our `initialTodos` array to `TodoType[]`. This is how the contents will end up:
```ts
// stores.ts
import { writable } from "svelte/store";
import { localStore } from "./localStore.js";
import type { TodoType } from "./types/todo.type";
export const alert = writable("Welcome to the To-Do list app!");
const initialTodos: TodoType[] = [
{ id: 1, name: "Visit MDN web docs", completed: true },
{ id: 2, name: "Complete the Svelte Tutorial", completed: false },
];
export const todos = localStore("mdn-svelte-todo", initialTodos);
```
3. Remember to update the `import` statements in `App.svelte`, `Alert.svelte`, and `Todos.svelte`. Just remove the `.js` extension, like this:
```js
import { todos } from "../stores";
```
Now onto `localStore.js`.
Update the `import` statement in `stores.ts` like so:
```js
import { localStore } from "./localStore";
```
1. Start by renaming the file to `localStore.ts`.
2. TypeScript is telling us to specify the type of the `key`, `initial`, and `value` variables. The first one is easy: the key of our local web storage should be a string.
But `initial` and `value` should be any object that could be converted to a valid JSON string with the `JSON.stringify` method, meaning any JavaScript object with a couple limitations: for example, `undefined`, functions, and symbols are not valid JSON values.
So we'll create the type `JsonValue` to specify these conditions.
Create the file `json.type.ts` in the `types` folder.
3. Give it the following content:
```ts
export type JsonValue =
| string
| number
| boolean
| null
| JsonValue[]
| { [key: string]: JsonValue };
```
The `|` operator lets us declare variables that could store values of two or more types. A `JsonValue` could be a string, a number, a boolean, and so on. In this case we are also making use of recursive types to specify that a `JsonValue` can have an array of `JsonValue` and also an object with properties of type `JsonValue`.
4. We will import our `JsonValue` type and use it accordingly. Update your `localStore.ts` file like this:
```ts
// localStore.ts
import { writable } from "svelte/store";
import type { JsonValue } from "./types/json.type";
export const localStore = (key: string, initial: JsonValue) => {
// receives the key of the local storage and an initial value
const toString = (value: JsonValue) => JSON.stringify(value, null, 2); // helper function
const toObj = JSON.parse; // helper function
if (localStorage.getItem(key) === null) {
// item not present in local storage
localStorage.setItem(key, toString(initial)); // initialize local storage with initial value
}
const saved = toObj(localStorage.getItem(key)); // convert to object
const { subscribe, set, update } = writable(saved); // create the underlying writable store
return {
subscribe,
set: (value: JsonValue) => {
localStorage.setItem(key, toString(value)); // save also to local storage as a string
return set(value);
},
update,
};
};
```
Now if we try to create a `localStore` with something that cannot be converted to JSON via `JSON.stringify()`, for example an object with a function as a property, VS Code/`validate` will complain about it:
![VS Code showing an error with using our store β it fails when trying to set a local storage value to something incompatible with JSON stringify](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript/11-vscode-invalid-store.png)
And best of all, it will even work with the `$store` auto-subscription syntax. If we try to save an invalid value to our `todos` store using the `$store` syntax, like this:
```svelte
<!-- App.svelte -->
<script lang="ts">
import Todos from "./components/Todos.svelte";
import Alert from "./components/Alert.svelte";
import { todos } from "./stores";
// this is invalid, the content cannot be converted to JSON using JSON.stringify
$todos = { handler: () => {} };
</script>
```
The check script will report the following error:
```bash
> npm run check
Getting Svelte diagnostics...
====================================
./svelte-todo-typescript/src/App.svelte:8:12
Error: Argument of type '{ handler: () => void; }' is not assignable to parameter of type 'JsonValue'.
Types of property 'handler' are incompatible.
Type '() => void' is not assignable to type 'JsonValue'.
Type '() => void' is not assignable to type '{ [key: string]: JsonValue; }'.
Index signature is missing in type '() => void'. (ts)
$todos = { handler: () => {} }
```
This is another example of how specifying types can make our code more robust and help us catch more bugs before they get into production.
And that's it. We've converted our whole application to use TypeScript.
Bulletproofing our stores with Generics
---------------------------------------
Our stores have already been ported to TypeScript, but we can do better. We shouldn't need to store any kind of value β we know that the alert store should contain string messages, and the to-dos store should contain an array of `TodoType`, etc. We can let TypeScript enforce this using TypeScript Generics. Let's find out more.
### Understanding TypeScript generics
Generics allow us to create reusable code components that work with a variety of types instead of a single type. They can be applied to interfaces, classes, and functions. Generic types are passed as parameters using a special syntax: they are specified between angle brackets, and by convention are denoted with an upper-cased single char letter. Generic types allows us to capture the types provided by the user to be used later.
Let's see a quick example, a simple `Stack` class that lets us `push` and `pop` elements, like this:
```ts
export class Stack {
private elements = [];
push = (element) => this.elements.push(element);
pop() {
if (this.elements.length === 0) throw new Error("The stack is empty!");
return this.elements.pop();
}
}
```
In this case `elements` is an array of type `any`, and accordingly the `push()` and `pop()` methods both receive and return a variable of type `any`. So it's perfectly valid to do something like the following:
```js
const anyStack = new Stack();
anyStack.push(1);
anyStack.push("hello");
```
But what if we wanted to have a `Stack` that would only work with type `string`? We could do the following:
```ts
export class StringStack {
private elements: string[] = [];
push = (element: string) => this.elements.push(element);
pop(): string {
if (this.elements.length === 0) throw new Error("The stack is empty!");
return this.elements.pop();
}
}
```
That would work. But if we wanted to work with numbers, we would then have to duplicate our code and create a `NumberStack` class. And how could we handle a stack of types we don't know yet, and that should be defined by the consumer?
To solve all these problems, we can use generics.
This is our `Stack` class reimplemented using generics:
```ts
export class Stack<T> {
private elements: T[] = [];
push = (element: T): number => this.elements.push(element);
pop(): T {
if (this.elements.length === 0) throw new Error("The stack is empty!");
return this.elements.pop();
}
}
```
We define a generic type `T` and then use it like we would normally use a specific type. Now elements is an array of type `T`, and `push()` and `pop()` both receive and return a variable of type `T`.
This is how we would use our generic `Stack`:
```ts
const numberStack = new Stack<number>();
numberStack.push(1);
```
Now TypeScript knows that our stack can only accept numbers, and will issue an error if we try to push anything else:
![Argument of type hello is not assignable to parameter of type number](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript/12-vscode-generic-stack-error.png)
TypeScript can also infer generic types by its usage. Generics also support default values and constraints.
Generics are a powerful feature that allows our code to abstract away from the specific types being used, making it more reusable and generic without giving up on type safety. To learn more about it, check out the TypeScript Introduction to Generics.
### Using Svelte stores with generics
Svelte stores support generics out of the box. And, because of generic type inference, we can take advantage of it without even touching our code.
If you open the file `Todos.svelte` and assign a `number` type to our `$alert` store, you'll get the following error:
![Todo Type object property complete should be completed](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript/13-vscode-generic-alert-error.png)
That's because when we defined our alert store in the `stores.ts` file with:
```js
export const alert = writable("Welcome to the To-Do list app!");
```
TypeScript inferred the generic type to be `string`. If we wanted to be explicit about it, we could do the following:
```ts
export const alert = writable<string>("Welcome to the To-Do list app!");
```
Now we'll make our `localStore` store support generics. Remember that we defined the `JsonValue` type to prevent the usage of our `localStore` store with values that cannot be persisted using `JSON.stringify()`. Now we want the consumers of `localStore` to be able to specify the type of data to persist, but instead of working with any type, they should comply with the `JsonValue` type. We'll specify that with a Generic constraint, like this:
```ts
export const localStore = <T extends JsonValue>(key: string, initial: T)
```
We define a generic type `T` and specify that it must be compatible with the `JsonValue` type. Then we'll use the `T` type appropriately.
Our `localStore.ts` file will end up like this β try the new code now in your version:
```ts
// localStore.ts
import { writable } from "svelte/store";
import type { JsonValue } from "./types/json.type";
export const localStore = <T extends JsonValue>(key: string, initial: T) => {
// receives the key of the local storage and an initial value
const toString = (value: T) => JSON.stringify(value, null, 2); // helper function
const toObj = JSON.parse; // helper function
if (localStorage.getItem(key) === null) {
// item not present in local storage
localStorage.setItem(key, toString(initial)); // initialize local storage with initial value
}
const saved = toObj(localStorage.getItem(key)); // convert to object
const { subscribe, set, update } = writable<T>(saved); // create the underlying writable store
return {
subscribe,
set: (value: T) => {
localStorage.setItem(key, toString(value)); // save also to local storage as a string
return set(value);
},
update,
};
};
```
And thanks to generic type inference, TypeScript already knows that our `$todos` store should contain an array of `TodoType`:
![Todo Type object property complete should be completed](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript/14-vscode-generic-localstore-error.png)
Once again, if we wanted to be explicit about it, we could do so in the `stores.ts` file like this:
```ts
const initialTodos: TodoType[] = [
{ id: 1, name: "Visit MDN web docs", completed: true },
{ id: 2, name: "Complete the Svelte Tutorial", completed: false },
];
export const todos = localStore<TodoType[]>("mdn-svelte-todo", initialTodos);
```
That will do for our brief tour of TypeScript Generics.
The code so far
---------------
### Git
To see the state of the code as it should be at the end of this article, access your copy of our repo like this:
```bash
cd mdn-svelte-tutorial/08-next-steps
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/08-next-steps
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
As we said earlier, TypeScript is not yet available in the REPL.
Summary
-------
In this article we took our to-do list application and ported it to TypeScript.
We first learnt about TypeScript and what advantages it can bring us. Then we saw how to create a new Svelte project with TypeScript support. We also saw how to convert an existing Svelte project to use TypeScript β our to-do list app.
We saw how to work with Visual Studio Code and the Svelte extension to get features like type checking and auto-completion. We also used the `svelte-check` tool to inspect TypeScript issues from the command line.
In the next article we will learn how to compile and deploy our app to production. We will also see which resources are available online to go further with learning Svelte.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Ember interactivity: Events, classes and state - Learn web development | Ember interactivity: Events, classes and state
==============================================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
At this point we'll start adding some interactivity to our app, providing the ability to add and display new todo items. Along the way, we'll look at using events in Ember, creating component classes to contain JavaScript code to control interactive features, and setting up a service to keep track of the data state of our app.
| | |
| --- | --- |
| Prerequisites: |
At minimum, it is recommended that you are familiar with the core
HTML,
CSS, and
JavaScript languages, and
have knowledge of the
terminal/command line.
A deeper understanding of modern JavaScript features (such as classes,
modules, etc.), will be extremely beneficial, as Ember makes heavy use
of them.
|
| Objective: |
To learn how to create component classes and use events to control
interactivity, and keep track of app state using a service.
|
Adding Interactivity
--------------------
Now we've got a refactored componentized version of our todo app, lets walk through how we can add the interactivity we need to make the app functional.
When beginning to think about interactivity, it's good to declare what each component's goals and responsibilities are. In the below sections we'll do this for each component, and then walk you through how the functionality can be implemented.
Creating todos
--------------
For our card-header / todo input, we'll want to be able to submit our typed in todo task when we press the `Enter` key and have it appear in the todos list.
We want to be able to capture the text typed into the input. We do this so that our JavaScript code knows what we typed in, and we can save our todo and pass that text along to the todo list component to display.
We can capture the `keydown` event via the on modifier, which is just Ember syntactic sugar around `addEventListener` and `removeEventListener` (see this explanation if needed).
Add the new line shown below to your `header.hbs` file:
```hbs
<input
class='new-todo'
aria-label='What needs to be done?'
placeholder='What needs to be done?'
autofocus
{{on 'keydown' this.onKeyDown}}
>
```
This new attribute is inside double curly braces, which tells you it is part of Ember's dynamic templating syntax. The first argument passed to `on` is the type of event to respond to (`keydown`), and the last argument is the event handler β the code that will run in response to the `keydown` event firing. As you may expect from dealing with vanilla JavaScript objects, the `this` keyword refers to the "context" or "scope" of the component. One component's `this` will be different from another component's `this`.
We can define what is available inside `this` by generating a component class to go along with your component. This is a vanilla JavaScript class and has no special meaning to Ember, other than *extending* from the `Component` super-class.
To create a header class to go with your header component, type this in to your terminal:
```bash
ember generate component-class header
```
This will create the following empty class file β `todomvc/app/components/header.js`:
```js
import Component from "@glimmer/component";
export default class HeaderComponent extends Component {}
```
Inside this file we will implement the event handler code. Update the content to the following:
```js
import Component from "@glimmer/component";
import { action } from "@ember/object";
export default class HeaderComponent extends Component {
@action
onKeyDown({ target, key }) {
let text = target.value.trim();
let hasValue = Boolean(text);
if (key === "Enter" && hasValue) {
alert(text);
target.value = "";
}
}
}
```
The `@action` decorator is the only Ember-specific code here (aside from extending from the `Component` superclass, and the Ember-specific items we are importing using JavaScript module syntax) β the rest of the file is vanilla JavaScript, and would work in any application. The `@action` decorator declares that the function is an "action", meaning it's a type of function that will be invoked from an event that occurred in the template. `@action` also binds the `this` of the function to the class instance.
**Note:** A decorator is basically a wrapper function, which wraps and calls other functions or properties, providing additional functionality along the way. For example, the `@tracked` decorator (see slightly later on) runs code it is applied to, but additionally tracks it and automatically updates the app when values change. Read JavaScript Decorators: What They Are and When to Use Them for more general information on decorators.
Coming back to our browser tab with the app running, we can type whatever we want, and when we hit `Enter` we'll be greeted with an alert message telling us exactly what we typed.
![the initial placeholder state of the add function, showing the text entered into the input elements being alerted back to you.](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state/todos-hello-there-alert.png)
With the interactivity of the header input out of the way, we need a place to store todos so that other components can access them.
Storing Todos with a service
----------------------------
Ember has built-in application-level **state** management that we can use to manage the storage of our todos and allow each of our components to access data from that application-level state. Ember calls these constructs Services, and they live for the entire lifetime of the page (a page refresh will clear them; persisting the data for longer is beyond the scope of this tutorial).
Run this terminal command to generate a service for us to store our todo-list data in:
```bash
ember generate service todo-data
```
This should give you a terminal output like so:
```
installing service
create app/services/todo-data.js
installing service-test
create tests/unit/services/todo-data-test.js
```
This creates a `todo-data.js` file inside the `todomvc/app/services` directory to contain our service, which initially contains an import statement and an empty class:
```js
import Service from "@ember/service";
export default class TodoDataService extends Service {}
```
First of all, we want to define *what a todo is*. We know that we want to track both the text of a todo, and whether or not it is completed.
Add the following `import` statement below the existing one:
```js
import { tracked } from "@glimmer/tracking";
```
Now add the following class below the previous line you added:
```js
class Todo {
@tracked text = "";
@tracked isCompleted = false;
constructor(text) {
this.text = text;
}
}
```
This class represents a todo β it contains a `@tracked text` property containing the text of the todo, and a `@tracked isCompleted` property that specifies whether the todo has been completed or not. When instantiated, a `Todo` object will have an initial `text` value equal to the text given to it when created (see below), and an `isCompleted` value of `false`. The only Ember-specific part of this class is the `@tracked` decorator β this hooks in to the reactivity system and allows Ember to update what you're seeing in your app automatically if the tracked properties change. More information on tracked can be found here.
Now it's time to add to the body of the service.
First add another `import` statement below the previous one, to make actions available inside the service:
```js
import { action } from "@ember/object";
```
Update the existing `export default class TodoDataService extends Service { }` block as follows:
```js
export default class TodoDataService extends Service {
@tracked todos = [];
@action
add(text) {
let newTodo = new Todo(text);
this.todos.pushObject(newTodo);
}
}
```
Here, the `todos` property on the service will maintain our list of todos contained inside an array, and we'll mark it with `@tracked`, because when the value of `todos` is updated we want the UI to update as well.
And just like before, the `add()` function that will be called from the template gets annotated with the `@action` decorator to bind it to the class instance.
While this may look like familiar JavaScript, you may notice that we're calling the method `pushObject()` on our `todos` array.
This is because Ember extends JavaScript's Array prototype by default, giving us convenient methods to ensure Ember's tracking system knows about these changes.
There are dozens of these methods, including `pushObjects()`, `insertAt()`, or `popObject()`, which can be used with any type (not just Objects).
Ember's ArrayProxy also gives us more handy methods, like `isAny()`, `findBy()`, and `filterBy()` to make life easier.
Using the service from our header component
-------------------------------------------
Now that we've defined a way to add todos, we can interact with this service from the `header.js` input component to actually start adding them.
First of all, the service needs to be injected into the template via the `@inject` decorator, which we'll rename to `@service` for semantic clarity. To do this, add the following `import` line to `header.js`, beneath the two existing `import` lines:
```js
import { inject as service } from "@ember/service";
```
With this import in place, we can now make the `todo-data` service available inside the `HeaderComponent` class via the `todos` object, using the `@service` decorator. Add the following line just below the opening `exportβ¦` line:
```js
@service('todo-data') todos;
```
Now the placeholder `alert(text);` line can be replaced with a call to our new `add()` function. Replace it with the following:
```js
this.todos.add(text);
```
If we try this out in the todo app in our browser (`npm start`, go to `localhost:4200`), it will look like nothing happens after hitting the `Enter` key (although the fact that the app builds without any errors is a good sign). Using the Ember Inspector however, we can see that our todo was added:
![The app being shown in the Ember inspector, to prove that added todos are being stored by the service, even if they are not being displayed in the UI yet](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state/todos-in-ember-inspector.gif)
Displaying our todos
--------------------
Now that we know that we can create todos, there needs to be a way to swap out our static "Buy Movie Tickets" todos with the todos we're actually creating. In the `TodoList` component, we'll want to get the todos out of the service, and render a `Todo` component for each todo.
In order to retrieve the todos from the service, our `TodoList` component first needs a backing component class to contain this functionality. Press `Ctrl` + `C` to stop the development server, and enter the following terminal command:
```bash
ember generate component-class todo-list
```
This generates the new component class `todomvc/app/components/todo-list.js`.
Populate this file with the following code, which exposes the `todo-data` service, via the `todos` property, to our template. This makes it accessible via `this.todos` inside both the class and the template:
```js
import Component from "@glimmer/component";
import { inject as service } from "@ember/service";
export default class TodoListComponent extends Component {
@service("todo-data") todos;
}
```
One issue here is that our service is called `todos`, but the list of todos is also called `todos`, so currently we would access the data using `this.todos.todos`. This is not intuitive, so we'll add a getter to the `todos` service called `all`, which will represent all todos.
To do this, go back to your `todo-data.js` file and add the following below the `@tracked todos = [];` line:
```js
get all() {
return this.todos;
}
```
Now we can access the data using `this.todos.all`, which is much more intuitive. To put this in action, go to your `todo-list.hbs` component, and replace the static component calls:
```hbs
<Todo />
<Todo />
```
With a dynamic `#each` block (which is basically syntactic sugar over the top of JavaScript's `forEach()`) that creates a `<Todo />` component for each todo available in the list of todos returned by the service's `all()` getter:
```hbs
{{#each this.todos.all as |todo|}}
<Todo @todo={{todo}} />
{{/each}}
```
Another way to look at this:
* `this` β the rendering context / component instance.
* `todos` β a property on `this`, which we defined in the `todo-list.js` component using `@service('todo-data') todos;`. This is a reference to the `todo-data` service, allowing us to interact with the service instance directly.
* `all` β a getter on the `todo-data` service that returns all the todos.
Try starting the server again and navigating to our app, and you'll find that it works! Well, sort of. Whenever you enter a new Todo item, a new list item appears below the text input, but unfortunately it always says "Buy Movie Tickets".
This is because the text label inside each list item is hardcoded to that text, as seen in `todo.hbs`:
```hbs
<label>Buy Movie Tickets</label>
```
Update this line to use the Argument `@todo` β which will represent the Todo that we passed in to this component when it was invoked in `todo-list.hbs`, in the line `<Todo @todo={{todo}} />`:
```hbs
<label>{{@todo.text}}</label>
```
OK, try it again. You should find that now the text submitted in the `<input>` is properly reflected in the UI:
![The app being shown in its final state of this article, with entered todo items being shown in the UI](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state/todos-being-appended-with-correct-text.gif)
Summary
-------
OK, so that's great progress for now. We can now add todo items to our app, and the state of the data is tracked using our service. Next we'll move on to getting our footer functionality working, including the todo counter, and look at conditional rendering, including correctly styling todos when they've been checked. We'll also wire up our "Clear completed" button.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Ember resources and troubleshooting - Learn web development | Ember resources and troubleshooting
===================================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
Our final Ember article provides you with a list of resources that you can use to go further in your learning, plus some useful troubleshooting and other information.
| | |
| --- | --- |
| Prerequisites: |
At minimum, it is recommended that you are familiar with the core
HTML,
CSS, and
JavaScript languages, and
have knowledge of the
terminal/command line.
A deeper understanding of modern JavaScript features (such as classes,
modules, etc.), will be extremely beneficial, as Ember makes heavy use
of them.
|
| Objective: | To provide further resource links and troubleshooting information. |
Further resources
-----------------
* Ember.JS Guides
+ Tutorial: Super Rentals
* Ember.JS API Documentation
* Ember.JS Discord Server β a forum/chat server where you can meet the Ember community, ask for help, and help others!
General troubleshooting, gotchas, and misconceptions
----------------------------------------------------
This is nowhere near an extensive list, but it is a list of things that came up around the time of writing (latest update, May 2020).
### How do I debug what's going on in the framework?
For *framework-specific* things, there is the ember-inspector add-on, which allows inspection of:
* Routes & Controllers
* Components
* Services
* Promises
* Data (i.e., from a remote API β from ember-data, by default)
* Deprecation Information
* Render Performance
For general JavaScript debugging, check out our guides on JavaScript Debugging
as well as interacting with the browser's other debugging tools. In any default Ember
project, there will be two main JavaScript files, `vendor.js` and `{app-name}.js`. Both of
these files are generated with sourcemaps, so when you open the `vendor.js` or `{app-name}.js` to search for relevant code, when a debugger is placed, the sourcemap will be loaded and the breakpoint will be placed in the pre-transpiled code for easier correlation to your project code.
For more information on sourcemaps, why they're needed, and what the ember-cli does with them, see the Advanced Use: Asset Compilation guide. Note that sourcemaps are enabled by default.
### `ember-data` comes pre-installed; do I need it?
Not at all. While `ember-data` solves *the most common problems* that any app dealing with
data will run in to, it is possible to roll your own front-end data client. A common
alternative is to any fully-featured front-end data client is The Fetch API.
Using the design patterns provided by the framework, a `Route` using `fetch()` would look something like this:
```js
import Route from "@ember/routing/route";
export default class MyRoute extends Route {
async model() {
let response = await fetch("some/url/to/json/data");
let json = await response.json();
return {
data: json,
};
}
}
```
See more information on specifying the `Route`'s model here.
### Why can't I just use JavaScript?
This is the *most* common question Ember folks hear from people who have previous
experience with React. While it is technically possible to use JSX, or any
other form of DOM creation, there has yet to be anything as robust as Ember's
templating system. The intentional minimalism forces certain decisions, and allows
for more consistent code, while keeping the template more structural rather than having them filled with bespoke logic.
See also: ReactiveConf 2017: Secrets of the Glimmer VM
### What is the state of the `mut` helper?
`mut` was not covered in this tutorial and is really baggage from a transitional time when Ember was moving from two-way bound data to the more common and easier-to-reason-about one-way bound data flow. It could be thought of as a build-time transform that wraps its argument with a setter function.
More concretely, using `mut` allows for template-only settings functions to be declared:
```hbs
<Checkbox
@value={{this.someData}}
@onToggle={{fn (mut this.someData) (not this.someData)}}
/>
```
Whereas, without `mut`, a component class would be needed:
```js
import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";
export default class Example extends Component {
@tracked someData = false;
@action
setData(newValue) {
this.someData = newValue;
}
}
```
Which would then be called in the template like so:
```hbs
<Checkbox @data={{this.someData}} @onChange={{this.setData}} />
```
Due to the conciseness of using `mut`, it may be desirable to reach for it. However, `mut` has unnatural semantics and has caused much confusion over the term of its existence.
There have been a couple of new ideas put together into the form of addons that use the public APIs, `ember-set-helper` and `ember-box`. Both of these try to solve the problems of `mut`
by introducing more obvious / "less magic" concepts, avoiding build-time transforms and
implicit Glimmer VM behavior.
With `ember-set-helper`:
```hbs
<Checkbox @value={{this.someData}} @onToggle={{set this "someData" (not
this.someData)}} />
```
With `ember-box`:
```hbs
{{#let (box this.someData) as |someData|}}
<Checkbox
@value={{unwrap someData}}
@onToggle={{update someData (not this.someData)}}
/>
{{/let}}
```
Note that none of these solutions are particularly common among members of the community, and as a whole, people are still trying to figure out an ergonomic and simple API for setting data in a template-only context, without backing JS.
### What is the purpose of Controllers?
Controllers are Singletons, which may help manage the rendering context of the
active route. On the surface, they function much the same as the backing JavaScript of a Component. Controllers are (as of January 2020), the only way to manage URL Query Params.
Ideally, controllers should be fairly light in their responsibilities, delegating to Components
and Services where possible.
### What is the purpose of Routes?
A Route represents part of the URL when a user navigates from place to place in the app.
A Route has only a couple responsibilities:
* Load the *minimally required data* to render the route (or view-sub-tree).
* Gate access to the route and redirect if needed.
* Handle loading and error states from the minimally required data.
A Route only has 3 lifecycle hooks, all of which are optional:
* `beforeModel` β gate access to the route.
* `model` β where data is loaded.
* `afterModel` β verify access.
Last, a Route has the ability to handle common events resulting from configuring the `model`:
* `loading` β what to do when the `model` hook is loading.
* `error` β what to do when an error is thrown from `model`.
Both `loading` and `error` can render default templates as well as customized templates defined elsewhere in the application, unifying loading/error states.
More information on everything a Route can do is found in the API documentation.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Getting started with Angular - Learn web development | Getting started with Angular
============================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
It is now time to look at Google's Angular framework, another popular option that you'll come across often. In this article we look at what Angular has to offer, install the prerequisites and set up a sample app, and look at Angular's basic architecture.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
|
| Objective: |
To setup a local Angular development environment, create a starter app,
and understand the basics of how it works.
|
What is Angular?
----------------
Angular is a development platform, built on TypeScript. As a platform, Angular includes:
* A component-based framework for building scalable web applications
* A collection of well-integrated libraries that cover a wide variety of features, including routing, forms management, client-server communication, and more
* A suite of developer tools to help you develop, build, test, and update your code
When you build applications with Angular, you're taking advantage of a platform that can scale from single-developer projects to enterprise-level applications. Angular is designed to make updating as easy as possible, so you can take advantage of the latest developments with a minimum of effort. Best of all, the Angular ecosystem consists of a diverse group of over 1.7 million developers, library authors, and content creators.
Before you start exploring the Angular platform, you should know about the Angular CLI. The Angular CLI is the fastest, easiest, and recommended way to develop Angular applications. The Angular CLI makes a number of tasks easy. Here are some examples:
| | |
| --- | --- |
| `ng build` | Compiles an Angular app into an output directory. |
| `ng serve` | Builds and serves your application, rebuilding on file changes. |
| `ng generate` | Generates or modifies files based on a schematic. |
| `ng test` | Runs unit tests on a given project. |
| `ng e2e` | Builds and serves an Angular application, then runs end-to-end tests. |
You'll find the Angular CLI to be a valuable tool for building out your applications.
What you'll build
-----------------
This tutorial series guides you through building a to-do list application. Via this application you'll learn how to use Angular to manage, edit, add, delete, and filter items.
Prerequisites
-------------
To install Angular on your local system, you need the following:
* **Node.js**
Angular requires a current, active LTS, or maintenance LTS version of Node.js. For information about specific version requirements, see the `engines` key in the package.json file.
For more information on installing Node.js, see nodejs.org.
If you are unsure what version of Node.js runs on your system, run `node -v` in a terminal window.
* **npm package manager**
Angular, the Angular CLI, and Angular applications depend on npm packages for many features and functions.
To download and install npm packages, you need an npm package manager.
This guide uses the npm client command line interface, which is installed with `Node.js` by default.
To check that you have the npm client installed, run `npm -v` in a terminal window.
Set up your application
-----------------------
You can use the Angular CLI to run commands in your terminal for generating, building, testing, and deploying Angular applications.
To install the Angular CLI, run the following command in your terminal:
```bash
npm install -g @angular/cli
```
Angular CLI commands all start with `ng`, followed by what you'd like the CLI to do.
In the Desktop directory, use the following `ng new` command to create a new application called `todo`:
```bash
ng new todo --routing=false --style=css
```
The `ng new` command creates a minimal starter Angular application on your Desktop.
The additional flags, `--routing` and `--style`, define how to handle navigation and styles in the application.
This tutorial describes these features later in more detail.
If you are prompted to enforce stricter type checking, you can respond with yes.
Navigate into your new project with the following `cd` command:
```bash
cd todo
```
To run your `todo` application, use `ng serve`:
```bash
ng serve
```
When the CLI prompts you about analytics, answer `no`.
In the browser, navigate to `http://localhost:4200/` to see your new starter application.
If you change any of the source files, the application automatically reloads.
While `ng serve` is running, you might want to open a second terminal tab or window in order to run commands.
If at any point you would like to stop serving your application, press `Ctrl+c` while in the terminal.
Get familiar with your Angular application
------------------------------------------
The application source files that this tutorial focuses on are in `src/app`.
Key files that the CLI generates automatically include the following:
1. `app.module.ts`: Specifies the files that the application uses.
This file acts as a central hub for the other files in your application.
2. `app.component.ts`: Also known as the class, contains the logic for the application's main page.
3. `app.component.html`: Contains the HTML for `AppComponent`. The contents of this file are also known as the template.
The template determines the view or what you see in the browser.
4. `app.component.css`: Contains the styles for `AppComponent`. You use this file when you want to define styles that only apply to a specific component, as opposed to your application overall.
A component in Angular is made up of three main partsβthe template, styles, and the class.
For example, `app.component.ts`, `app.component.html`, and `app.component.css` together constitute the `AppComponent`.
This structure separates the logic, view, and styles so that the application is more maintainable and scalable.
In this way, you are using the best practices from the very beginning.
The Angular CLI also generates a file for component testing called `app.component.spec.ts`, but this tutorial doesn't go into testing, so you can ignore that file.
Whenever you generate a component, the CLI creates these four files in a directory with the name you specify.
The structure of an Angular application
---------------------------------------
Angular is built with TypeScript.
TypeScript is a superset of JavaScript meaning that any valid JavaScript is valid TypeScript.
TypeScript offers typing and a more concise syntax than plain JavaScript, which gives you a tool for creating more maintainable code and minimizing bugs.
Components are the building blocks of an Angular application.
A component includes a TypeScript class that has a `@Component()` decorator.
### The decorator
You use the `@Component()` decorator to specify metadata (HTML template and styles) about a class.
### The class
The class is where you put any logic your component needs.
This code can include functions, event listeners, properties, and references to services to name a few.
The class is in a file with a name such as `feature.component.ts`, where `feature` is the name of your component.
So, you could have files with names such as `header.component.ts`, `signup.component.ts`, or `feed.component.ts`.
You create a component with a `@Component()` decorator that has metadata that tells Angular where to find the HTML and CSS.
A typical component is as follows:
```js
import { Component } from "@angular/core";
@Component({
selector: "app-item",
// the following metadata specifies the location of the other parts of the component
templateUrl: "./item.component.html",
styleUrls: ["./item.component.css"],
})
export class ItemComponent {
// your code goes here
}
```
This component is called `ItemComponent`, and its selector is `app-item`.
You use a selector just like regular HTML tags by placing it within other templates.
When a selector is in a template, the browser renders the template of that component whenever an instance of the selector is encountered.
This tutorial guides you through creating two components and using one within the other.
**NOTE:** The name of the component above is `ItemComponent` which is also the name of the class. Why?
The names are the same simply because a component is nothing but a class supplemented by a TypeScript decorator.
Angular's component model offers strong encapsulation and an intuitive application structure.
Components also make your application easier to unit test and can improve the overall readability of your code.
### The HTML template
Every component has an HTML template that declares how that component renders.
You can define this template either inline or by file path.
To refer to an external HTML file, use the `templateUrl` property:
```js
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
})
export class AppComponent {
// code goes here
}
```
To write inline HTML, use the `template` property and write your HTML within backticks:
```js
@Component({
selector: "app-root",
template: `<h1>Hi!</h1>`,
})
export class AppComponent {
// code goes here
}
```
Angular extends HTML with additional syntax that lets you insert dynamic values from your component.
Angular automatically updates the rendered DOM when your component's state changes.
One use of this feature is inserting dynamic text, as shown in the following example.
```html
<h1>{{ title }}</h1>
```
The double curly braces instruct Angular to interpolate the contents within them.
The value for `title` comes from the component class:
```js
import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent {
title = "To do application";
}
```
When the application loads the component and its template, the browser sees the following:
```html
<h1>To do application</h1>
```
### Styles
A component can inherit global styles from the application's `styles.css` file and augment or override them with its own styles.
You can write component-specific styles directly in the `@Component()` decorator or specify the path to a CSS file.
To include the styles directly in the component decorator, use the `styles` property:
```js
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styles: ['h1 { color: red; }']
})
```
Typically, a component uses styles in a separate file using the `styleUrls` property:
```js
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
```
With component-specific styles, you can organize your CSS so that it is easily maintainable and portable.
Summary
-------
That's it for your first introduction to Angular. At this point you should be set up and ready to build an Angular app, and have a basic understanding of how Angular works. In the next article we'll deepen that knowledge and start to build up the structure of our to-do list application.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Ember app structure and componentization - Learn web development | Ember app structure and componentization
========================================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
In this article we'll get right on with planning out the structure of our TodoMVC Ember app, adding in the HTML for it, and then breaking that HTML structure into components.
| | |
| --- | --- |
| Prerequisites: |
At minimum, it is recommended that you are familiar with the core
HTML,
CSS, and
JavaScript languages, and
have knowledge of the
terminal/command line.
A deeper understanding of modern JavaScript features (such as classes,
modules, etc.), will be extremely beneficial, as Ember makes heavy use
of them.
|
| Objective: |
To learn how to structure an Ember app, and then break that structure
into components.
|
Planning out the layout of the TodoMVC app
------------------------------------------
In the last article we set up a new Ember project, then added and configured our CSS styles. At this point we add some HTML, planning out the structure and semantics of our TodoMVC app.
The landing page HTML of our application is defined in `app/templates/application.hbs`. This already exists, and its contents currently look like so:
```hbs
{{!-- The following component displays Ember's default welcome message. --}}
<WelcomePage />
{{!-- Feel free to remove this! --}}
{{outlet}}
```
`<WelcomePage />` is a component provided by an Ember addon that renders the default welcome page we saw in the previous article, when we first navigated to our server at `localhost:4200`.
However, we don't want this. Instead, we want it to contain the TodoMVC app structure. To start with, delete the contents of `application.hbs` and replace them with the following:
```html
<section class="todoapp">
<h1>todos</h1>
<input
class="new-todo"
aria-label="What needs to be done?"
placeholder="What needs to be done?"
autofocus />
</section>
```
**Note:** `aria-label` provides a label for assistive technology to make use of β for example, for a screen reader to read out. This is useful in such cases where we have an `<input>` being used with no corresponding HTML text that could be turned into a label.
When you save `application.hbs`, the development server you started earlier will automatically rebuild the app and refresh the browser. The rendered output should now look like this:
![todo app rendered in the browser with only the new todo input field showing](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization/todos-initial-render.png)
It doesn't take too much effort to get our HTML looking like a fully-featured to-do list app. Update the `application.hbs` file again so its content looks like this:
```html
<section class="todoapp">
<h1>todos</h1>
<input
class="new-todo"
aria-label="What needs to be done?"
placeholder="What needs to be done?"
autofocus />
<section class="main">
<input id="mark-all-complete" class="toggle-all" type="checkbox" />
<label for="mark-all-complete">Mark all as complete</label>
<ul class="todo-list">
<li>
<div class="view">
<input
aria-label="Toggle the completion of this todo"
class="toggle"
type="checkbox" />
<label>Buy Movie Tickets</label>
<button
type="button"
class="destroy"
title="Remove this todo"></button>
</div>
<input autofocus class="edit" value="Todo Text" />
</li>
<li>
<div class="view">
<input
aria-label="Toggle the completion of this todo"
class="toggle"
type="checkbox" />
<label>Go to Movie</label>
<button
type="button"
class="destroy"
title="Remove this todo"></button>
</div>
<input autofocus class="edit" value="Todo Text" />
</li>
</ul>
</section>
<footer class="footer">
<span class="todo-count"> <strong>0</strong> todos left </span>
<ul class="filters">
<li>
<a href="#">All</a>
<a href="#">Active</a>
<a href="#">Completed</a>
</li>
</ul>
<button type="button" class="clear-completed">Clear Completed</button>
</footer>
</section>
```
The rendered output should now be as follows:
![todo app rendered in the browser with new todo input field and existing todos showing, - buy movie tickets and go to movie](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization/todos-with-todo-items.png)
This looks pretty complete, but remember that this is only a static prototype. Now we need to break up our HTML code into dynamic components; later we'll turn it into a fully interactive app.
Looking at the code next to the rendered todo app, there are a number of ways we could decide how to break up the UI, but let's plan on splitting the HTML out into the following components:
![code screenshot annotated to show what parts of the code will go into which component](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization/todos-ui-component-breakdown.png)
The component groupings are as follows:
* The main input / "new-todo" (red in the image)
* The containing body of the todo list + the `mark-all-complete` button (purple in the image)
+ The `mark-all-complete button`, explicitly highlighted for reasons given below (yellow in the image)
+ Each todo is an individual component (green in the image)
* The footer (blue in the image)
Something odd to note is that the `mark-all-complete` checkbox (marked in yellow), while in the "main" section, is rendered next to the "new-todo" input. This is because the default CSS absolutely positions the checkbox + label with negative top and left values to move it next to the input, rather than it being inside the "main" section.
![todo app looked at through devtools](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization/todos-devtools-view.png)
Using the CLI to create our components for us
---------------------------------------------
So to represent our app, we want to create 4 components:
* Header
* List
* Individual Todo
* Footer
To create a component, we use the `ember generate component` command, followed by the name of the component. Let's create the header component first. To do so:
1. Stop the server running by going to the terminal and pressing `Ctrl` + `C`.
2. Enter the following command into your terminal:
```bash
ember generate component header
```
These will generate some new files, as shown in the resulting terminal output:
```
installing component
create app/components/header.hbs
skip app/components/header.js
tip to add a class, run `ember generate component-class header`
installing component-test
create tests/integration/components/header-test.js
```
`header.hbs` is the template file where we'll include the HTML structure for just that component. Later on we'll add the required dynamic functionality such as data bindings, responding to user interaction, etc.
**Note:** The `header.js` file (shown as skipped) is for connection to a backing Glimmer Component Class, which we don't need for now, as they are for adding interactivity and state manipulation. By default, `generate component` generates template-only components, because in large applications, template-only components end up being the majority of the components.
`header-test.js` is for writing automated tests to ensure that our app continues to work over time as we upgrade, add features, refactor, etc. Testing is outside the scope of this tutorial, although generally testing should be implemented as you develop, rather than after, otherwise it tends to be forgotten about. If you're curious about testing, or why you would want to have automated tests, check out the official Ember tutorial on testing.
Before we start adding any component code, let's create the scaffolding for the other components. Enter the following lines into your terminal, one by one:
```bash
ember generate component todo-list
ember generate component todo
ember generate component footer
```
You'll now see the following inside your `todomvc/app/components` directory:
![the app components directory, showing the component template files we've created](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization/todos-components-directory.png)
Now that we have all of our component structure files, we can cut and paste the HTML for each component out of the `application.hbs` file and into each of those components, and then re-write the `application.hbs` to reflect our new abstractions.
1. The `header.hbs` file should be updated to contain the following:
```html
<input
class="new-todo"
aria-label="What needs to be done?"
placeholder="What needs to be done?"
autofocus />
```
2. `todo-list.hbs` should be updated to contain this chunk of code:
```html
<section class="main">
<input id="mark-all-complete" class="toggle-all" type="checkbox" />
<label for="mark-all-complete">Mark all as complete</label>
<ul class="todo-list">
<Todo />
<Todo />
</ul>
</section>
```
**Note:** The only non-HTML in this new `todo-list.hbs` is the `<Todo />` component invocation. In Ember, a component invocation is similar to declaring an HTML element, but the first letter starts with a capital letter, and the names are written in upper camel case, as you'll see with `<TodoList />` later on. The contents of the `todo.hbs` file below will replace `<Todo />` in the rendered page as our application loads.
3. Add the following into the `todo.hbs` file:
```html
<li>
<div class="view">
<input
aria-label="Toggle the completion of this todo"
class="toggle"
type="checkbox" />
<label>Buy Movie Tickets</label>
<button type="button" class="destroy" title="Remove this todo"></button>
</div>
<input autofocus class="edit" value="Todo Text" />
</li>
```
4. `footer.hbs` should be updated to contain the following:
```html
<footer class="footer">
<span class="todo-count"> <strong>0</strong> todos left </span>
<ul class="filters">
<li>
<a href="#">All</a>
<a href="#">Active</a>
<a href="#">Completed</a>
</li>
</ul>
<button type="button" class="clear-completed">Clear Completed</button>
</footer>
```
5. Finally, the contents of `application.hbs` should be updated so that they call the appropriate components, like so:
```hbs
<section class="todoapp">
<h1>todos</h1>
<Header />
<TodoList />
<Footer />
</section>
```
6. With these changes made, run `npm start` in your terminal again, then head over to `http://localhost:4200` to ensure that the todo app still looks as it did before the refactor.
![todo app rendered in the browser with new todo input field and existing todos showing, both saying buy movie tickets](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization/todos-components-render.png)
Notice how the todo items both say "Buy Movie Tickets" β this is because the same component is being invoked twice, and the todo text is hardcoded into it. We'll look at showing different todo items in the next article!
Summary
-------
Great! Everything looks as it should. We have successfully refactored our HTML into components! In the next article we'll start looking into adding interactivity to our Ember application.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Vue conditional rendering: editing existing todos - Learn web development | Vue conditional rendering: editing existing todos
=================================================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
Now it is time to add one of the major parts of functionality that we're still missing β the ability to edit existing todo items. To do this, we will take advantage of Vue's conditional rendering capabilities β namely `v-if` and `v-else` β to allow us to toggle between the existing todo item view, and an edit view where you can update todo item labels. We'll also look at adding functionality to delete todo items.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with node + npm installed.
|
| Objective: | To learn how to do conditional rendering in Vue. |
Creating an editing component
-----------------------------
We can start by creating a separate component to handle the editing functionality. In your `components` directory, create a new file called `ToDoItemEditForm.vue`. Copy the following code into that file:
```html
<template>
<form class="stack-small" @submit.prevent="onSubmit">
<div>
<label class="edit-label">Edit Name for "{{label}}"</label>
<input
:id="id"
type="text"
autocomplete="off"
v-model.lazy.trim="newLabel" />
</div>
<div class="btn-group">
<button type="button" class="btn" @click="onCancel">
Cancel
<span class="visually-hidden">editing {{label}}</span>
</button>
<button type="submit" class="btn btn\_\_primary">
Save
<span class="visually-hidden">edit for {{label}}</span>
</button>
</div>
</form>
</template>
<script>
export default {
props: {
label: {
type: String,
required: true,
},
id: {
type: String,
required: true,
},
},
data() {
return {
newLabel: this.label,
};
},
methods: {
onSubmit() {
if (this.newLabel && this.newLabel !== this.label) {
this.$emit("item-edited", this.newLabel);
}
},
onCancel() {
this.$emit("edit-cancelled");
},
},
};
</script>
<style scoped>
.edit-label {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #0b0c0c;
display: block;
margin-bottom: 5px;
}
input {
display: inline-block;
margin-top: 0.4rem;
width: 100%;
min-height: 4.4rem;
padding: 0.4rem 0.8rem;
border: 2px solid #565656;
}
form {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
form > \* {
flex: 0 0 100%;
}
</style>
```
**Note:** Walk through the above code then read the below description to make sure you understand everything the component is doing before moving on. This is a useful way to help reinforce everything you've learned so far.
This code sets up the core of the edit functionality. We create a form with an `<input>` field for editing the name of our to-do.
There is a "Save" button and a "Cancel" button:
* When the "Save" button is clicked, the component emits the new label via an `item-edited` event.
* When the "Cancel" button is clicked, the component signals this by emitting an `edit-cancelled` event.
Modifying our ToDoItem component
--------------------------------
Before we can add `ToDoItemEditForm` to our app, we need to make a few modifications to our `ToDoItem` component. Specifically, we need to add a variable to track if the item is being edited, and a button to toggle that variable. We'll also add a `Delete` button since deletion is closely related.
Update your `ToDoItem`'s template as shown below.
```html
<template>
<div class="stack-small">
<div class="custom-checkbox">
<input
type="checkbox"
class="checkbox"
:id="id"
:checked="isDone"
@change="$emit('checkbox-changed')" />
<label :for="id" class="checkbox-label">{{label}}</label>
</div>
<div class="btn-group">
<button type="button" class="btn" @click="toggleToItemEditForm">
Edit <span class="visually-hidden">{{label}}</span>
</button>
<button type="button" class="btn btn\_\_danger" @click="deleteToDo">
Delete <span class="visually-hidden">{{label}}</span>
</button>
</div>
</div>
</template>
```
We've added a wrapper `<div>` around the whole template for layout purposes.
We've also added "Edit" and "Delete" buttons:
* The "Edit" button, when clicked, will toggle displaying the `ToDoItemEditForm` component so we can use it to edit our todo item, via an event handler function called `toggleToItemEditForm()`. This handler will set an `isEditing` flag to true. To do that, we'll need to first define it inside our `data()` property.
* The "Delete" button, when clicked, will delete the todo item via an event handler function called `deleteToDo()`. In this handler we'll emit an `item-deleted` event to our parent component so the list can be updated.
Let's define our click handlers, and the necessary `isEditing` flag.
Add `isEditing` below your existing `isDone` data point:
```js
data() {
return {
isDone: this.done,
isEditing: false
};
}
```
Now add your methods inside a methods property, right below your `data()` property:
```js
methods: {
deleteToDo() {
this.$emit('item-deleted');
},
toggleToItemEditForm() {
this.isEditing = true;
}
}
```
Conditionally displaying components via v-if and v-else
-------------------------------------------------------
Now we have an `isEditing` flag that we can use to signify that the item is being edited (or not). If `isEditing` is true, we want to use that flag to display our `ToDoItemEditForm` instead of the checkbox. To do that, we'll use another Vue directive: `v-if`.
The `v-if` directive will only render a block if the value passed to it is truthy. This is similar to how an `if` statement works in JavaScript. `v-if` also has corresponding `v-else-if` and `v-else` directives to provide the equivalent of JavaScript `else if` and `else` logic inside Vue templates.
It's important to note that `v-else` and `v-else-if` blocks need to be the first sibling of a `v-if`/`v-else-if` block, otherwise Vue will not recognize them. You can also attach `v-if` to a `<template>` tag if you need to conditionally render an entire template.
Lastly, you can use a `v-if` + `v-else` at the root of your component to display only one block or another, since Vue will only render one of these blocks at a time. We'll do this in our app, as it will allow us to replace the code that displays our to-do item with the edit form.
First of all add `v-if="!isEditing"` to the root `<div>` in your `ToDoItem` component,
```html
<div class="stack-small" v-if="!isEditing"></div>
```
Next, below that `<div>`'s closing tag add the following line:
```html
<to-do-item-edit-form v-else :id="id" :label="label"></to-do-item-edit-form>
```
We also need to import and register the `ToDoItemEditForm` component, so we can use it inside this template. Add this line at the top of your `<script>` element:
```js
import ToDoItemEditForm from "./ToDoItemEditForm";
```
And add a `components` property above the `props` property inside the component object:
```js
components: {
ToDoItemEditForm
},
```
Now, if you go to your app and click a todo item's "Edit" button, you should see the checkbox replaced with the edit form.
![The todo list app, with Edit and Delete buttons shown, and one of the todos in edit mode, with an edit input and save and cancel buttons shown](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering/todo-edit-delete.png)
However, there's currently no way to go back. To fix that, we need to add some more event handlers to our component.
Getting back out of edit mode
-----------------------------
First, we need to add an `itemEdited()` method to our `ToDoItem` component's `methods`. This method should take the new item label as an argument, emit an `itemEdited` event to the parent component, and set `isEditing` to `false`.
Add it now, below your existing methods:
```js
itemEdited(newLabel) {
this.$emit('item-edited', newLabel);
this.isEditing = false;
}
```
Next, we'll need an `editCancelled()` method. This method will take no arguments and just serve to set `isEditing` back to `false`. Add this method below the previous one:
```js
editCancelled() {
this.isEditing = false;
}
```
Last for this section, we'll add event handlers for the events emitted by the `ToDoItemEditForm` component, and attach the appropriate methods to each event.
Update your `<to-do-item-edit-form></to-do-item-edit-form>` call to look like so:
```html
<to-do-item-edit-form
v-else
:id="id"
:label="label"
@item-edited="itemEdited"
@edit-cancelled="editCancelled">
</to-do-item-edit-form>
```
Updating and deleting todo items
--------------------------------
Now we can toggle between the edit form and the checkbox. However, we haven't actually handled updating the `ToDoItems` array back in `App.vue`. To fix that, we need to listen for the `item-edited` event, and update the list accordingly. We'll also want to handle the delete event so that we can delete todo items.
Add the following new methods to your `App.vue`'s component object, below the existing methods inside the `methods` property:
```js
deleteToDo(toDoId) {
const itemIndex = this.ToDoItems.findIndex((item) => item.id === toDoId);
this.ToDoItems.splice(itemIndex, 1);
},
editToDo(toDoId, newLabel) {
const toDoToEdit = this.ToDoItems.find((item) => item.id === toDoId);
toDoToEdit.label = newLabel;
}
```
Next, we'll add the event listeners for the `item-deleted` and `item-edited` events:
* For `item-deleted`, you'll need to pass the `item.id` to the method.
* For `item-edited`, you'll need to pass the `item.id` and the special `$event` variable. This is a special Vue variable used to pass event data to methods. When using native HTML events (like `click`), this will pass the native event object to your method.
Update the `<to-do-item></to-do-item>` call inside the `App.vue` template to look like this:
```html
<to-do-item
:label="item.label"
:done="item.done"
:id="item.id"
@checkbox-changed="updateDoneStatus(item.id)"
@item-deleted="deleteToDo(item.id)"
@item-edited="editToDo(item.id, $event)">
</to-do-item>
```
And there you have it β you should now be able to edit and delete items from the list!
Fixing a small bug with isDone status
-------------------------------------
This is great so far, but we've actually introduced a bug by adding in the edit functionality. Try doing this:
1. Check (or uncheck) one of the todo checkboxes.
2. Press the "Edit" button for that todo item.
3. Cancel the edit by pressing the "Cancel" button.
Note the state of the checkbox after you cancel β not only has the app forgotten the state of the checkbox, but the done status of that todo item is now out of whack. If you try checking (or unchecking) it again, the completed count will change in the opposite way to what you'd expect. This is because the `isDone` inside `data` is only given the value `this.done` on component load.
Fixing this is fortunately quite easy β we can do this by converting our `isDone` data item into a computed property β another advantage of computed properties is that they preserve reactivity, meaning (among other things) that their state is saved when the template changes like ours is now doing.
So, let's implement the fix in `ToDoItem.vue`:
1. Remove the following line from inside our `data()` property:
```js
isDone: this.done,
```
2. Add the following block below the data() { } block:
```js
computed: {
isDone() {
return this.done;
}
},
```
Now when you save and reload, you'll find that the problem is solved β the checkbox state is now preserved when you switch between todo item templates.
Understanding the tangle of events
----------------------------------
One of the most potentially confusing parts is the tangle of standard and custom events we've used to trigger all the interactivity in our app. To understand this better, it is a good idea to write out a flow chart, description, or diagram of what events are emitted where, where they are being listened for, and what happens as a result of them firing.
### App.vue
`<to-do-form>` listens for:
* `todo-added` event emitted by the `onSubmit()` method inside the `ToDoForm` component when the form is submitted.
**Result**: `addToDo()` method invoked to add new todo item to the `ToDoItems` array.
`<to-do-item>` listens for:
* `checkbox-changed` event emitted by the checkbox `<input>` inside the `ToDoItem` component when it is checked or unchecked.
**Result**: `updateDoneStatus()` method invoked to update done status of associated todo item.
* `item-deleted` event emitted by the `deleteToDo()` method inside the `ToDoItem` component when the "Delete" button is pressed.
**Result**: `deleteToDo()` method invoked to delete associated todo item.
* `item-edited` event emitted by the `itemEdited()` method inside the `ToDoItem` component when the `item-edited` event emitted by the `onSubmit()` method inside the `ToDoItemEditForm` has been successfully listened for. Yes, this is a chain of two different `item-edited` events!
**Result**: `editToDo()` method invoked to update label of associated todo item.
### ToDoForm.vue
`<form>` listens for `submit` event.
**Result**: `onSubmit()` method is invoked, which checks that the new label is not empty, then emits the `todo-added` event (which is then listened for inside `App.vue`, see above), and finally clears the new label `<input>`.
### ToDoItem.vue
The `<input>` of `type="checkbox"` listens for `change` events.
**Result**: `checkbox-changed` event emitted when the checkbox is checked/unchecked (which is then listened for inside `App.vue`; see above).
"Edit" `<button>` listens for `click` event.
**Result**: `toggleToItemEditForm()` method is invoked, which toggles `this.isEditing` to `true`, which in turn displays the todo item's edit form on re-render.
"Delete" `<button>` listens for `click` event.
**Result**: `deleteToDo()` method is invoked, which emits the `item-deleted` event (which is then listened for inside `App.vue`; see above).
`<to-do-item-edit-form>` listens for:
* `item-edited` event emitted by the `onSubmit()` method inside the `ToDoItemEditForm` component when the form is successfully submitted.
**Result**: `itemEdited()` method is invoked, which emits the `item-edited` event (which is then listened for inside `App.vue`, see above), and sets `this.isEditing` back to `false`, so that the edit form is no longer shown on re-render.
* `edit-cancelled` event emitted by the `onCancel()` method inside the `ToDoItemEditForm` component when the "Cancel" button is clicked.
**Result**: `editCancelled()` method is invoked, which sets `this.isEditing` back to `false`, so that the edit form is no longer shown on re-render.
### ToDoItemEditForm.vue
`<form>` listens for `submit` event.
**Result**: `onSubmit()` method is invoked, which checks to see if the new label value is not blank, and not the same as the old one, and if so emits the `item-edited` event (which is then listened for inside `ToDoItem.vue`, see above).
"Cancel" `<button>` listens for `click` event.
**Result**: `onCancel()` method is invoked, which emits the `edit-cancelled` event (which is then listened for inside `ToDoItem.vue`, see above).
Summary
-------
This article has been fairly intense, and we covered a lot here. We've now got edit and delete functionality in our app, which is fairly exciting. We are nearing the end of our Vue series now. The last bit of functionality to look at is focus management, or put another way, how we can improve our app's keyboard accessibility.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Componentizing our Svelte app - Learn web development | Componentizing our Svelte app
=============================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
In the last article we started developing our to-do list app. The central objective of this article is to look at how to break our app into manageable components and share information between them. We'll componentize our app, then add more functionality to allow users to update existing components.
| | |
| --- | --- |
| Prerequisites: |
At minimum, it is recommended that you are familiar with the core
HTML,
CSS, and
JavaScript languages, and
have knowledge of the
terminal/command line.
You'll need a terminal with node and npm installed to compile and build
your app.
|
| Objective: |
To learn how to break our app into components and share information
among them.
|
Code along with us
------------------
### Git
Clone the GitHub repo (if you haven't already done it) with:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then to get to the current app state, run
```bash
cd mdn-svelte-tutorial/04-componentizing-our-app
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/04-componentizing-our-app
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To code along with us using the REPL, start at
https://svelte.dev/repl/99b9eb228b404a2f8c8959b22c0a40d3?version=3.23.2
Breaking the app into components
--------------------------------
In Svelte, an application is composed from one or more components. A component is a reusable, self-contained block of code that encapsulates HTML, CSS, and JavaScript that belong together, written into a `.svelte` file. Components can be big or small, but they are usually clearly defined: the most effective components serve a single, obvious purpose.
The benefits of defining components are comparable to the more general best practice of organizing your code into manageable pieces. It will help you understand how they relate to each other, it will promote reuse, and it will make your code easier to reason about, maintain, and extend.
But how do you know what should be split into its own component?
There are no hard rules for this. Some people prefer an intuitive approach and start looking at the markup and drawing boxes around every component and subcomponent that seems to have its own logic.
Other people apply the same techniques used for deciding if you should create a new function or object. One such technique is the single responsibility principle β that is, a component should ideally only do one thing. If it ends up growing, it should be split into smaller subcomponents.
Both approaches should complement each other, and help you decide how to better organize your components.
Eventually, we will split up our app into the following components:
* `Alert.svelte`: A general notification box for communicating actions that have occurred.
* `NewTodo.svelte`: The text input and button that allow you to enter a new to-do item.
* `FilterButton.svelte`: The *All*, *Active*, and *Completed* buttons that allow you to apply filters to the displayed to-do items.
* `TodosStatus.svelte`: The "x out of y items completed" heading.
* `Todo.svelte`: An individual to-do item. Each visible to-do item will be displayed in a separate copy of this component.
* `MoreActions.svelte`: The *Check All* and *Remove Completed* buttons at the bottom of the UI that allow you to perform mass actions on the to-do items.
![graphical representation of the list of components in our app](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_components/01-todo-components.png)
In this article we will concentrate on creating the `FilterButton` and `Todo` components; we'll get to the others in future articles.
Let's get started.
**Note:** In the process of creating our first couple of components, we will also learn different techniques to communicate between components, and the pros and cons of each.
Extracting our filter component
-------------------------------
We'll begin by creating our `FilterButton.svelte`.
1. First of all, create a new file, `components/FilterButton.svelte`.
2. Inside this file we will declare a `filter` prop, and then copy the relevant markup over to it from `Todos.svelte`. Add the following content into the file:
```svelte
<script>
export let filter = 'all'
</script>
<div class="filters btn-group stack-exception">
<button class="btn toggle-btn" class:btn\_\_primary={filter === 'all'} aria-pressed={filter === 'all'} on:click={() => filter = 'all'} >
<span class="visually-hidden">Show</span>
<span>All</span>
<span class="visually-hidden">tasks</span>
</button>
<button class="btn toggle-btn" class:btn\_\_primary={filter === 'active'} aria-pressed={filter === 'active'} on:click={() => filter = 'active'} >
<span class="visually-hidden">Show</span>
<span>Active</span>
<span class="visually-hidden">tasks</span>
</button>
<button class="btn toggle-btn" class:btn\_\_primary={filter === 'completed'} aria-pressed={filter === 'completed'} on:click={() => filter = 'completed'} >
<span class="visually-hidden">Show</span>
<span>Completed</span>
<span class="visually-hidden">tasks</span>
</button>
</div>
```
3. Back in our `Todos.svelte` component, we want to make use of our `FilterButton` component. First of all, we need to import it. Add the following line at the top of the `Todos.svelte <script>` section:
```js
import FilterButton from "./FilterButton.svelte";
```
4. Now replace the `<div class="filters...` element with a call to the `FilterButton` component, which takes the current filter as a prop. The below line is all you need:
```svelte
<FilterButton {filter} />
```
**Note:** Remember that when the HTML attribute name and variable match, they can be replaced with `{variable}`. That's why we could replace `<FilterButton filter={filter} />` with `<FilterButton {filter} />`.
So far so good! Let's try out the app now. You'll notice that when you click on the filter buttons, they are selected and the style updates appropriately. But we have a problem: the to-dos aren't filtered. That's because the `filter` variable flows down from the `Todos` component to the `FilterButton` component through the prop, but changes occurring in the `FilterButton` component don't flow back up to its parent β the data binding is one-way by default. Let's look at a way to solve this.
Sharing data between components: passing a handler as a prop
------------------------------------------------------------
One way to let child components notify their parents of any changes is to pass a handler as a prop. The child component will execute the handler, passing the needed information as a parameter, and the handler will modify the parent's state.
In our case, the `FilterButton` component will receive an `onclick` handler from its parent. Whenever the user clicks on any filter button, the child will call the `onclick` handler, passing the selected filter as a parameter back up to its parent.
We will just declare the `onclick` prop assigning a dummy handler to prevent errors, like this:
```js
export let onclick = (clicked) => {};
```
And we'll declare the reactive statement `$: onclick(filter)` to call the `onclick` handler whenever the `filter` variable is updated.
1. The `<script>` section of our `FilterButton` component should end up looking like this. Update it now:
```js
export let filter = "all";
export let onclick = (clicked) => {};
$: onclick(filter);
```
2. Now when we call `FilterButton` inside `Todos.svelte`, we'll need to specify the handler. Update it like this:
```svelte
<FilterButton {filter} onclick={ (clicked) => filter = clicked }/>
```
When any filter button is clicked, we just update the filter variable with the new filter. Now our `FilterButton` component will work again.
Easier two-way data binding with the bind directive
---------------------------------------------------
In the previous example we realized that our `FilterButton` component wasn't working because our application state was flowing down from parent to child through the `filter` prop, but it wasn't going back up. So we added an `onclick` prop to let the child component communicate the new `filter` value to its parent.
It works OK, but Svelte provides us with an easier and more straightforward way to achieve two-way data binding. Data ordinarily flows down from parent to child using props. If we want it to also flow the other way, from child to parent, we can use the `bind:` directive.
Using `bind`, we will tell Svelte that any changes made to the `filter` prop in the `FilterButton` component should propagate back up to the parent component, `Todos`. That is, we will bind the `filter` variable's value in the parent to its value in the child.
1. In `Todos.svelte`, update the call to the `FilterButton` component as follows:
```svelte
<FilterButton bind:filter={filter} />
```
As usual, Svelte provides us with a nice shorthand: `bind:value={value}` is equivalent to `bind:value`. So in the above example you could just write `<FilterButton bind:filter />`.
2. The child component can now modify the value of the parent's filter variable, so we no longer need the `onclick` prop. Modify the `<script>` element of your `FilterButton` like this:
```svelte
<script>
export let filter = "all";
</script>
```
3. Try your app again, and you should still see your filters working correctly.
Creating our Todo component
---------------------------
Now we will create a `Todo` component to encapsulate each individual to-do, including the checkbox and some editing logic so you can change an existing to-do.
Our `Todo` component will receive a single `todo` object as a prop. Let's declare the `todo` prop and move the code from the `Todos` component. Just for now, we'll replace the call to `removeTodo` with an alert. We'll add that functionality back in later on.
1. Create a new component file, `components/Todo.svelte`.
2. Put the following contents inside this file:
```svelte
<script>
export let todo
</script>
<div class="stack-small">
<div class="c-cb">
<input type="checkbox" id="todo-{todo.id}"
on:click={() => todo.completed = !todo.completed}
checked={todo.completed}
/>
<label for="todo-{todo.id}" class="todo-label">{todo.name}</label>
</div>
<div class="btn-group">
<button type="button" class="btn">
Edit <span class="visually-hidden">{todo.name}</span>
</button>
<button type="button" class="btn btn\_\_danger" on:click={() => alert('not implemented')}>
Delete <span class="visually-hidden">{todo.name}</span>
</button>
</div>
</div>
```
3. Now we need to import our `Todo` component into `Todos.svelte`. Go to this file now, and add the following `import` statement below your previous one:
```js
import Todo from "./Todo.svelte";
```
4. Next we need to update our `{#each}` block to include a `<Todo>` component for each to-do, rather than the code that has been moved out to `Todo.svelte`. We are also passing the current `todo` object into the component as a prop.
Update the `{#each}` block inside `Todos.svelte` like so:
```svelte
<ul role="list" class="todo-list stack-large" aria-labelledby="list-heading">
{#each filterTodos(filter, todos) as todo (todo.id)}
<li class="todo">
<Todo {todo} />
</li>
{:else}
<li>Nothing to do here!</li>
{/each}
</ul>
```
The list of to-dos is displayed on the page, and the checkboxes should work (try checking/unchecking a couple, and then observing that the filters still work as expected), but our "x out of y items completed" status heading will no longer update accordingly. That's because our `Todo` component is receiving the to-do via the prop, but it's not sending any information back to its parent. We'll fix this later on.
Sharing data between components: props-down, events-up pattern
--------------------------------------------------------------
The `bind` directive is pretty straightforward and allows you to share data between a parent and child component with minimal fuss. However, when your application grows larger and more complex, it can easily get difficult to keep track of all your bound values. A different approach is the "props-down, events-up" communication pattern.
Basically, this pattern relies on child components receiving data from their parents via props and parent components updating their state by handling events emitted from child components. So props *flow down* from parent to child and events *bubble up* from child to parent. This pattern establishes a two-way flow of information, which is predictable and easier to reason about.
Let's look at how to emit our own events to re-implement the missing *Delete* button functionality.
To create custom events, we'll use the `createEventDispatcher` utility. This will return a `dispatch()` function that will allow us to emit custom events. When you dispatch an event, you have to pass the name of the event and, optionally, an object with additional information that you want to pass to every listener. This additional data will be available on the `detail` property of the event object.
**Note:** Custom events in Svelte share the same API as regular DOM events. Moreover, you can bubble up an event to your parent component by specifying `on:event` without any handler.
We'll edit our `Todo` component to emit a `remove` event, passing the to-do being removed as additional information.
1. First of all, add the following lines to the top of the `Todo` component's `<script>` section:
```js
import { createEventDispatcher } from "svelte";
const dispatch = createEventDispatcher();
```
2. Now update the *Delete* button in the markup section of the same file to look like so:
```svelte
<button type="button" class="btn btn\_\_danger" on:click={() => dispatch('remove', todo)}>
Delete <span class="visually-hidden">{todo.name}</span>
</button>
```
With `dispatch('remove', todo)` we are emitting a `remove` event, and passing as additional data the `todo` being deleted. The handler will be called with an event object available, with the additional data available in the `event.detail` property.
3. Now we have to listen to that event from inside `Todos.svelte` and act accordingly. Go back to this file and update your `<Todo>` component call like so:
```svelte
<Todo {todo} on:remove={(e) => removeTodo(e.detail)} />
```
Our handler receives the `e` parameter (the event object), which as described before holds the to-do being deleted in the `detail` property.
4. At this point, if you try out your app again, you should see that the *Delete* functionality now works again. So our custom event has worked as we hoped. In addition, the `remove` event listener is sending the data change back up to the parent, so our "x out of y items completed" status heading will now update appropriately when to-dos are deleted.
Now we'll take care of the `update` event, so that our parent component can get notified of any modified to-do.
Updating to-dos
---------------
We still have to implement functionality to allow us to edit existing to-dos. We'll have to include an editing mode in the `Todo` component. When entering editing mode, we'll show an `<input>` field to allow us to edit the current to-do name, with two buttons to confirm or cancel our changes.
### Handling the events
1. We'll need one variable to track whether we are in editing mode and another to store the name of the task being updated. Add the following variable definitions at the bottom of the `<script>` section of the `Todo` component:
```js
let editing = false; // track editing mode
let name = todo.name; // hold the name of the to-do being edited
```
2. We have to decide what events our `Todo` component will emit:
* We could emit different events for the status toggle and editing of the name (for example, `updateTodoStatus` and `updateTodoName`).
* Or we could take a more generic approach and emit a single `update` event for both operations.We will take the second approach so that we can demonstrate a different technique. The advantage of this approach is that later we can add more fields to the to-dos and still handle all updates with the same event.
Let's create an `update()` function that will receive the changes and will emit an update event with the modified to-do. Add the following, again to the bottom of the `<script>` section:
```js
function update(updatedTodo) {
todo = { ...todo, ...updatedTodo }; // applies modifications to todo
dispatch("update", todo); // emit update event
}
```
Here we are using the spread syntax to return the original to-do with the modifications applied to it.
3. Next we'll create different functions to handle each user action. When the to-do is in editing mode, the user can save or cancel the changes. When it's not in editing mode, the user can delete the to-do, edit it, or toggle its status between completed and active.
Add the following set of functions below your previous function to handle these actions:
```js
function onCancel() {
name = todo.name; // restores name to its initial value and
editing = false; // and exit editing mode
}
function onSave() {
update({ name }); // updates todo name
editing = false; // and exit editing mode
}
function onRemove() {
dispatch("remove", todo); // emit remove event
}
function onEdit() {
editing = true; // enter editing mode
}
function onToggle() {
update({ completed: !todo.completed }); // updates todo status
}
```
### Updating the markup
Now we need to update our `Todo` component's markup to call the above functions when the appropriate actions are taken.
To handle the editing mode, we are using the `editing` variable, which is a boolean. When it's `true`, it should display the `<input>` field for editing the to-do name, and the *Cancel* and *Save* buttons. When it's not in editing mode, it will display the checkbox, the to-do name, and the buttons to edit and delete the to-do.
To achieve this we will use an `if` block. The `if` block conditionally renders some markup. Take into account that it won't just show or hide the markup based on the condition β it will dynamically add and remove the elements from the DOM, depending on the condition.
When `editing` is `true`, for example, Svelte will show the update form; when it's `false`, it will remove it from the DOM and add in the checkbox. Thanks to Svelte reactivity, assigning the value of the editing variable will be enough to display the correct HTML elements.
The following gives you an idea of what the basic `if` block structure looks like:
```svelte
<div class="stack-small">
{#if editing}
<!-- markup for editing to-do: label, input text, Cancel and Save Button -->
{:else}
<!-- markup for displaying to-do: checkbox, label, Edit and Delete Button -->
{/if}
</div>
```
The non-editing section β that is, the `{:else}` part (lower half) of the `if` block β will be very similar to the one we had in our `Todos` component. The only difference is that we are calling `onToggle()`, `onEdit()`, and `onRemove()`, depending on the user action.
```svelte
{:else}
<div class="c-cb">
<input type="checkbox" id="todo-{todo.id}"
on:click={onToggle} checked={todo.completed}
>
<label for="todo-{todo.id}" class="todo-label">{todo.name}</label>
</div>
<div class="btn-group">
<button type="button" class="btn" on:click={onEdit}>
Edit<span class="visually-hidden"> {todo.name}</span>
</button>
<button type="button" class="btn btn\_\_danger" on:click={onRemove}>
Delete<span class="visually-hidden"> {todo.name}</span>
</button>
</div>
{/if}
</div>
```
It is worth noting that:
* When the user presses the *Edit* button, we execute `onEdit()`, which just sets the `editing` variable to `true`.
* When the user clicks on the checkbox, we call the `onToggle()` function, which executes `update()`, passing an object with the new `completed` value as a parameter.
* The `update()` function emits the `update` event, passing as additional information a copy of the original to-do with the changes applied.
* Finally, the `onRemove()` function emits the `remove` event, passing the `todo` to be deleted as additional data.
The editing UI (the upper half) will contain an `<input>` field and two buttons to cancel or save the changes:
```svelte
<div class="stack-small">
{#if editing}
<form on:submit|preventDefault={onSave} class="stack-small" on:keydown={(e) => e.key === 'Escape' && onCancel()}>
<div class="form-group">
<label for="todo-{todo.id}" class="todo-label">New name for '{todo.name}'</label>
<input bind:value={name} type="text" id="todo-{todo.id}" autoComplete="off" class="todo-text" />
</div>
<div class="btn-group">
<button class="btn todo-cancel" on:click={onCancel} type="button">
Cancel<span class="visually-hidden">renaming {todo.name}</span>
</button>
<button class="btn btn\_\_primary todo-edit" type="submit" disabled={!name}>
Save<span class="visually-hidden">new name for {todo.name}</span>
</button>
</div>
</form>
{:else}
[...]
```
When the user presses the *Edit* button, the `editing` variable will be set to `true`, and Svelte will remove the markup in the `{:else}` part of the DOM and replace it with the markup in the `{#if}` section.
The `<input>`'s `value` property will be bound to the `name` variable, and the buttons to cancel and save the changes call `onCancel()` and `onSave()` respectively (we added those functions earlier):
* When `onCancel()` is invoked, `name` is restored to its original value (when passed in as a prop) and we exit editing mode (by setting `editing` to `false`).
* When `onSave()` in invoked, we run the `update()` function β passing it the modified `name` β and exit editing mode.
We also disable the *Save* button when the `<input>` is empty, using the `disabled={!name}` attribute, and allow the user to cancel the edit using the `Escape` key, like this:
```
on:keydown={(e) => e.key === 'Escape' && onCancel()}
```
We also use `todo.id` to create unique ids for the new input controls and labels.
1. The complete updated markup of our `Todo` component looks like the following. Update yours now:
```svelte
<div class="stack-small">
{#if editing}
<!-- markup for editing todo: label, input text, Cancel and Save Button -->
<form on:submit|preventDefault={onSave} class="stack-small" on:keydown={(e) => e.key === 'Escape' && onCancel()}>
<div class="form-group">
<label for="todo-{todo.id}" class="todo-label">New name for '{todo.name}'</label>
<input bind:value={name} type="text" id="todo-{todo.id}" autoComplete="off" class="todo-text" />
</div>
<div class="btn-group">
<button class="btn todo-cancel" on:click={onCancel} type="button">
Cancel<span class="visually-hidden">renaming {todo.name}</span>
</button>
<button class="btn btn\_\_primary todo-edit" type="submit" disabled={!name}>
Save<span class="visually-hidden">new name for {todo.name}</span>
</button>
</div>
</form>
{:else}
<!-- markup for displaying todo: checkbox, label, Edit and Delete Button -->
<div class="c-cb">
<input type="checkbox" id="todo-{todo.id}"
on:click={onToggle} checked={todo.completed}
>
<label for="todo-{todo.id}" class="todo-label">{todo.name}</label>
</div>
<div class="btn-group">
<button type="button" class="btn" on:click={onEdit}>
Edit<span class="visually-hidden"> {todo.name}</span>
</button>
<button type="button" class="btn btn\_\_danger" on:click={onRemove}>
Delete<span class="visually-hidden"> {todo.name}</span>
</button>
</div>
{/if}
</div>
```
**Note:** We could further split this into two different components, one for editing the to-do and the other for displaying it. In the end, it boils down to how comfortable you feel dealing with this level of complexity in a single component. You should also consider whether splitting it further would enable reusing this component in a different context.
2. To get the update functionality working, we have to handle the `update` event from the `Todos` component. In its `<script>` section, add this handler:
```js
function updateTodo(todo) {
const i = todos.findIndex((t) => t.id === todo.id);
todos[i] = { ...todos[i], ...todo };
}
```
We find the `todo` by `id` in our `todos` array, and update its content using spread syntax. In this case we could have also just used `todos[i] = todo`, but this implementation is more bullet-proof, allowing the `Todo` component to return only the updated parts of the to-do.
3. Next we have to listen for the `update` event on our `<Todo>` component call, and run our `updateTodo()` function when this occurs to change the `name` and `completed` status. Update your <Todo> call like this:
```svelte
{#each filterTodos(filter, todos) as todo (todo.id)}
<li class="todo">
<Todo {todo} on:update={(e) => updateTodo(e.detail)} on:remove={(e) =>
removeTodo(e.detail)} />
</li>
```
4. Try your app again, and you should see that you can delete, add, edit, cancel editing of, and toggle completion status of to-dos. And our "x out of y items completed" status heading will now update appropriately when to-dos are completed.
As you can see, it's easy to implement the "props-down, events-up" pattern in Svelte. Nevertheless, for simple components `bind` can be a good choice; Svelte will let you choose.
**Note:** Svelte provides more advanced mechanisms to share information among components: the Context API and Stores. The Context API provides a mechanism for components and their descendants to "talk" to each other without passing around data and functions as props, or dispatching lots of events. Stores allows you to share reactive data among components that are not hierarchically related. We will look at Stores later on in the series.
The code so far
---------------
### Git
To see the state of the code as it should be at the end of this article, access your copy of our repo like this:
```bash
cd mdn-svelte-tutorial/05-advanced-concepts
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/05-advanced-concepts
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To see the current state of the code in a REPL, visit:
https://svelte.dev/repl/76cc90c43a37452e8c7f70521f88b698?version=3.23.2
Summary
-------
Now we have all of our app's required functionality in place. We can display, add, edit, and delete to-dos, mark them as completed, and filter by status.
In this article, we covered the following topics:
* Extracting functionality to a new component
* Passing information from child to parent using a handler received as a prop
* Passing information from child to parent using the `bind` directive
* Conditionally rendering blocks of markup using the `if` block
* Implementing the "props-down, events-up" communication pattern
* Creating and listening to custom events
In the next article we will continue componentizing our app and look at some advanced techniques for working with the DOM.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Introduction to client-side frameworks - Learn web development | Introduction to client-side frameworks
======================================
* Overview: Client-side JavaScript frameworks
* Next
We begin our look at frameworks with a general overview of the area, looking at a brief history of JavaScript and frameworks, why frameworks exist and what they give us, how to start thinking about choosing a framework to learn, and what alternatives there are to client-side frameworks.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages.
|
| Objective: | To understand how client-side JavaScript frameworks came to exist, what problems they solve, what alternatives there are, and how to go about choosing one. |
A brief history
---------------
When JavaScript debuted in 1996, it added occasional interactivity and excitement to a web that was, up until then, composed of static documents. The web became not just a place to *read things*, but to *do things*. JavaScript's popularity steadily increased. Developers who worked with JavaScript wrote tools to solve the problems they faced, and packaged them into reusable packages called **libraries**, so they could share their solutions with others. This shared ecosystem of libraries helped shape the growth of the web.
Now, JavaScript is an essential part of the web, used on 98% of all websites, and the web is an essential part of modern life. Users write papers, manage their budgets, stream music, watch movies, and communicate with others over great distances instantaneously, with text, audio, or video chat. The web allows us to do things that used to be possible only in native applications installed on our computers. These modern, complex, interactive websites are often referred to as **web applications**.
The advent of modern JavaScript frameworks has made it much easier to build highly dynamic, interactive applications. A **framework** is a library that offers opinions about how software gets built. These opinions allow for predictability and homogeneity in an application; predictability allows the software to scale to an enormous size and still be maintainable; predictability and maintainability are essential for the health and longevity of software.
JavaScript frameworks power much of the impressive software on the modern web β including many of the websites you likely use every day. MDN Web Docs, which you are currently reading this on, uses the React/ReactDOM framework to power its front end.
What frameworks are out there?
------------------------------
There are many frameworks out there, but currently the "big four" are considered to be the following.
### Ember
Ember was initially released in December 2011 as a continuation of work that started in the SproutCore project. It is an older framework that has fewer users than more modern alternatives such as React and Vue, but it still enjoys a fair amount of popularity due to its stability, community support, and some clever coding principles.
Start learning Ember
### Angular
Angular is an open-source web application framework led by the Angular Team at Google and by a community of individuals and corporations. It is a complete rewrite from the same team that built AngularJS. Angular was officially released on the 14th of September 2016.
Angular is a component-based framework which uses declarative HTML templates. At build time, transparently to developers, the framework's compiler translates the templates to optimized JavaScript instructions. Angular uses TypeScript, a superset of JavaScript that we'll look at in a little more detail in the next chapter.
Start learning Angular
### Vue
After working on and learning from the original AngularJS project, Evan You released Vue in 2014. Vue is the youngest of the big four, but has enjoyed a recent uptick in popularity.
Vue, like AngularJS, extends HTML with some of its own code. Apart from that, it mainly relies on modern, standard JavaScript.
Start learning Vue
### React
Facebook released React in 2013. By this point, it had already been using React to solve many of its problems internally. Technically, React itself is *not* a framework; it's a library for rendering UI components. React is used in combination with *other* libraries to make applications β React and React Native enable developers to make mobile applications; React and ReactDOM enable them to make web applications, etc.
Because React and ReactDOM are so often used together, React is colloquially understood as a JavaScript framework. As you read through this module, we will be working with that colloquial understanding.
React extends JavaScript with HTML-like syntax, known as JSX.
Start learning React
Why do frameworks exist?
------------------------
We've discussed the environment that inspired the creation of frameworks, but not really *why* developers felt the need to make them. Exploring the why requires first examining the challenges of software development.
Consider a common kind of application: A to-do list creator, which we'll look at implementing using a variety of frameworks in future chapters. This application should allow users to do things like render a list of tasks, add a new task, and delete a task; and it must do this while reliably tracking and updating the data underlying the application. In software development, this underlying data is known as state.
Each of our goals is theoretically simple in isolation. We can iterate over the data to render it; we can add to an object to make a new task; we can use an identifier to find, edit, or delete a task. When we remember that the application has to let the user do *all* of these things through the browser, some cracks start to show. **The real problem is this: every time we change our application's state, we need to update the UI to match.**
We can examine the difficulty of this problem by looking at just *one* feature of our to-do list app: rendering a list of tasks.
The verbosity of DOM changes
----------------------------
Building HTML elements and rendering them in the browser at the appropriate time takes a surprising amount of code. Let's say that our state is an array of objects structured like this:
```js
const state = [
{
id: "todo-0",
name: "Learn some frameworks!",
},
];
```
How do we show one of those tasks to our users? We want to represent each task as a list item β an HTML `<li>` element inside of an unordered list element (a `<ul>`). How do we make it? That could look something like this:
```js
function buildTodoItemEl(id, name) {
const item = document.createElement("li");
const span = document.createElement("span");
span.textContent = name;
item.id = id;
item.appendChild(span);
item.appendChild(buildDeleteButtonEl(id));
return item;
}
```
Here, we use the `document.createElement()` method to make our `<li>`, and several more lines of code to create the properties and child elements it needs.
The previous snippet references another build function: `buildDeleteButtonEl()`. It follows a similar pattern to the one we used to build a list item element:
```js
function buildDeleteButtonEl(id) {
const button = document.createElement("button");
button.setAttribute("type", "button");
button.textContent "Delete";
return button;
}
```
This button doesn't do anything yet, but it will later once we decide to implement our delete feature. The code that will render our items on the page might read something like this:
```js
function renderTodoList() {
const frag = document.createDocumentFragment();
state.tasks.forEach((task) => {
const item = buildTodoItemEl(task.id, task.name);
frag.appendChild(item);
});
while (todoListEl.firstChild) {
todoListEl.removeChild(todoListEl.firstChild);
}
todoListEl.appendChild(frag);
}
```
We've now got almost thirty lines of code dedicated *just* to the UI β *just* to render something in the DOM β and at no point do we add classes that we could use later to style our list-items!
Working directly with the DOM, as in this example, requires understanding many things about how the DOM works: how to make elements; how to change their properties; how to put elements inside of each other; how to get them on the page. None of this code actually handles user interactions, or addresses adding or deleting a task. If we add those features, we have to remember to update our UI at the right time and in the right way.
JavaScript frameworks were created to make this kind of work a lot easier β they exist to provide a better *developer experience*. They don't bring brand-new powers to JavaScript; they give you easier access to JavaScript's powers so you can build for today's web.
If you want to see code samples from this section in action, you can check out a working version of the app on CodePen, which also allows users to add and delete new tasks.
Read more about the JavaScript features used in this section:
* `Array.forEach()`
* `Document.createDocumentFragment()`
* `Document.createElement()`
* `Element.setAttribute()`
* `Node.appendChild()`
* `Node.removeChild()`
* `Node.textContent`
Another way to build UIs
------------------------
Every JavaScript framework offers a way to write user interfaces more *declaratively*. That is, they allow you to write code that describes how your UI should look, and the framework makes it happen in the DOM behind the scenes.
The vanilla JavaScript approach to building out new DOM elements in repetition was difficult to understand at a glance. By contrast, the following block of code illustrates the way you might use Vue to describe our list of tasks:
```html
<ul>
<li v-for="task in tasks" v-bind:key="task.id">
<span>{{task.name}}</span>
<button type="button">Delete</button>
</li>
</ul>
```
That's it. This snippet reduces almost thirty lines of code down to six lines. If the curly braces and `v-` attributes here are unfamiliar to you, that's okay; you'll learn about Vue-specific syntax later on in the module. The thing to take away here is that this code looks like the UI it represents, whereas the vanilla JavaScript code does not.
Thanks to Vue, we didn't have to write our own functions for building the UI; the framework will handle that for us in an optimized, efficient way. Our only role here was to describe to Vue what each item should look like. Developers who are familiar with Vue can quickly work out what is going on when they join our project. Vue is not alone in this: using a framework improves team as well as individual efficiency.
It's possible to do things *similar* to this in vanilla JavaScript. Template literal strings make it easy to write strings of HTML that represent what the final element would look like. That might be a useful idea for something as simple as our to-do list application, but it's not maintainable for large applications that manage thousands of records of data, and could render just as many unique elements in a user interface.
Other things frameworks give us
-------------------------------
Let's look at some of the other advantages offered by frameworks. As we've alluded to before, the advantages of frameworks are achievable in vanilla JavaScript, but using a framework takes away all of the cognitive load of having to solve these problems yourself.
### Tooling
Because each of the frameworks in this module have a large, active community, each framework's ecosystem provides tooling that improves the developer experience. These tools make it easy to add things like testing (to ensure that your application behaves as it should) or linting (to ensure that your code is error-free and stylistically consistent).
**Note:** If you want to find out more details about web tooling concepts, check out our Client-side tooling overview.
### Compartmentalization
Most major frameworks encourage developers to abstract the different parts of their user interfaces into *components* β maintainable, reusable chunks of code that can communicate with one another. All the code related to a given component can live in one file (or a couple of specific files) so that you as a developer know exactly where to go to make changes to that component. In a vanilla JavaScript app, you'd have to create your own set of conventions to achieve this in an efficient, scalable way. Many JavaScript developers, if left to their own devices, could end up with all the code related to one part of the UI being spread out all over a file β or in another file altogether.
### Routing
The most essential feature of the web is that it allows users to navigate from one page to another β it is, after all, a network of interlinked documents. When you follow a link on this very website, your browser communicates with a server and fetches new content to display for you. As it does so, the URL in your address bar changes. You can save this new URL and come back to the page later on, or share it with others so they can easily find the same page. Your browser remembers your navigation history and allows you to navigate back and forth, too. This is called **server-side routing**.
Modern web applications typically do not fetch and render new HTML files β they load a single HTML shell, and continually update the DOM inside it (referred to as **single page apps**, or **SPAs**) without navigating users to new addresses on the web. Each new pseudo-webpage is usually called a *view*, and by default, no routing is done.
When an SPA is complex enough, and renders enough unique views, it's important to bring routing functionality into your application. People are used to being able to link to specific pages in an application, travel forward and backward in their navigation history, etc., and their experience suffers when these standard web features are broken. When routing is handled by a client application in this fashion, it is aptly called **client-side routing**.
It's *possible* to make a router using the native capabilities of JavaScript and the browser, but popular, actively developed frameworks have companion libraries that make routing a more intuitive part of the development process.
Things to consider when using frameworks
----------------------------------------
Being an effective web developer means using the most appropriate tools for the job. JavaScript frameworks make front-end application development easy, but they are not a silver bullet that will solve all problems. This section talks about some of the things you should consider when using frameworks. Bear in mind that you might not need a framework at all β beware that you don't end up using a framework just for the sake of it.
### Familiarity with the tool
Just like vanilla JavaScript, frameworks take time to learn and have their quirks. Before you decide to use a framework for a project, be sure you have time to learn enough of its features for it to be useful to you rather than it working against you, and be sure that your teammates are comfortable with it as well.
### Overengineering
If your web development project is a personal portfolio with a few pages, and those pages have little or no interactive capability, a framework (and all of its JavaScript) may not be necessary at all. That said, frameworks are not monolithic, and some of them are better suited to small projects than others. In an article for Smashing Magazine, Sarah Drasner writes about how Vue can replace jQuery as a tool for making small portions of a webpage interactive.
### Larger code base and abstraction
Frameworks allow you to write more declarative code β and sometimes *less* code overall β by dealing with the DOM interactions for you, behind the scenes. This abstraction is great for your experience as a developer, but it isn't free. In order to translate what you write into DOM changes, frameworks have to run their own code, which in turn makes your final piece of software larger and more computationally expensive to operate.
Some extra code is inevitable, and a framework that supports tree-shaking (removal of any code that isn't actually used in the app during the build process) will allow you to keep your applications small, but this is still a factor you need to keep in mind when considering your app's performance, especially on more network/storage-constrained devices, like mobile phones.
The abstraction of frameworks affects not only your JavaScript, but also your relationship with the very nature of the web. No matter how you build for the web, the end result, the layer that your users ultimately interact with, is HTML. Writing your whole application in JavaScript can make you lose sight of HTML and the purpose of its various tags, and lead you to produce an HTML document that is un-semantic and inaccessible. In fact, it's possible to write a fragile application that depends entirely on JavaScript and will not function without it.
Frameworks are not the source of our problems. With the wrong priorities, any application can be fragile, bloated, and inaccessible. Frameworks do, however, amplify our priorities as developers. If your priority is to make a complex web app, it's easy to do that. However, if your priorities don't carefully guard performance and accessibility, frameworks will amplify your fragility, your bloat, and your inaccessibility. Modern developer priorities, amplified by frameworks, have inverted the structure of the web in many places. Instead of a robust, content-first network of documents, the web now often puts JavaScript first and user experience last.
Accessibility on a framework-driven web
---------------------------------------
Let's build on what we said in the previous section, and talk a bit more about accessibility. Making user interfaces accessible always requires some thought and effort, and frameworks can complicate that process. You often have to employ advanced framework APIs to access native browser features like ARIA live regions or focus management.
In some cases, framework applications create accessibility barriers that do not exist for traditional websites. The biggest example of this is in client-side routing, as mentioned earlier.
With traditional (server-side) routing, navigating the web has predictable results. The browser knows to set focus to the top of the page and assistive technologies will announce the title of the page. These things happen every time you navigate to a new page.
With client-side routing, your browser is not loading new web pages, so it doesn't know that it should automatically adjust focus or announce a new page title. Framework authors have devoted immense time and labor to writing JavaScript that recreates these features, and even then, no framework has done so perfectly.
The upshot is that you should consider accessibility from the very start of *every* web project, but bear in mind that abstracted codebases that use frameworks are more likely to suffer from major accessibility issues if you don't.
How to choose a framework
-------------------------
Each of the frameworks discussed in this module takes different approaches to web application development. Each is regularly improving or changing, and each has its pros and cons. Choosing the right framework is a team- and project-dependent process, and you should do your own research to uncover what suits your needs. That said, we've identified a few questions you can ask in order to research your options more effectively:
1. What browsers does the framework support?
2. What domain-specific languages does the framework utilize?
3. Does the framework have a strong community and good docs (and other support) available?
The table in this section provides a glanceable summary of the current *browser support* offered by each framework, as well as the **domain-specific languages** with which it can be used.
Broadly, domain-specific languages (DSLs) are programming languages relevant in specific areas of software development. In the context of frameworks, DSLs are variations on JavaScript or HTML that make it easier to develop with that framework. Crucially, none of the frameworks *require* a developer to use a specific DSL, but they have almost all been designed with a specific DSL in mind. Choosing not to employ a framework's preferred DSL will mean you miss out on features that would otherwise improve your developer experience.
You should seriously consider the support matrix and DSLs of a framework when making a choice for any new project. Mismatched browser support can be a barrier to your users; mismatched DSL support can be a barrier to you and your teammates.
| Framework | Browser support | Preferred DSL | Supported DSLs | Citation |
| --- | --- | --- | --- | --- |
| Angular | Modern | TypeScript | HTML-based; TypeScript | official docs |
| React | Modern | JSX | JSX; TypeScript | official docs |
| Vue | Modern (IE9+ in Vue 2) | HTML-based | HTML-based, JSX, Pug | official docs |
| Ember | Modern (IE9+ in Ember version 2.18) | Handlebars | Handlebars, TypeScript | official docs |
**Note:** DSLs we've described as "HTML-based" do not have official names. They are not really true DSLs, but they are non-standard HTML, so we believe they are worth highlighting.
### Does the framework have a strong community?
This is perhaps the hardest metric to measure because community size does not correlate directly to easy-to-access numbers. You can check a project's number of GitHub stars or weekly npm downloads to get an idea of its popularity, but sometimes the best thing to do is search a few forums or talk to other developers. It is not just about the community's size, but also how welcoming and inclusive it is, and how good the available documentation is.
### Opinions on the web
Don't just take our word on this matter β there are discussions all over the web. The Wikimedia Foundation recently chose to use Vue for its front-end, and posted a request for comments (RFC) on framework adoption. Eric Gardner, the author of the RFC, took time to outline the needs of the Wikimedia project and why certain frameworks were good choices for the team. This RFC serves as a great example of the kind of research you should do for yourself when planning to use a front-end framework.
The State of JavaScript survey is a helpful collection of feedback from JavaScript developers. It covers many topics related to JavaScript, including data about both the use of frameworks and developer sentiment toward them. Currently, there are several years of data available, allowing you to get a sense of a framework's popularity.
The Vue team has exhaustively compared Vue to other popular frameworks. There may be some bias in this comparison (which they note), but it's a valuable resource nonetheless.
Alternatives to client-side frameworks
--------------------------------------
If you're looking for tools to expedite the web development process, and you know your project isn't going to require intensive client-side JavaScript, you could reach for one of a handful of other solutions for building the web:
* A content management system
* Server-side rendering
* A static site generator
### Content management systems
**Content-management systems** (**CMSes**) are any tools that allow a user to create content for the web without directly writing code themselves. They're a good solution for large projects, especially projects that require input from content writers who have limited coding ability, or for programmers who want to save time. They do, however, require a significant amount of time to set up, and utilizing a CMS means that you surrender at least some measure of control over the final output of your website. For example: if your chosen CMS doesn't author accessible content by default, it's often difficult to improve this.
A few popular CMS systems include Wordpress, Joomla, and Drupal.
### Server-side rendering
**Server-side rendering** (**SSR**) is an application architecture in which it is the *server*'s job to render a single-page application. This is the opposite of *client-side rendering*, which is the most common and most straightforward way to build a JavaScript application. Server-side rendering is easier on the client's device because you're only sending a rendered HTML file to them, but it can be difficult to set up compared to a client-side-rendered application.
All of the frameworks covered in this module support server-side rendering as well as client-side rendering. Check out Next.js for React, Nuxt.js for Vue (yes, it is confusing, and no, these projects are not related!), FastBoot for Ember, and Angular Universal for Angular.
**Note:** Some SSR solutions are written and maintained by the community, whereas some are "official" solutions provided by the framework's maintainer.
### Static site generators
Static site generators are programs that dynamically generate all the webpages of a multi-page website β including any relevant CSS or JavaScript β so that they can be published in any number of places. The publishing host could be a GitHub pages branch, a Netlify instance, or any private server of your choosing, for example. There are a number of advantages of this approach, mostly around performance (your user's device isn't building the page with JavaScript; it's already complete) and security (static pages have fewer attack vectors). These sites can still utilize JavaScript where they need to, but they are not *dependent* upon it. Static site generators take time to learn, just like any other tool, which can be a barrier to your development process.
Static sites can have as few or as many unique pages as you want. Just as frameworks empower you to quickly write client-side JavaScript applications, static site generators allow you a way to quickly create HTML files you would otherwise have written individually. Like frameworks, static site generators allow developers to write components that define common pieces of your web pages, and to compose those components together to create a final page. In the context of static site generators, these components are called **templates**. Web pages built by static site generators can even be home to framework applications: if you want one specific page of your statically-generated website to boot up a React application when your user visits it for example, you can do that.
Static site generators have been around for quite a long time, and they've recently seen a wave of renewed interest and innovation. A handful of powerful options are now available, such as Astro, Eleventy, Hugo, Jekyll, and Gatsby.
If you'd like to learn more about static site generators on the whole, check out Tatiana Mac's Beginner's guide to Eleventy. In the first article of the series, they explain what a static site generator is, and how it relates to other means of publishing web content.
Summary
-------
And that brings us to the end of our introduction to frameworks β we've not taught you any code yet, but hopefully we've given you a useful background on why you'd use frameworks in the first place and how to go about choosing one, and made you excited to learn more and get stuck in!
Our next article goes down to a lower level, looking at the specific kinds of features frameworks tend to offer, and why they work as they do.
* Overview: Client-side JavaScript frameworks
* Next |
Filtering our to-do items - Learn web development | Filtering our to-do items
=========================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
Now let's move on to adding functionality to allow users to filter their to-do items, so they can view active, completed, or all items.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
|
| Objective: | To add filtering functionality to our app. |
Our filtering code
------------------
Filtering items builds on the `filter` property, which you previously added to `app.component.ts`:
```ts
filter: 'all' | 'active' | 'done' = 'all';
```
The default value for filter is `all`, but it can also be `active` or `done`.
Adding filter controls
----------------------
In `app.component.html`, add the following HTML below the **Add** button but above the section that lists the items.
In the following snippet, the existing sections in your HTML are in comments so you can see exactly where to put the buttons.
```html
<!-- <button class="btn-primary" (click)="addItem(newItem.value)">Add</button>
-->
<!-- Buttons that show all, still to do, or done items on click -->
<div class="btn-wrapper">
<button
class="btn btn-menu"
[class.active]="filter == 'all'"
(click)="filter = 'all'">
All
</button>
<button
class="btn btn-menu"
[class.active]="filter == 'active'"
(click)="filter = 'active'">
To Do
</button>
<button
class="btn btn-menu"
[class.active]="filter == 'done'"
(click)="filter = 'done'">
Done
</button>
</div>
<!-- <h2>{{items.length}} item(s)</h2>
<ul>... -->
```
Clicking the buttons changes the `filter` values, which determines the `items` that show as well as the styles that Angular applies to the active button.
* If the user clicks the **All** button, all of the items show.
* If the user clicks the **To do** button, only the items with a `done` value of `false` show.
* If the user clicks the **Done** button, only the items with a `done` value of `true` show.
A class attribute binding, using square brackets, `[]`, controls the text color of the buttons.
The class binding, `[class.active]`, applies the `active` class when the value of `filter` matches the expression.
For example, when the user clicks the **Done** button, which sets the `filter` value to `done`, the class binding expression of `filter == 'done'` evaluates to `true`.
When the `filter` value is `done`, Angular applies the `active` class to the **Done** button to make the text color green.
As soon as the user clicks on one of the other buttons, the value a `filter` is no longer `done`, so the green text color no longer applies.
Summary
-------
That was quick! Since you already had the `filter` code in `app.component.ts`, all you had to do was edit the template in order to provide controls for filtering the items. Our next β and last β article looks at how to build your Angular app ready for production, and provides further resources to carry on your learning journey.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Building Angular applications and further resources - Learn web development | Building Angular applications and further resources
===================================================
* Previous
* Overview: Client-side JavaScript frameworks
This final Angular article covers how to build an app ready for production, and provides further resources for you to continue your learning journey.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
|
| Objective: | To learn how to build your Angular app. |
Building your finished application
----------------------------------
Now that you are finished developing your application, you can run the Angular CLI `build` command.
When you run the `build` command in your `todo` directory, your application compiles into an output directory named `dist/`.
In the `todo` directory, run the following command at the command line:
```bash
ng build -c production
```
The CLI compiles the application and puts the output in a new `dist` directory.
The `--configuration production`/`-c production` flag with `ng build` gets rid of stuff you don't need for production.
Deploying your application
--------------------------
To deploy your application, you can copy the contents of the `dist/my-project-name` folder to your web server.
Because these files are static, you can host them on any web server capable of serving files, such as:
* Node.js
* Java
* .NET
You can use any backend such as Firebase, Google Cloud, or App Engine.
What's next
-----------
At this point, you've built a basic application, but your Angular journey is just beginning.
You can learn more by exploring the Angular documentation, such as:
* Tour of Heroes: An in-depth tutorial highlighting Angular features, such as using services, navigation, and getting data from a server.
* The Angular Components guides: A series of articles that cover topics such as lifecycle, component interaction, and view encapsulation.
* The Forms guides: Articles that guide you through building reactive forms in Angular, validating input, and building dynamic forms.
Summary
-------
That's it for now. We hope you had fun with Angular!
* Previous
* Overview: Client-side JavaScript frameworks |
Getting started with Svelte - Learn web development | Getting started with Svelte
===========================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
In this article we'll provide a quick introduction to the Svelte framework. We will see how Svelte works and what sets it apart from the rest of the frameworks and tools we've seen so far. Then we will learn how to set up our development environment, create a sample app, understand the structure of the project, and see how to run it locally and build it for production.
| | |
| --- | --- |
| Prerequisites: |
At minimum, it is recommended that you are familiar with the core
HTML,
CSS, and
JavaScript languages, and
have knowledge of the
terminal/command line.
Svelte is a compiler that generates minimal and highly optimized
JavaScript code from our sources; you'll need a terminal with node +
npm installed to compile and build your app.
|
| Objective: |
To setup a local Svelte development environment, create and build a
starter app, and understand the basics of how it works.
|
Svelte: A new approach to building rich user interfaces
-------------------------------------------------------
Svelte provides a different approach to building web apps than some of the other frameworks covered in this module. While frameworks like React and Vue do the bulk of their work in the user's browser while the app is running, Svelte shifts that work into a compile step that happens only when you build your app, producing highly optimized vanilla JavaScript.
The outcome of this approach is not only smaller application bundles and better performance, but also a developer experience that is more approachable for people that have limited experience of the modern tooling ecosystem.
Svelte sticks closely to the classic web development model of HTML, CSS, and JS, just adding a few extensions to HTML and JavaScript. It arguably has fewer concepts and tools to learn than some of the other framework options.
Its main current disadvantages are that it is a young framework β its ecosystem is therefore more limited in terms of tooling, support, plugins, clear usage patterns, etc. than more mature frameworks, and there are also fewer job opportunities. But its advantages should be enough to make you interested to explore it.
**Note:** Svelte has official TypeScript support. We'll look at it later on in this tutorial series.
We encourage you to go through the Svelte tutorial for a really quick introduction to the basic concepts, before returning to this tutorial series to learn how to build something slightly more in-depth.
Use cases
---------
Svelte can be used to develop small pieces of an interface or whole applications. You can either start from scratch letting Svelte drive your UI or you can incrementally integrate it into an existing application.
Nevertheless, Svelte is particularly appropriate to tackle the following situations:
* Web applications intended for low-power devices: Applications built with Svelte have smaller bundle sizes, which is ideal for devices with slow network connections and limited processing power. Less code means fewer KB to download, parse, execute, and keep hanging around in memory.
* Highly interactive pages or complex visualizations: If you are building data-visualizations that need to display a large number of DOM elements, the performance gains that come from a framework with no runtime overhead will ensure that user interactions are snappy and responsive.
* Onboarding people with basic web development knowledge: Svelte has a shallow learning curve. Web developers with basic HTML, CSS, and JavaScript knowledge can easily grasp Svelte specifics in a short time and start building web applications.
The Svelte team launched SvelteKit, a framework for building web applications using Svelte. It contains features found in modern web frameworks, such as filesystem-based routing, server-side rendering (SSR), page-specific rendering modes, offline support, and more. For more information about SvelteKit, see the official tutorial and documentation.
**Note:** SvelteKit is designed to replace Sapper as the recommended Svelte framework for building web applications.
Svelte is also available for mobile development via Svelte Native.
How does Svelte work?
---------------------
Being a compiler, Svelte can extend HTML, CSS, and JavaScript, generating optimal JavaScript code without any runtime overhead. To achieve this, Svelte extends vanilla web technologies in the following ways:
* It extends HTML by allowing JavaScript expressions in markup and providing directives to use conditions and loops, in a fashion similar to handlebars.
* It extends CSS by adding a scoping mechanism, allowing each component to define its own styles without the risk of clashing with other components' styles.
* It extends JavaScript by reinterpreting specific directives of the language to achieve true reactivity and ease component state management.
The compiler only intervenes in very specific situations and only in the context of Svelte components. Extensions to the JavaScript language are minimal and carefully picked in order not to break JavaScript syntax or alienate developers. In fact, you will be mostly working with vanilla JavaScript.
First steps with Svelte
-----------------------
Since Svelte is a compiler, you can't just add a `<script src="svelte.js">` tag to your page and import it into your app. You'll have to set up your development environment in order to let the compiler do its job.
### Requirements
In order to work with Svelte, you need to have Node.js installed. It's recommended that you use the long-term support (LTS) version. Node includes npm (the node package manager), and npx (the node package runner). Note that you can also use the Yarn package manager in place of npm, but we'll assume you are using npm in this set of tutorials. See Package management basics for more information on npm and yarn.
If you're using Windows, you will need to install some software to give you parity with Unix/macOS terminal in order to use the terminal commands mentioned in this tutorial. Gitbash (which comes as part of the git for Windows toolset) or Windows Subsystem for Linux (WSL) are both suitable. See Command line crash course for more information on these, and on terminal commands in general.
Also see the following for more information:
* "About npm" on the npm documentation
* "Introducing npx" on the npm blog
### Creating your first Svelte app
The easiest way to create a starter app template is to just download the starter template application. You can do that by visiting sveltejs/template on GitHub, or you can avoid having to download and unzip it and just use degit.
To create your starter app template, run the following terminal commands:
```bash
npx degit sveltejs/template moz-todo-svelte
cd moz-todo-svelte
npm install
npm run dev
```
**Note:** degit doesn't do any kind of magic β it just lets you download and unzip the latest version of a git repo's contents. This is much quicker than using `git clone` because it will not download all the history of the repo, or create a complete local clone.
After running `npm run dev`, Svelte will compile and build your application. It will start a local server at `localhost:8080`. Svelte will watch for file updates, and automatically recompile and refresh the app for you when changes are made to the source files. Your browser will display something like this:
![A simple start page that says hello world, and gives a link to the official svelte tutorials](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started/01-svelte-starter-app.png)
### Application structure
The starter template comes with the following structure:
```
moz-todo-svelte
βββ README.md
βββ package.json
βββ package-lock.json
βββ rollup.config.js
βββ .gitignore
βββ node_modules
βββ public
β βββ favicon.png
β βββ index.html
β βββ global.css
β βββ build
β βββ bundle.css
β βββ bundle.js
β βββ bundle.js.map
βββ scripts
β βββ setupTypeScript.js
βββ src
βββ App.svelte
βββ main.js
```
The contents are as follows:
* `package.json` and `package-lock.json`: Contains information about the project that Node.js/npm uses to keep it organized. You don't need to understand this file at all to complete this tutorial, however, if you'd like to learn more, you can read about `package.json` handling on npmjs.com; we also talk about it in our Package management basics tutorial.
* `node_modules`: This is where node saves the project dependencies. These dependencies won't be sent to production, they are just used for development purposes.
* `.gitignore`: Tells git which files or folder to ignore from the project β useful if you decide to include your app in a git repo.
* `rollup.config.js`: Svelte uses rollup.js as a module bundler. This configuration file tells rollup how to compile and build your app. If you prefer webpack, you can create your starter project with `npx degit sveltejs/template-webpack svelte-app` instead.
* `scripts`: Contains setup scripts as required. Currently should only contain `setupTypeScript.js`.
+ `setupTypeScript.js`: This script sets up TypeScript support in Svelte. We'll talk about this more in the last article.
* `src`: This directory is where the source code for your application lives β where you'll be creating the code for your app.
+ `App.svelte`: This is the top-level component of your app. So far it just renders the 'Hello World!' message.
+ `main.js`: The entry point to our application. It just instantiates the `App` component and binds it to the body of our HTML page.
* `public`: This directory contains all the files that will be published in production.
+ `favicon.png`: This is the favicon for your app. Currently, it's the Svelte logo.
+ `index.html`: This is the main page of your app. Initially it's just an empty HTML page that loads the CSS files and js bundles generated by Svelte.
+ `global.css`: This file contains unscoped styles. It's a regular CSS file that will be applied to the whole application.
+ `build`: This folder contains the generated CSS and JavaScript source code.
- `bundle.css`: The CSS file that Svelte generated from the styles defined for each component.
- `bundle.js`: The JavaScript file compiled from all your JavaScript source code.
Having a look at our first Svelte component
-------------------------------------------
Components are the building blocks of Svelte applications. They are written into `.svelte` files using a superset of HTML.
All three sections β `<script>`, `<style>`, and markup β are optional, and can appear in any order you like.
```html
<script>
// logic goes here
</script>
<style>
/\* styles go here \*/
</style>
<!-- markup (zero or more HTML elements) goes here -->
```
**Note:** For more information on the component format, have a look at the Svelte Components documentation.
With this in mind, let's have a look at the `src/App.svelte` file that came with the starter template. You should see something like the following:
```html
<script>
export let name;
</script>
<main>
<h1>Hello {name}!</h1>
<p>
Visit the <a href="https://learn.svelte.dev/">Svelte tutorial</a> to learn
how to build Svelte apps.
</p>
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
h1 {
color: #ff3e00;
text-transform: uppercase;
font-size: 4em;
font-weight: 100;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>
```
### The `<script>` section
The `<script>` block contains JavaScript that runs when a component instance is created. Variables declared (or imported) at the top level are 'visible' from the component's markup. Top-level variables are the way Svelte handles the component state, and they are reactive by default. We will explain in detail what this means later on.
```html
<script>
export let name;
</script>
```
Svelte uses the `export` keyword to mark a variable declaration as a property (or prop), which means it becomes accessible to consumers of the component (e.g. other components). This is one example of Svelte extending JavaScript syntax to make it more useful, while keeping it familiar.
### The markup section
In the markup section you can insert any HTML you like, and in addition you can insert valid JavaScript expressions inside single curly braces (`{}`). In this case we are embedding the value of the `name` prop right after the `Hello` text.
```html
<main>
<h1>Hello {name}!</h1>
<p>
Visit the <a href="https://learn.svelte.dev/">Svelte tutorial</a> to learn
how to build Svelte apps.
</p>
</main>
```
Svelte also supports tags like `{#if}`, `{#each}`, and `{#await}` β these examples allow you to conditionally render a portion of the markup, iterate through a list of elements, and work with async values, respectively.
### The `<style>` section
If you have experience working with CSS, the following snippet should make sense:
```html
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
h1 {
color: #ff3e00;
text-transform: uppercase;
font-size: 4em;
font-weight: 100;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>
```
We are applying a style to our `<h1>` element. What will happen to other components with `<h1>` elements in them?
In Svelte, CSS inside a component's `<style>` block will be scoped only to that component. This works by adding a class to selected elements, which is based on a hash of the component styles.
You can see this in action by opening `localhost:8080` in a new browser tab, right/`Ctrl`-clicking on the *HELLO WORLD!* label, and choosing *Inspect*:
![Svelte starter app with devtools open, showing classes for scoped styles](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started/02-svelte-component-scoped-styles.png)
When compiling the app, Svelte changes our `h1` styles definition to `h1.svelte-1tky8bj`, and then modifies every `<h1>` element in our component to `<h1 class="svelte-1tky8bj">`, so that it picks up the styles as required.
**Note:** You can override this behavior and apply styles to a selector globally using the `:global()` modifier (see the Svelte `<style>` docs for more information).
Making a couple of changes
--------------------------
Now that we have a general idea of how it all fits together, we can start making a few changes.
At this point you can try updating your `App.svelte` component β for example change the `<h1>` element on line 6 of `App.svelte` so that it reads like this:
```html
<h1>Hello {name} from MDN!</h1>
```
Just save your changes and the app running at `localhost:8080` will be automatically updated.
### A first look at Svelte reactivity
In the context of a UI framework, reactivity means that the framework can automatically update the DOM when the state of any component is changed.
In Svelte, reactivity is triggered by assigning a new value to any top-level variable in a component. For example, we could include a `toggleName()` function in our `App` component, and a button to run it.
Try updating your `<script>` and markup sections like so:
```html
<script>
export let name;
function toggleName() {
if (name === "world") {
name = "Svelte";
} else {
name = "world";
}
}
</script>
<main>
<h1>Hello {name}!</h1>
<button on:click="{toggleName}">Toggle name</button>
<p>
Visit the <a href="https://learn.svelte.dev/">Svelte tutorial</a> to learn
how to build Svelte apps.
</p>
</main>
```
Whenever the button is clicked, Svelte executes the `toggleName()` function, which in turn updates the value of the `name` variable.
As you can see, the `<h1>` label is automatically updated. Behind the scenes, Svelte created the JavaScript code to update the DOM whenever the value of the name variable changes, without using any virtual DOM or other complex reconciliation mechanism.
Note the use of `:` in `on:click`. That's Svelte's syntax for listening to DOM events.
Inspecting main.js: the entry point of our app
----------------------------------------------
Let's open `src/main.js`, which is where the `App` component is being imported and used. This file is the entry point for our app, and it initially looks like this:
```js
import App from "./App.svelte";
const app = new App({
target: document.body,
props: {
name: "world",
},
});
export default app;
```
`main.js` starts by importing the Svelte component that we are going to use. Then in line 3 it instantiates it, passing an option object with the following properties:
* `target`: The DOM element inside which we want the component to be rendered, in this case the `<body>` element.
* `props`: the values to assign to each prop of the `App` component.
A look under the hood
---------------------
How does Svelte manage to make all these files work together nicely?
The Svelte compiler processes the `<style>` section of every component and compiles them into the `public/build/bundle.css` file.
It also compiles the markup and `<script>` section of every component and stores the result in `public/build/bundle.js`. It also adds the code in `src/main.js` to reference the features of each component.
Finally the file `public/index.html` includes the generated `bundle.css` and `bundle.js` files:
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Svelte app</title>
<link rel="icon" type="image/png" href="/favicon.png" />
<link rel="stylesheet" href="/global.css" />
<link rel="stylesheet" href="/build/bundle.css" />
<script defer src="/build/bundle.js"></script>
</head>
<body></body>
</html>
```
The minified version of `bundle.js` weighs a little more than 3KB, which includes the "Svelte runtime" (just 300 lines of JavaScript code) and the `App.svelte` compiled component. As you can see, `bundle.js` is the only JavaScript file referenced by `index.html`. There are no other libraries loaded into the web page.
This is a much smaller footprint than compiled bundles from other frameworks. Take into account that, in the case of code bundles, it's not just the size of the files you have to download that matter. This is executable code that needs to be parsed, executed, and kept in memory. So this really makes a difference, especially in low-powered devices or CPU-intensive applications.
Following this tutorial
-----------------------
In this tutorial series you will be building a complete web application. We'll learn all the basics about Svelte and also quite a few advanced topics.
You can just read the content to get a good understanding of Svelte features, but you'll get the most out of this tutorial if you follow along coding the app with us as you go. To make it easier for you to follow each article, we provide a GitHub repository with a folder containing the source for the app as it is at the start of each tutorial.
Svelte also provides an online REPL, which is a playground for live-coding Svelte apps on the web without having to install anything on your machine. We provide a REPL for each article so you can start coding along right away. Let's talk a bit more about how to use these tools.
### Using Git
The most popular version control system is Git, along with GitHub, a site that provides hosting for your repositories and several tools for working with them.
We'll be using GitHub so that you can easily download the source code for each article. You will also be able to get the code as it should be after completing the article, just in case you get lost.
After installing git, to clone the repository you should execute:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then at the beginning of each article, you can just `cd` into the corresponding folder and start the app in dev mode to see what its current state should be, like this:
```bash
cd 02-starting-our-todo-app
npm install
npm run dev
```
If you want lo learn more about git and GitHub, we've compiled a list of links to useful guides β see Git and GitHub.
**Note:** If you just want to download the files without cloning the git repo, you can use the degit tool like this β `npx degit opensas/mdn-svelte-tutorial`. You can also download a specific folder with `npx degit opensas/mdn-svelte-tutorial/01-getting-started`. Degit won't create a local git repo, it will just download the files of the specified folder.
### Using the Svelte REPL
A REPL (readβevalβprint loop) is an interactive environment that allows you to enter commands and immediately see the results β many programming languages provide a REPL.
Svelte's REPL is much more than that. It's an online tool that allows you to create complete apps, save them online, and share with others.
It's the easiest way to start playing with Svelte from any machine, without having to install anything. It is also widely used by Svelte community. If you want to share an idea, ask for help, or report an issue, it's always extremely useful to create a REPL instance demonstrating the issue.
Let's have a quick look at the Svelte REPL and how you'd use it. It looks like so:
![the svelte REPL in action, showing component code on the left, and output on the right](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started/03-svelte-repl-in-action.png)
To start a REPL, open your browser and navigate to https://svelte.dev/repl.
* On the left side of the screen you'll see the code of your components, and on the right you'll see the running output of your app.
* The bar above the code lets you create `.svelte` and `.js` files and rearrange them. To create a file inside a folder, just specify the complete pathname, like this: `components/MyComponent.svelte`. The folder will be automatically created.
* Above that bar you have the title of the REPL. Click on it to edit it.
* On the right side you have three tabs:
+ The *Result* tab shows your app output, and provides a console at the bottom.
+ The *JS output* tab lets you inspect the JavaScript code generated by Svelte and set compiler options.
+ The *CSS output* tab shows the CSS generated by Svelte.
* Above the tabs, you'll find a toolbar that lets you enter fullscreen mode and download your app. If you log in with a GitHub account, you'll also be able to fork and save the app. You'll also be able to see all your saved REPLs by clicking on your GitHub username profile and selecting *Your saved apps*.
Whenever you change any file on the REPL, Svelte will recompile the app and update the Result tab. To share your app, share the URL. For example, here's the link for a REPL running our complete app: https://svelte.dev/repl/378dd79e0dfe4486a8f10823f3813190?version=3.23.2.
**Note:** Notice how you can specify Svelte's version in the URL. This is useful when reporting issues related to a specific version of Svelte.
We will provide a REPL at the beginning and end of each article so that you can start coding with us right away.
**Note:** At the moment the REPL can't handle folder names properly. If you are following the tutorial on the REPL, just create all your components inside the root folder. Then when you see a path in the code, for example `import Todos from './components/Todos.svelte'`, just replace it with a flat URL, e.g. `import Todos from './Todos.svelte'`.
The code so far
---------------
### Git
Clone the GitHub repo (if you haven't already done it) with:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then to get to the current app state, run
```bash
cd mdn-svelte-tutorial/01-getting-started
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/01-getting-started
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To code along with us using the REPL, start at
https://svelte.dev/repl/fc68b4f059d34b9c84fa042d1cce586c?version=3.23.2
Summary
-------
This brings us to the end of our initial look at Svelte, including how to install it locally, create a starter app, and how the basics work. In the next article we'll start building our first proper application, a todo list. Before we do that, however, let's recap some of the things we've learned.
In Svelte:
* We define the script, style, and markup of each component in a single `.svelte` file.
* Component props are declared with the `export` keyword.
* Svelte components can be used just by importing the corresponding `.svelte` file.
* Components styles are scoped, keeping them from clashing with each other.
* In the markup section you can include any JavaScript expression by putting it between curly braces.
* The top-level variables of a component constitute its state.
* Reactivity is fired just by assigning a new value to a top-level variable.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Routing in Ember - Learn web development | Routing in Ember
================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
In this article we learn about **routing**, or URL-based filtering as it is sometimes referred to. We'll use it to provide a unique URL for each of the three todo views β "All", "Active", and "Completed".
| | |
| --- | --- |
| Prerequisites: |
At minimum, it is recommended that you are familiar with the core
HTML,
CSS, and
JavaScript languages, and
have knowledge of the
terminal/command line.
A deeper understanding of modern JavaScript features (such as classes,
modules, etc.), will be extremely beneficial, as Ember makes heavy use
of them.
|
| Objective: | To learn about implementing routing in Ember. |
URL-based filtering
-------------------
Ember comes with a routing system that has a tight integration with the browser URL. Typically, when writing web applications, you want the page to be represented by the URL so that if (for any reason), the page needs to refresh, the user isn't surprised by the state of the web app β they can link directly to significant views of the app.
At the moment, we already have the "All" page, as we are currently not doing any filtering in the page that we've been working with, but we will need to reorganize it a bit to handle a different view for the "Active" and "Completed" todos.
An Ember application has a default "application" route, which is tied to the `app/templates/application.hbs` template. Because that application template is the entry point to our todo app, we'll need to make some changes to allow for routing.
Creating the routes
-------------------
Let's start by creating three new routes: "Index", "Active" and "Completed". To do this you'll need to enter the following commands into your terminal, inside the root directory of your app:
```bash
ember generate route index
ember generate route completed
ember generate route active
```
The second and third commands should have not only generated new files, but also updated an existing file, `app/router.js`. It contains the following contents:
```js
import EmberRouter from "@ember/routing/router";
import config from "./config/environment";
export default class Router extends EmberRouter {
location = config.locationType;
rootURL = config.rootURL;
}
Router.map(function () {
this.route("completed");
this.route("active");
});
```
The highlighted lines were added when the 2nd and 3rd commands above were run.
`router.js` behaves as a "sitemap" for developers to be able to quickly see how the entire app is structured. It also tells Ember how to interact with your route, such as when loading arbitrary data, handling errors while loading that data, or interpreting dynamic segments of the URL. Since our data is static, we won't get to any of those fancy features, but we'll still make sure that the route provides the minimally required data to view a page.
Creating the "Index" route did not add a route definition line to `router.js`, because like with URL navigation and JavaScript module loading, "Index" is a special word that indicates the default route to render, load, etc.
To adjust our old way of rendering the TodoList app, we'll first need to replace the TodoList component invocation from the application template with an `{{outlet}}` call, which means "any sub-route will be rendered in place here".
Go to the `todomvc/app/templates/application.hbs` file and replace
```hbs
<TodoList />
```
With
```hbs
{{outlet}}
```
Next, in our `index.hbs`, `completed.hbs`, and `active.hbs` templates (also found in the templates directory) we can for now just enter the TodoList component invocation.
In each case, replace
```hbs
{{outlet}}
```
with
```hbs
<TodoList />
```
So at this point, if you try the app again and visit any of the three routes
`localhost:4200 localhost:4200/active localhost:4200/completed`
you'll see exactly the same thing. At each URL, the template that corresponds to the specific path ("Active", "Completed", or "Index"), will render the `<TodoList />` component. The location in the page where `<TodoList />` is rendered is determined by the `{{ outlet }}` inside the parent route, which in this case is `application.hbs`. So we have our routes in place. Great!
But now we need a way to differentiate between each of these routes, so that they show what they are supposed to show.
First of all, return once more to our `todo-data.js` file. It already contains a getter that returns all todos, and a getter that returns incomplete todos. The getter we are missing is one to return just the completed todos. Add the following below the existing getters:
```js
get completed() {
return this.todos.filter((todo) => todo.isCompleted);
}
```
Models
------
Now we need to add models to our route JavaScript files to allow us to easily return specific data sets to display in those models. `model` is a data loading lifecycle hook. For TodoMVC, the capabilities of model aren't that important to us; you can find more information in the Ember model guide if you want to dig deeper. We also provide access to the service, like we did for the components.
### The index route model
First of all, update `todomvc/app/routes/index.js` so it looks as follows:
```js
import Route from "@ember/routing/route";
import { inject as service } from "@ember/service";
export default class IndexRoute extends Route {
@service("todo-data") todos;
model() {
let todos = this.todos;
return {
get allTodos() {
return todos.all;
},
};
}
}
```
We can now update the `todomvc/app/templates/index.hbs` file so that when it includes the `<TodoList />` component, it does so explicitly with the available model, calling its `allTodos()` getter to make sure all of the todos are shown.
In this file, change
```hbs
<TodoList />
```
To
```hbs
<TodoList @todos={{ @model.allTodos }} />
```
### The completed route model
Now update `todomvc/app/routes/completed.js` so it looks as follows:
```js
import Route from "@ember/routing/route";
import { inject as service } from "@ember/service";
export default class CompletedRoute extends Route {
@service("todo-data") todos;
model() {
let todos = this.todos;
return {
get completedTodos() {
return todos.completed;
},
};
}
}
```
We can now update the `todomvc/app/templates/completed.hbs` file so that when it includes the `<TodoList />` component, it does so explicitly with the available model, calling its `completedTodos()` getter to make sure only the completed todos are shown.
In this file, change
```hbs
<TodoList />
```
To
```hbs
<TodoList @todos={{ @model.completedTodos }} />
```
### The active route model
Finally for the routes, let's sort out our active route. Start by updating `todomvc/app/routes/active.js` so it looks as follows:
```js
import Route from "@ember/routing/route";
import { inject as service } from "@ember/service";
export default class ActiveRoute extends Route {
@service("todo-data") todos;
model() {
let todos = this.todos;
return {
get activeTodos() {
return todos.incomplete;
},
};
}
}
```
We can now update the `todomvc/app/templates/active.hbs` file so that when it includes the `<TodoList />` component, it does so explicitly with the available model, calling its `activeTodos()` getter to make sure only the active (incomplete) todos are shown.
In this file, change
```hbs
<TodoList />
```
To
```hbs
<TodoList @todos={{ @model.activeTodos }} />
```
Note that, in each of the route model hooks, we are returning an object with a getter instead of a static object, or more just the static list of todos (for example, `this.todos.completed`). The reason for this is that we want the template to have a dynamic reference to the todo list, and if we returned the list directly, the data would never re-compute, which would result in the navigations appearing to fail / not actually filter. By having a getter defined in the return object from the model data, the todos are re-looked-up so that our changes to the todo list are represented in the rendered list.
Getting the footer links working
--------------------------------
So our route functionality is now all in place, but we can't access them from our app. Let's get the footer links active so that clicking on them goes to the desired routes.
Go back to `todomvc/app/components/footer.hbs`, and find the following bit of markup:
```hbs
<a href="#">All</a>
<a href="#">Active</a>
<a href="#">Completed</a>
```
Update it to
```hbs
<LinkTo @route="index">All</LinkTo>
<LinkTo @route="active">Active</LinkTo>
<LinkTo @route="completed">Completed</LinkTo>
```
`<LinkTo>` is a built-in Ember component that handles all the state changes when navigating routes, as well as setting an "active" class on any link that matches the URL, in case there is a desire to style it differently from inactive links.
Updating the todos display inside TodoList
------------------------------------------
One small final thing that we need to fix is that previously, inside `todomvc/app/components/todo-list.hbs`, we were accessing the todo-data service directly and looping over all todos, as shown here:
```hbs
{{#each this.todos.all as |todo| }}
```
Since we now want to have our TodoList component show a filtered list, we'll want to pass an argument to the TodoList component representing the "current list of todos", as shown here:
```hbs
{{#each @todos as |todo| }}
```
And that's it for this tutorial! Your app should now have fully working links in the footer that display the "Index"/default, "Active", and "Completed" routes.
![The todo list app, showing the routing working for all, active, and completed todos.](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing/todos-navigation.gif)
Summary
-------
Congratulations! You've finished this tutorial!
There is a lot more to be implemented before what we've covered here has parity with the original TodoMVC app, such as editing, deleting, and persisting todos across page reloads.
To see our finished Ember implementation, checkout the finished app folder in the repository for the code of this tutorial or see the live deployed version here. Study the code to learn more about Ember, and also check out the next article, which provides links to more resources and some troubleshooting advice.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Getting started with Ember - Learn web development | Getting started with Ember
==========================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
In our first Ember article we will look at how Ember works and what it's useful for, install the Ember toolchain locally, create a sample app, and then do some initial setup to get it ready for development.
| | |
| --- | --- |
| Prerequisites: |
At minimum, it is recommended that you are familiar with the core
HTML,
CSS, and
JavaScript languages, and
have knowledge of the
terminal/command line.
A deeper understanding of modern JavaScript features (such as classes,
modules, etc.), will be extremely beneficial, as Ember makes heavy use
of them.
|
| Objective: | To learn how to install Ember, and create a starter app. |
Introducing Ember
-----------------
Ember is a component-service framework that focuses on the overall web application development experience, minimizing the trivial differences between applications β all while being a modern and light layer on top of native JavaScript. Ember also has immense backwards and forwards compatibility to help businesses stay up to date with the latest versions of Ember and latest community-driven conventions.
What does it mean to be a component-service framework? Components are individual bundles of behavior, style, and markup β much like what other frontend frameworks provide, such as React, Vue, and Angular. The service side provides long-lived shared state, behavior, and an interface to integrating with other libraries or systems. For example, the Router (which will be mentioned later in this tutorial) is a service. Components and Services make up the majority of any EmberJS application.
Use cases
---------
Generally, EmberJS works well for building apps that desire either or both of the following traits:
* Single Page Applications, including native-like web apps, and progressive web apps (PWAs)
+ Ember works best when it is the entire front end of your application.
* Increasing cohesion among many team's technology stacks
+ Community-backed "best practices" allow for faster long-term development speed.
+ Ember has clear conventions that are useful for enforcing consistency and helping team members get up to speed quickly.
### Ember with add-ons
EmberJS has a plugin architecture, which means that add-ons can be installed and provide additional functionality without much, if any, configuration.
Examples include:
* PREmber: Static website rendering for blogs or marketing content.
* FastBoot: Server-side rendering, including improving search-engine optimization (SEO), or improving initial render performance of complex, highly interactive web pages.
* empress-blog: Authoring blog posts in markdown while optimizing for SEO with PREmber.
* ember-service-worker: Configuring a PWA so that the app can be installed on mobile devices, just like apps from the device's respective app-store.
### Native mobile apps
Ember can also be used with native mobile apps with a native-mobile bridge to JavaScript, such as that provided by Corber.
Opinions
--------
EmberJS is one of the most opinionated front-end frameworks out there. But what does it mean to be opinionated? In Ember, opinions are a set of conventions that help increase the efficiency of developers at the cost of having to learn those conventions. As conventions are defined and shared, the opinions that back those conventions help reduce the menial differences between apps β a common goal among all opinionated frameworks, across any language and ecosystem. Developers are then more easily able to switch between projects and applications without having to completely relearn the architecture, patterns, conventions, etc.
As you work through this series of tutorials, you'll notice Ember's opinions β such as strict naming conventions of component files.
How does Ember relate to vanilla JavaScript?
--------------------------------------------
Ember is built on JavaScript technologies and is a thin layer on top of traditional object-oriented programming, while still allowing developers to utilize functional programming techniques.
Ember makes use of two main syntaxes:
* JavaScript (or optionally, TypeScript)
* Ember's own templating language, which is loosely based on Handlebars.
The templating language is used to make build and runtime optimizations that otherwise wouldn't be possible. Most importantly, it is a superset of HTML β meaning that anyone who knows HTML can make meaningful contributions to any Ember project with minimal fear of breaking code. Designers and other non-developers can contribute to page templates without any knowledge of JavaScript, and interactivity can be added later.
This language also enables lighter asset payloads due to *compiling* the templates into a "byte code" that can be parsed faster than JavaScript. The **Glimmer VM** enables extremely fast DOM change tracking without the need to manage and diff a cached virtual representation (which is a common approach to mitigating the slow I/O of DOM changes).
For more information on the technical aspects of The Glimmer VM, the GitHub repository has some documentation β specifically, References and Validators may be of interest.
Everything else in Ember is *just* JavaScript. In particular, JavaScript classes. This is where most of the "framework" parts come into play, as there are superclasses, where each type of *thing* has a different purpose and different expected location within your project.
Here is a demonstration the impact Ember has on the JavaScript that is in typical projects:
Gavin Demonstrates how < 20% of the JS written is specific to Ember.
![a set of code files with the ember-specific JavaScript highlighted, showing that only 20% of the Ember code is Ember-specific](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started/20percent-js-specific-ember.png)
Getting started
---------------
The rest of the Ember material you'll find here consists of a multi-part tutorial, in which we'll make a version of the classic TodoMVC sample app, teaching you how to use the essentials of the Ember framework along the way. TodoMVC is a basic to-do tracking app implemented in many different technologies.
Here is the completed Ember version, for reference.
### A note on TodoMVC and accessibility
The TodoMVC project has a few issues in terms of adhering to accessible/default web practices. There are a couple of GitHub issues open about this on the TodoMVC family of projects:
* Add keyboard access to demos
* Re-enable Outline on focusable elements
Ember has a strong commitment to being accessible by default and there is an entire section of the Ember Guides on accessibility on what it means for website / app design.
That said, because this tutorial is a focus on the JavaScript side of making a small web application, TodoMVC's value comes from providing pre-made CSS and recommended HTML structure, which eliminates small differences between implementations, allowing for easier comparison. Later on in the tutorial, we'll focus on adding code to our application to fix some of TodoMVC's biggest faults.
Installing the Ember tooling
----------------------------
Ember uses a command-line interface (CLI) tool for building and scaffolding parts of your application.
1. You'll need node and npm installed before you can install ember-cli. Go here to find out how to install node and npm, if you haven't already got them.
2. Now type the following into your terminal to install ember-cli:
```bash
npm install -g ember-cli
```
This tool provides the `ember` program in your terminal, which is used to create, build, develop, test, and scaffold your application (run `ember --help` for a full list of commands and their options).
3. To create a brand new application, type the following in your terminal. This creates a new directory inside the current directory you are in called todomvc, containing the scaffolding for a new Ember app. Make sure you navigate to somewhere appropriate in the terminal before you run it. (Good suggestions are your "desktop" or "documents" directories, so that it is easy to find):
```bash
ember new todomvc
```
Or, on Windows:
```bash
npx ember-cli new todomvc
```
This generates a production-ready application development environment that includes the following features by default:
* Development server with live reload.
* Plugin-architecture that allows for third-party packages to richly enhance your application.
* The latest JavaScript via Babel and Webpack integration.
* Automated testing environment that runs your tests in the browser, allowing you to *test like a user*.
* Transpilation, and minification, of both CSS and JavaScript for production builds.
* Conventions for minimizing the differences between applications (allowing easier mental context switching).
Getting ready to build our Ember project
----------------------------------------
You'll need a code editor before continuing to interact with your brand new project. If you don't have one configured already, The Ember Atlas has some guides on how to set up various editors.
### Installing the shared assets for TodoMVC projects
Installing shared assets, as we're about to do, isn't normally a required step for new projects, but it allows us to use existing shared CSS so we don't need to try to guess at what CSS is needed to create the TodoMVC styles.
1. First, enter into your `todomvc` directory in the terminal, for example using `cd todomvc` in macOS/Linux.
2. Now run the following command to place the common todomvc CSS inside your app:
```bash
npm install --save-dev todomvc-app-css todomvc-common
```
3. Next, find the ember-cli-build.js file inside the todomvc directory (it's right there inside the root) and open it in your chosen code editor. ember-cli-build.js is responsible for configuring details about how your project is built β including bundling all your files together, asset minification, and creating sourcemaps β with reasonable defaults, so you don't typically need to worry about this file.
We will however add lines to the ember-cli-build.js file to import our shared CSS files, so that they become part of our build without having to explicitly `@import` them into the `app.css` file (this would require URL rewrites at build time and therefore be less efficient and more complicated to set up).
4. In `ember-cli-build.js`, find the following code:
```js
let app = new EmberApp(defaults, {
// Add options here
});
```
5. Add the following lines underneath it before saving the file:
```js
app.import("node\_modules/todomvc-common/base.css");
app.import("node\_modules/todomvc-app-css/index.css");
```
For more information on what `ember-cli-build.js` does, and for other ways in which you can customize your build / pipeline, the Ember Guides have a page on Addons and Dependencies.
6. Finally, find `app.css`, located at `app/styles/app.css`, and paste in the following:
```css
:focus,
.view label:focus,
.todo-list li .toggle:focus + label,
.toggle-all:focus + label {
/\* !important needed because todomvc styles deliberately disable the outline \*/
outline: #d86f95 solid !important;
}
```
This CSS overrides some of the styles provided by the `todomvc-app-css` npm package, therefore allowing keyboard focus to be visible. This goes some way towards fixing one of the major accessibility disadvantages of the default TodoMVC app.
### Starting the development server
You may start the app in *development* mode by typing the following command in your terminal, while inside the `todomvc` directory:
```bash
ember server
```
This should give you an output similar to the following:
```
Build successful (190ms) β Serving on http://localhost:4200/
Slowest Nodes (totalTime >= 5%) | Total (avg)
-----------------------------------------+-----------
BroccoliMergeTrees (17) | 35ms (2 ms)
Package /assets/vendor.js (1) | 13ms
Concat: Vendor Styles/assets/vend... (1) | 12ms
```
The development server launches at `http://localhost:4200`, which you can visit in your browser to check out what your work looks like so far.
If everything is working correctly, you should see a page like this:
![The default start page when you create a new Ember app, with a cartoon mascot, saying congratulations](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started/ember-start-page.png)
**Note:** on Windows systems without Windows Subsystem for Linux (WSL), you will experience slower build-times overall compared to macOS, Linux, and Windows *with* WSL.
Summary
-------
So far so good. We've got to the point where we can start build up our sample TodoMVC app in Ember. In the next article we'll look at building up the markup structure of our app, as a group of logical components.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Dynamic behavior in Svelte: working with variables and props - Learn web development | Dynamic behavior in Svelte: working with variables and props
============================================================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
Now that we have our markup and styles ready, we can start developing the required features for our Svelte to-do list app. In this article we'll be using variables and props to make our app dynamic, allowing us to add and delete to-dos, mark them as complete, and filter them by status.
| | |
| --- | --- |
| Prerequisites: |
At minimum, it is recommended that you are familiar with the core
HTML,
CSS, and
JavaScript languages, and
have knowledge of the
terminal/command line.
You'll need a terminal with node and npm installed to compile and build
your app.
|
| Objective: |
Learn and put into practice some basic Svelte concepts, like creating
components, passing data using props, rendering JavaScript expressions into
our markup, modifying the components' state, and iterating over lists.
|
Code along with us
------------------
### Git
Clone the GitHub repo (if you haven't already done it) with:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then to get to the current app state, run
```bash
cd mdn-svelte-tutorial/03-adding-dynamic-behavior
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/03-adding-dynamic-behavior
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To code along with us using the REPL, start at
https://svelte.dev/repl/c862d964d48d473ca63ab91709a0a5a0?version=3.23.2
Working with to-dos
-------------------
Our `Todos.svelte` component is currently just displaying static markup; let's start making it a bit more dynamic. We'll take the tasks information from the markup and store it in a `todos` array. We'll also create two variables to keep track of the total number of tasks and the completed tasks.
The state of our component will be represented by these three top-level variables.
1. Create a `<script>` section at the top of `src/components/Todos.svelte` and give it some content, as follows:
```svelte
<script>
let todos = [
{ id: 1, name: "Create a Svelte starter app", completed: true },
{ id: 2, name: "Create your first component", completed: true },
{ id: 3, name: "Complete the rest of the tutorial", completed: false }
];
let totalTodos = todos.length;
let completedTodos = todos.filter((todo) => todo.completed).length;
</script>
```
Now let's do something with that information.
2. Let's start by showing a status message. Find the `<h2>` heading with an `id` of `list-heading` and replace the hardcoded number of active and completed tasks with dynamic expressions:
```svelte
<h2 id="list-heading">{completedTodos} out of {totalTodos} items completed</h2>
```
3. Go to the app, and you should see the "2 out of 3 items completed" message as before, but this time the information is coming from the `todos` array.
4. To prove it, go to that array, and try changing some of the to-do object's completed property values, and even add a new to-do object. Observe how the numbers in the message are updated appropriately.
Dynamically generating the to-dos from the data
-----------------------------------------------
At the moment, our displayed to-do items are all static. We want to iterate over each item in our `todos` array and render the markup for each task, so let's do that now.
HTML doesn't have a way of expressing logic β like conditionals and loops. Svelte does. In this case we use the `{#each}` directive to iterate over the `todos` array. The second parameter, if provided, will contain the index of the current item. Also, a key expression can be provided, which will uniquely identify each item. Svelte will use it to diff the list when data changes, rather than adding or removing items at the end, and it's a good practice to always specify one. Finally, an `:else` block can be provided, which will be rendered when the list is empty.
Let's give it a try.
1. Replace the existing `<ul>` element with the following simplified version to get an idea of how it works:
```svelte
<ul>
{#each todos as todo, index (todo.id)}
<li>
<input type="checkbox" checked={todo.completed}/> {index}. {todo.name} (id: {todo.id})
</li>
{:else}
Nothing to do here!
{/each}
</ul>
```
2. Go back to the app; you'll see something like this:
![very simple to-do list output created using an each block](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_variables_props/01-each-block.png)
3. Now that we've seen that this is working, let's generate a complete to-do item with each loop of the `{#each}` directive, and inside embed the information from the `todos` array: `id`, `name`, and `completed`. Replace your existing `<ul>` block with the following:
```svelte
<!-- To-dos -->
<ul role="list" class="todo-list stack-large" aria-labelledby="list-heading">
{#each todos as todo (todo.id)}
<li class="todo">
<div class="stack-small">
<div class="c-cb">
<input
type="checkbox"
id="todo-{todo.id}"
checked={todo.completed} />
<label for="todo-{todo.id}" class="todo-label"> {todo.name} </label>
</div>
<div class="btn-group">
<button type="button" class="btn">
Edit <span class="visually-hidden">{todo.name}</span>
</button>
<button type="button" class="btn btn\_\_danger">
Delete <span class="visually-hidden">{todo.name}</span>
</button>
</div>
</div>
</li>
{:else}
<li>Nothing to do here!</li>
{/each}
</ul>
```
Notice how we are using curly braces to embed JavaScript expressions in HTML attributes, like we did with the `checked` and `id` attributes of the checkbox.
We've turned our static markup into a dynamic template ready to display the tasks from our component's state. Great! We are getting there.
Working with props
------------------
With a hardcoded list of to-dos, our `Todos` component is not very useful. To turn our component into a general purpose to-do editor, we should allow the parent of this component to pass in the list of to-dos to edit. This would allow us to save them to a web service or local storage and later retrieve them for update. So let's turn the array into a `prop`.
1. In `Todos.svelte`, replace the existing `let todos = β¦` block with `export let todos = []`.
```js
export let todos = [];
```
This may feel a little weird at first. That's not how `export` normally works in JavaScript modules! This is how Svelte 'extends' JavaScript by taking valid syntax and giving it a new purpose. In this case Svelte is using the `export` keyword to mark a variable declaration as a property or prop, which means it becomes accessible to consumers of the component.
You can also specify a default initial value for a prop. This will be used if the component's consumer doesn't specify the prop on the component β or if its initial value is undefined β when instantiating the component.
So with `export let todos = []`, we are telling Svelte that our `Todos.svelte` component will accept a `todos` attribute, which when omitted will be initialized to an empty array.
2. Have a look at the app, and you'll see the "Nothing to do here!" message. This is because we are currently not passing any value into it from `App.svelte`, so it's using the default value.
3. Now let's move our to-dos to `App.svelte` and pass them to the `Todos.svelte` component as a prop. Update `src/App.svelte` as follows:
```svelte
<script>
import Todos from "./components/Todos.svelte";
let todos = [
{ id: 1, name: "Create a Svelte starter app", completed: true },
{ id: 2, name: "Create your first component", completed: true },
{ id: 3, name: "Complete the rest of the tutorial", completed: false }
];
</script>
<Todos todos={todos} />
```
4. When the attribute and the variable have the same name, Svelte allows you to just specify the variable as a handy shortcut, so we can rewrite our last line like this. Try this now.
```svelte
<Todos {todos} />
```
At this point your to-dos should render just like they did before, except that now we're passing them in from the `App.svelte` component.
Toggling and removing to-dos
----------------------------
Let's add some functionality to toggle the task status. Svelte has the `on:eventname` directive for listening to DOM events. Let's add a handler to the `on:click` event of the checkbox input to toggle the completed value.
1. Update the `<input type="checkbox">` element inside `src/components/Todos.svelte` as follows:
```svelte
<input type="checkbox" id="todo-{todo.id}"
on:click={() => todo.completed = !todo.completed}
checked={todo.completed}
/>
```
2. Next we'll add a function to remove a to-do from our `todos` array. At the bottom of the `<script>` section of `Todos.svelte`, add the `removeTodo()` function like so:
```js
function removeTodo(todo) {
todos = todos.filter((t) => t.id !== todo.id);
}
```
3. We'll call it via the *Delete* button. Update it with a `click` event, like so:
```svelte
<button type="button" class="btn btn\_\_danger"
on:click={() => removeTodo(todo)}
>
Delete <span class="visually-hidden">{todo.name}</span>
</button>
```
A very common mistake with handlers in Svelte is to pass the result of executing a function as a handler, instead of passing the function. For example, if you specify `on:click={removeTodo(todo)}`, it will execute `removeTodo(todo)` and the result will be passed as a handler, which is not what we had in mind.
In this case you have to specify `on:click={() => removeTodo(todo)}` as the handler. If `removeTodo()` received no params, you could use `on:event={removeTodo}`, but not `on:event={removeTodo()}`. This is not some special Svelte syntax β here we are just using regular JavaScript arrow functions.
Again, this is good progress β at this point, we can now delete tasks. When a to-do item's *Delete* button is pressed, the relevant to-do is removed from the `todos` array, and the UI updates to no longer show it. In addition, we can now check the checkboxes, and the completed status of the relevant to-dos will now update in the `todos` array.
However, the "x out of y items completed" heading is not being updated. Read on to find out why this is happening and how we can solve it.
Reactive to-dos
---------------
As we've already seen, every time the value of a component top-level variable is modified, Svelte knows how to update the UI. In our app, the `todos` array value is updated directly every time a to-do is toggled or deleted, and so Svelte will update the DOM automatically.
The same is not true for `totalTodos` and `completedTodos`, however. In the following code they are assigned a value when the component is instantiated and the script is executed, but after that, their values are not modified:
```js
let totalTodos = todos.length;
let completedTodos = todos.filter((todo) => todo.completed).length;
```
We could recalculate them after toggling and removing to-dos, but there's an easier way to do it.
We can tell Svelte that we want our `totalTodos` and `completedTodos` variables to be reactive by prefixing them with `$:`. Svelte will generate the code to automatically update them whenever data they depend on is changed.
**Note:** Svelte uses the `$:` JavaScript label statement syntax to mark reactive statements. Just like the `export` keyword being used to declare props, this may look a little alien. This is another example in which Svelte takes advantage of valid JavaScript syntax and gives it a new purpose β in this case to mean "re-run this code whenever any of the referenced values change". Once you get used to it, there's no going back.
Update your `totalTodos` and `completedTodos` variable definitions inside `src/components/Todos.svelte` to look like so:
```js
$: totalTodos = todos.length;
$: completedTodos = todos.filter((todo) => todo.completed).length;
```
If you check your app now, you'll see that the heading's numbers are updated when to-dos are completed or deleted. Nice!
Behind the scenes the Svelte compiler will parse and analyze our code to make a dependency tree, and then it will generate the JavaScript code to re-evaluate each reactive statement whenever one of their dependencies is updated. Reactivity in Svelte is implemented in a very lightweight and performant way, without using listeners, setters, getters, or any other complex mechanism.
Adding new to-dos
-----------------
Now on to the next major task for this article β let's add some functionality for adding new to-dos.
1. First we'll create a variable to hold the text of the new to-do. Add this declaration to the `<script>` section of `Todos.svelte` file:
```js
let newTodoName = "";
```
2. Now we will use this value in the `<input>` for adding new tasks. To do that we need to bind our `newTodoName` variable to the `todo-0` input, so that the `newTodoName` variable value stays in sync with the input's `value` property. We could do something like this:
```svelte
<input value={newTodoName} on:keydown={(e) => newTodoName = e.target.value} />
```
Whenever the value of the variable `newTodoName` changes, it will be reflected in the `value` attribute of the input, and whenever a key is pressed in the input, we will update the contents of the variable `newTodoName`.
This is a manual implementation of two-way data binding for an input box. But we don't need to do this β Svelte provides an easier way to bind any property to a variable, using the `bind:property` directive:
```svelte
<input bind:value={newTodoName} />
```
So, let's implement this. Update the `todo-0` input like so:
```svelte
<input
bind:value={newTodoName}
type="text"
id="todo-0"
autocomplete="off"
class="input input\_\_lg" />
```
3. An easy way to test that this works is to add a reactive statement to log the contents of `newTodoName`. Add this snippet at the end of the `<script>` section:
```js
$: console.log("newTodoName: ", newTodoName);
```
**Note:** As you may have noticed, reactive statements aren't limited to variable declarations. You can put *any* JavaScript statement after the `$:` sign.
4. Now try going back to `localhost:5042`, pressing `Ctrl` + `Shift` + `K` to open your browser console and typing something into the input field. You should see your entries logged. At this point, you can delete the reactive `console.log()` if you wish.
5. Next up we'll create a function to add the new to-do β `addTodo()` β which will push a new `todo` object onto the `todos` array. Add this to the bottom of your `<script>` block inside `src/components/Todos.svelte`:
```js
function addTodo() {
todos.push({ id: 999, name: newTodoName, completed: false });
newTodoName = "";
}
```
**Note:** For the moment we are just assigning the same `id` to every to-do, but don't worry, we will fix that soon.
6. Now we want to update our HTML so that we call `addTodo()` whenever the form is submitted. Update the NewTodo form's opening tag like so:
```svelte
<form on:submit|preventDefault={addTodo}>
```
The `on:eventname` directive supports adding modifiers to the DOM event with the `|` character. In this case, the `preventDefault` modifier tells Svelte to generate the code to call `event.preventDefault()` before running the handler. Explore the previous link to see what other modifiers are available.
7. If you try adding new to-dos at this point, the new to-dos are added to the to-dos array, but our UI is not updated. Remember that in Svelte reactivity is triggered with assignments. That means that the `addTodo()` function is executed, the element is added to the `todos` array, but Svelte won't detect that the push method modified the array, so it won't refresh the tasks `<ul>`.
Just adding `todos = todos` to the end of the `addTodo()` function would solve the problem, but it seems strange to have to include that at the end of the function. Instead, we'll take out the `push()` method and use spread syntax to achieve the same result: we'll assign a value to the `todos` array equal to the `todos` array plus the new object.
**Note:** `Array` has several mutable operations: `push()`, `pop()`, `splice()`, `shift()`, `unshift()`, `reverse()`, and `sort()`. Using them often causes side effects and bugs that are hard to track. By using the spread syntax instead of `push()` we avoid mutating the array, which is considered a good practice.
Update your `addTodo()` function like so:
```js
function addTodo() {
todos = [...todos, { id: 999, name: newTodoName, completed: false }];
newTodoName = "";
}
```
Giving each to-do a unique ID
-----------------------------
If you try to add new to-dos in your app now, you'll be able to add a new to-do and have it appear in the UI β once. If you try it a second time, it won't work, and you'll get a console message saying "Error: Cannot have duplicate keys in a keyed each". We need unique IDs for our to-dos.
1. Let's declare a `newTodoId` variable calculated from the number of to-dos plus 1, and make it reactive. Add the following snippet to the `<script>` section:
```js
let newTodoId;
$: {
if (totalTodos === 0) {
newTodoId = 1;
} else {
newTodoId = Math.max(...todos.map((t) => t.id)) + 1;
}
}
```
**Note:** As you can see, reactive statements are not limited to one-liners. The following would work too, but it is a little less readable: `$: newTodoId = totalTodos ? Math.max(...todos.map((t) => t.id)) + 1 : 1`
2. How does Svelte achieve this? The compiler parses the whole reactive statement, and detects that it depends on the `totalTodos` variable and the `todos` array. So whenever either of them is modified, this code is re-evaluated, updating `newTodoId` accordingly.
Let's use this in our `addTodo()` function. Update it like so:
```js
function addTodo() {
todos = [...todos, { id: newTodoId, name: newTodoName, completed: false }];
newTodoName = "";
}
```
Filtering to-dos by status
--------------------------
Finally for this article, let's implement the ability to filter our to-dos by status. We'll create a variable to hold the current filter, and a helper function that will return the filtered to-dos.
1. At the bottom of our `<script>` section add the following:
```js
let filter = "all";
const filterTodos = (filter, todos) =>
filter === "active"
? todos.filter((t) => !t.completed)
: filter === "completed"
? todos.filter((t) => t.completed)
: todos;
```
We use the `filter` variable to control the active filter: *all*, *active*, or *completed*. Just assigning one of these values to the filter variable will activate the filter and update the list of to-dos. Let's see how to achieve this.
The `filterTodos()` function will receive the current filter and the list of to-dos, and return a new array of to-dos filtered accordingly.
2. Let's update the filter button markup to make it dynamic and update the current filter when the user presses one of the filter buttons. Update it like this:
```svelte
<div class="filters btn-group stack-exception">
<button class="btn toggle-btn" class:btn\_\_primary={filter === 'all'} aria-pressed={filter === 'all'} on:click={() => filter = 'all'} >
<span class="visually-hidden">Show</span>
<span>All</span>
<span class="visually-hidden">tasks</span>
</button>
<button class="btn toggle-btn" class:btn\_\_primary={filter === 'active'} aria-pressed={filter === 'active'} on:click={() => filter = 'active'} >
<span class="visually-hidden">Show</span>
<span>Active</span>
<span class="visually-hidden">tasks</span>
</button>
<button class="btn toggle-btn" class:btn\_\_primary={filter === 'completed'} aria-pressed={filter === 'completed'} on:click={() => filter = 'completed'} >
<span class="visually-hidden">Show</span>
<span>Completed</span>
<span class="visually-hidden">tasks</span>
</button>
</div>
```
There are a couple of things going on in this markup.
We will show the current filter by applying the `btn__primary` class to the active filter button. To conditionally apply style classes to an element we use the `class:name={value}` directive. If the value expression evaluates to truthy, the class name will be applied. You can add many of these directives, with different conditions, to the same element. So when we issue `class:btn__primary={filter === 'all'}`, Svelte will apply the `btn__primary` class if filter equals all.
**Note:** Svelte provides a shortcut which allows us to shorten `<div class:active={active}>` to `<div class:active>` when the class matches the variable name.
Something similar happens with `aria-pressed={filter === 'all'}`: when the JavaScript expression passed between curly braces evaluates to a truthy value, the `aria-pressed` attribute will be added to the button.
Whenever we click on a button, we update the filter variable by issuing `on:click={() => filter = 'all'}`. Read on to find out how Svelte reactivity will take care of the rest.
3. Now we just need to use the helper function in the `{#each}` loop; update it like this:
```svelte
β¦
<ul role="list" class="todo-list stack-large" aria-labelledby="list-heading">
{#each filterTodos(filter, todos) as todo (todo.id)}
β¦
```
After analyzing our code, Svelte detects that our `filterTodos()` function depends on the variables `filter` and `todos`. And, just like with any other dynamic expression embedded in the markup, whenever any of these dependencies changes, the DOM will be updated accordingly. So whenever `filter` or `todos` changes, the `filterTodos()` function will be re-evaluated and the items inside the loop will be updated.
**Note:** Reactivity can be tricky sometimes. Svelte recognizes `filter` as a dependency because we are referencing it in the `filterTodos(filter, todo)` expression. `filter` is a top-level variable, so we might be tempted to remove it from the helper function params, and just call it like this: `filterTodos(todo)`. This would work, but now Svelte has no way to find out that `{#each filterTodos(todos) }` depends on `filter`, and the list of filtered to-dos won't be updated when the filter changes. Always remember that Svelte analyzes our code to find out dependencies, so it's better to be explicit about it and not rely on the visibility of top-level variables. Besides, it's a good practice to make our code clear and explicit about what information it is using.
The code so far
---------------
### Git
To see the state of the code as it should be at the end of this article, access your copy of our repo like this:
```bash
cd mdn-svelte-tutorial/04-componentizing-our-app
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/04-componentizing-our-app
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To see the current state of the code in a REPL, visit:
https://svelte.dev/repl/99b9eb228b404a2f8c8959b22c0a40d3?version=3.23.2
Summary
-------
That will do for now! In this article we already implemented most of our desired functionality. Our app can display, add, and delete to-dos, toggle their completed status, show how many of them are completed, and apply filters.
To recap, we covered the following topics:
* Creating and using components
* Turning static markup into a live template
* Embedding JavaScript expressions in our markup
* Iterating over lists using the `{#each}` directive
* Passing information between components with props
* Listening to DOM events
* Declaring reactive statements
* Basic debugging with `console.log()` and reactive statements
* Binding HTML properties with the `bind:property` directive
* Triggering reactivity with assignments
* Using reactive expressions to filter data
* Explicitly defining our reactive dependencies
In the next article we will add further functionality, which will allow users to edit to-dos.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Rendering a list of Vue components - Learn web development | Rendering a list of Vue components
==================================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
At this point we've got a fully working component; we're now ready to add multiple `ToDoItem` components to our app. In this article we'll look at adding a set of todo item data to our `App.vue` component, which we'll then loop through and display inside `ToDoItem` components using the `v-for` directive.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with node + npm installed.
|
| Objective: |
To learn how to loop through an array of data and render it in multiple
components.
|
Rendering lists with v-for
--------------------------
To be an effective to-do list, we need to be able to render multiple to-do items. To do that, Vue has a special directive, `v-for`. This is a built-in Vue directive that lets us include a loop inside of our template, repeating the rendering of a template feature for each item in an array. We'll use this to iterate through an array of to-do items and display them in our app in separate `ToDoItem` components.
### Adding some data to render
First we need to get an array of to-do items. To do that, we'll add a `data` property to the `App.vue` component object, containing a `ToDoItems` field whose value is an array of todo items. While we'll eventually add a mechanism to add new todo items, we can start with some mock to do items. Each to-do item will be represented by an object with a `label` and a `done` property.
Add a few sample to-do items, along the lines of those seen below. This way you have some data available for rendering using `v-for`.
```js
export default {
name: "app",
components: {
ToDoItem,
},
data() {
return {
ToDoItems: [
{ label: "Learn Vue", done: false },
{ label: "Create a Vue project with the CLI", done: true },
{ label: "Have fun", done: true },
{ label: "Create a to-do list", done: false },
],
};
},
};
```
Now that we have a list of items, we can use the `v-for` directive to display them. Directives are applied to elements like other attributes. In case of `v-for`, you use a special syntax similar to a `for...in` loop in JavaScript β `v-for="item in items"` β where `items` is the array you want to iterate over, and `item` is a reference to the current element in the array.
`v-for` attaches to the element you want to repeat, and renders that element and its children. In this case, we want to display an `<li>` element for every to-do item inside our `ToDoItems` array. Then we want to pass the data from each to-do item to a `ToDoItem` component.
### Key attribute
Before we do that, there's one other piece of syntax to know about that is used with `v-for`, the `key` attribute. To help Vue optimize rendering the elements in the list, it tries to patch list elements so it's not recreating them every time the list changes. However, Vue needs help. To make sure it is re-using list elements appropriately, it needs a unique "key" on the same element that you attach `v-for` to.
To make sure that Vue can accurately compare the `key` attributes, they need to be string or numeric values. While it would be great to use the name field, this field will eventually be controlled by user input, which means we can't guarantee that the names would be unique. We could use `lodash.uniqueid()`, however, like we did in the previous article.
1. Import `lodash.uniqueid` into your `App` component in the same way you did with your `ToDoItem` component, using
```js
import uniqueId from "lodash.uniqueid";
```
2. Next, add an `id` field to each element in your `ToDoItems` array, and assign each of them a value of `uniqueId('todo-')`.
The `<script>` element in `App.vue` should now have the following contents:
```js
import ToDoItem from "./components/ToDoItem.vue";
import uniqueId from "lodash.uniqueid";
export default {
name: "app",
components: {
ToDoItem,
},
data() {
return {
ToDoItems: [
{ id: uniqueId("todo-"), label: "Learn Vue", done: false },
{
id: uniqueId("todo-"),
label: "Create a Vue project with the CLI",
done: true,
},
{ id: uniqueId("todo-"), label: "Have fun", done: true },
{ id: uniqueId("todo-"), label: "Create a to-do list", done: false },
],
};
},
};
```
3. Now, add the `v-for` directive and `key` attribute to the `<li>` element in your `App.vue` template, like so:
```html
<ul>
<li v-for="item in ToDoItems" :key="item.id">
<to-do-item label="My ToDo Item" :done="true"></to-do-item>
</li>
</ul>
```
When you make this change, every JavaScript expression between the `<li>` tags will have access to the `item` value in addition to the other component attributes. This means we can pass the fields of our item objects to our `ToDoItem` component β just remember to use the `v-bind` syntax. This is really useful, as we want our todo items to display their `label` properties as their label, not a static label of "My Todo Item". In addition, we want their checked status to reflect their `done` properties, not always be set to `done="true"`.
4. Update the `label="My ToDo Item"` attribute to `:label="item.label"`, and the `:done="true"` attribute to `:done="item.done"`, as seen in context below:
```html
<ul>
<li v-for="item in ToDoItems" :key="item.id">
<to-do-item :label="item.label" :done="item.done"></to-do-item>
</li>
</ul>
```
Now when you look at your running app, it'll show the todo items with their proper names, and if you inspect the source code you'll see that the inputs all have unique `id`s, taken from the object in the `App` component.
![The app with a list of todo items rendered.](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_rendering_lists/rendered-todo-items.png)
Chance for a slight refactor
----------------------------
There's one little bit of refactoring we can do here. Instead of generating the `id` for the checkboxes inside your `ToDoItem` component, we can turn the `id` into a prop. While this isn't strictly necessary, it makes it easier for us to manage since we already need to create a unique `id` for each todo item anyway.
1. Add a new prop to your `ToDoItem` component β `id`.
2. Make it required, and make its type a `String`.
3. To prevent name collisions, remove the `id` field from your `data` attribute.
4. You are no longer using `uniqueId`, so you need to remove the `import uniqueId from 'lodash.uniqueid';` line, otherwise your app will throw an error.
The `<script>` contents in your `ToDoItem` component should now look something like this:
```js
export default {
props: {
label: { required: true, type: String },
done: { default: false, type: Boolean },
id: { required: true, type: String },
},
data() {
return {
isDone: this.done,
};
},
};
```
Now, over in your `App.vue` component, pass `item.id` as a prop to the `ToDoItem` component. Your `App.vue` template should now look like this:
```html
<template>
<div id="app">
<h1>My To-Do List</h1>
<ul>
<li v-for="item in ToDoItems" :key="item.id">
<to-do-item
:label="item.label"
:done="item.done"
:id="item.id"></to-do-item>
</li>
</ul>
</div>
</template>
```
When you look at your rendered site, it should look the same, but our refactor now means that our `id` is being taken from the data inside `App.vue` and passed into `ToDoItem` as a prop, just like everything else, so things are now more logical and consistent.
Summary
-------
And that brings us to the end of another article. We now have sample data in place, and a loop that takes each bit of data and renders it inside a `ToDoItem` in our app.
What we really need next is the ability to allow our users to enter their own todo items into the app, and for that we'll need a text `<input>`, an event to fire when the data is submitted, a method to fire upon submission to add the data and rerender the list, and a model to control the data. We'll get to these in the next article.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Ember Interactivity: Footer functionality, conditional rendering - Learn web development | Ember Interactivity: Footer functionality, conditional rendering
================================================================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
Now it's time to start tackling the footer functionality in our app. Here we'll get the todo counter to update to show the correct number of todos still to complete, and correctly apply styling to completed todos (i.e. where the checkbox has been checked). We'll also wire up our "Clear completed" button. Along the way, we'll learn about using conditional rendering in our templates.
| | |
| --- | --- |
| Prerequisites: |
At minimum, it is recommended that you are familiar with the core
HTML,
CSS, and
JavaScript languages, and
have knowledge of the
terminal/command line.
A deeper understanding of modern JavaScript features (such as classes,
modules, etc.), will be extremely beneficial, as Ember makes heavy use
of them.
|
| Objective: |
To continue our learning about components classes, start looking at
conditional rendering, and wire up some of our footer functionality.
|
Connecting the behavior in the footer
-------------------------------------
To get the footer working, we need to implement the following three areas of functionality:
* A pending todo counter.
* Filters for all, active, and completed todos.
* A button to clear the completed todos.
1. Because we need access to our service from the footer component, we need to generate a class for the footer. Enter the following terminal command to do so:
```bash
ember generate component-class footer
```
2. Next, go and find the newly-created `todomvc/app/components/footer.js` file and update it to the following:
```js
import Component from "@glimmer/component";
import { inject as service } from "@ember/service";
export default class FooterComponent extends Component {
@service("todo-data") todos;
}
```
3. Now we need to go back to our `todo-data.js` file and add some functionality that will allow us to return the number of incomplete todos (useful for showing how many are left), and clear the completed todos out of the list (which is what the "Clear completed" functionality needs).
In `todo-data.js`, add the following getter underneath the existing `all()` getter to define what the incomplete todos actually are:
```js
get incomplete() {
return this.todos.filterBy('isCompleted', false);
}
```
Using Ember's `ArrayProxy.filterBy()` method, we're able to easily filter Objects in our array based on simple equals conditions. Here we're asking for all the todo items where the `isCompleted` property is equal to `false`, and because `isCompleted` is `@tracked` in our `Todo` object, this getter will re-compute when the value changes on an Object in the array.
4. Next, add the following action underneath the existing `add(text)` action:
```js
@action
clearCompleted() {
this.todos = this.incomplete;
}
```
This is rather nice for clearing the todos β we just need to set the `todos` array to equal the list of incomplete todos.
5. Finally, we need to make use of this new functionality in our `footer.hbs` template. Go to this file now.
6. First of all, replace this line:
```hbs
<strong>0</strong> todos left
```
With this, which populates the incomplete number with the length of the `incomplete` array:
```hbs
<strong>{{this.todos.incomplete.length}}</strong> todos left
```
7. Next, replace this:
```hbs
<button type="button" class="clear-completed">
```
With this:
```hbs
<button type="button" class="clear-completed" {{on 'click' this.todos.clearCompleted}}>
```
So now when the button is clicked, the `clearCompleted()` action we added earlier is run.
However, if you try to click the "Clear Completed" button now, it won't appear to do anything, because there is currently no way to "complete" a todo. We need to wire up the `todo.hbs` template to the service, so that checking the relevant checkbox changes the state of each todo. We'll do that next.
The todo/todos plural problem
-----------------------------
The above is fine, but we have another small issue to contend with. The "todos left" indicator always says "x todos left", even when there is only one todo left, which is bad grammar!
To fix this, we need to update this part of the template to include some conditional rendering. In Ember, you can conditionally render parts of the template using conditional content; a simple block example looks something like this:
```hbs
{{#if this.thingIsTrue}} Content for the block form of "if"
{{/if}}
```
So let's try replacing this part of `footer.hbs`:
```hbs
<strong>{{this.todos.incomplete.length}}</strong> todos left
```
with the following:
```hbs
<strong>{{this.todos.incomplete.length}}</strong>
{{#if this.todos.incomplete.length === 1}} todo
{{else}} todos
{{/if}} left
```
This will give us an error, however β in Ember, these simple if statements can currently only test for a truthy/falsy value, not a more complex expression such as a comparison. To fix this, we'll have to add a getter to `todo-data.js` to return the result of `this.incomplete.length === 1`, and then call that in our template.
Add the following new getter to `todo-data.js`, just below the existing getters. Note that here we need `this.incomplete.length`, not `this.todos.incomplete.length`, because we are doing this inside the service, where the `incomplete()` getter is available directly (in the template, the contents of the service has been made available as `todos` via the `@service('todo-data') todos;` line inside the footer class, hence it being `this.todos.incomplete.length` there).
```js
get todoCountIsOne() {
return this.incomplete.length === 1;
}
```
Then go back over to `footer.hbs` and update the previous template section we edited to the following:
```hbs
<strong>{{this.todos.incomplete.length}}</strong>
{{#if this.todos.todoCountIsOne}}todo{{else}}todos{{/if}} left
```
Now save and test, and you'll see the correct pluralization used when you only have one todo item present!
Note that this is the block form of `if` in Ember; you could also use the inline form:
```hbs
{{if this.todos.todoCountIsOne "todo" "todos"}}
```
Completing todos
----------------
As with the other components, we need a class to access the service.
### Creating a todo class
1. Run the following command in your terminal:
```bash
ember generate component-class todo
```
2. Now go to the newly-created `todomvc/app/components/todo.js` file and update the contents to look like so, to give the todo component access to the service:
```js
import Component from "@glimmer/component";
import { inject as service } from "@ember/service";
export default class TodoComponent extends Component {
@service("todo-data") todos;
}
```
3. Next, go back again to our `todo-data.js` service file and add the following action just below the previous ones, which will allow us to toggle a completion state for each todo:
```js
@action
toggleCompletion(todo) {
todo.isCompleted = !todo.isCompleted;
}
```
### Updating the template to show completed state
Finally, we will edit the `todo.hbs` template such that the checkbox's value is now bound to the `isCompleted` property on the todo, and so that on change, the `toggleCompletion()` method on the todo service is invoked.
1. In `todo.hbs`, first find the following line:
```hbs
<li>
```
And replace it with this β you'll notice that here we're using some more conditional content to add the class value if appropriate:
```hbs
<li class={{ if @todo.isCompleted 'completed' }}>
```
2. Next, find the following line:
```hbs
<input
aria-label="Toggle the completion of this todo"
class="toggle"
type="checkbox"
>
```
And replace it with this:
```hbs
<input
class="toggle"
type="checkbox"
aria-label="Toggle the completion of this todo"
checked={{ @todo.isCompleted }}
{{ on 'change' (fn this.todos.toggleCompletion @todo) }}
>
```
**Note:** The above snippet uses a new Ember-specific keyword β `fn`. `fn` allows for partial application, which is similar to `bind`, but it never changes the invocation context; this is equivalent to using `bind` with a `null` first argument.
Try restarting the dev server and going to `localhost:4200` again, and you'll now see that we have a fully-operational "todos left" counter and Clear button:
![todos being marked as complete, and cleared](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_conditional_footer/todos-being-marked-completed-and-cleared.gif)
If you're asking yourself why we're not just doing the toggle on the component, since the function is entirely self-contained and not at all needing anything from the service, then you are 100% right to ask that question! However, because \*eventually\*, we'll want to persist or sync all changes to the todos list to local storage (see the final version of the app), it makes sense to have all persistent-state-changing operations be in the same place.
Summary
-------
That's enough for now. At this point, not only can we mark todos as complete, but we can clear them as well. Now the only thing left to wire up the footer are the three filtering links: "All", "Active", and "Completed". We'll do that in the next article, using Routing.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
React interactivity: Events and state - Learn web development | React interactivity: Events and state
=====================================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
With our component plan worked out, it's now time to start updating our app from a completely static UI to one that actually allows us to interact and change things. In this article we'll do this, digging into events and state along the way, and ending up with an app in which we can successfully add and delete tasks, and toggle tasks as completed.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
|
| Objective: |
To learn about handling events and state in React, and use those to
start making the case study app interactive.
|
Handling events
---------------
If you've only written vanilla JavaScript before now, you might be used to having a separate JavaScript file in which you query for some DOM nodes and attach listeners to them. For example, an HTML file might have a button in it, like this:
```html
<button type="button">Say hi!</button>
```
And a JavaScript file might have some code like this:
```js
const btn = document.querySelector("button");
btn.addEventListener("click", () => {
alert("hi!");
});
```
In JSX, the code that describes the UI lives right alongside our event listeners:
```jsx
<button type="button" onClick={() => alert("hi!")}>
Say hi!
</button>
```
In this example, we're adding an `onClick` attribute to the `<button>` element. The value of that attribute is a function that triggers a simple alert. This may seem counter to best practice advice about not writing event listeners in HTML, but remember: JSX is not HTML.
The `onClick` attribute has special meaning here: it tells React to run a given function when the user clicks on the button. There are a couple of other things to note:
* The camel-cased nature of `onClick` is important β JSX will not recognize `onclick` (again, it is already used in JavaScript for a specific purpose, which is related but different β standard `onclick` handler properties).
* All browser events follow this format in JSX β `on`, followed by the name of the event.
Let's apply this to our app, starting in the `Form.jsx` component.
### Handling form submission
At the top of the `Form()` component function (i.e., just below the `function Form() {` line), create a function named `handleSubmit()`. This function should prevent the default behavior of the `submit` event. After that, it should trigger an `alert()`, which can say whatever you'd like. It should end up looking something like this:
```jsx
function handleSubmit(event) {
event.preventDefault();
alert("Hello, world!");
}
```
To use this function, add an `onSubmit` attribute to the `<form>` element, and set its value to the `handleSubmit` function:
```jsx
<form onSubmit={handleSubmit}>
```
Now if you head back to your browser and click on the "Add" button, your browser will show you an alert dialog with the words "Hello, world!" β or whatever you chose to write there.
Callback props
--------------
In React applications, interactivity is rarely confined to just one component: events that happen in one component will affect other parts of the app. When we start giving ourselves the power to make new tasks, things that happen in the `<Form />` component will affect the list rendered in `<App />`.
We want our `handleSubmit()` function to ultimately help us create a new task, so we need a way to pass information from `<Form />` to `<App />`. We can't pass data from child to parent in the same way as we pass data from parent to child using standard props. Instead, we can write a function in `<App />` that will expect some data from our form as an input, then pass that function to `<Form />` as a prop. This function-as-a-prop is called a **callback prop**. Once we have our callback prop, we can call it inside `<Form />` to send the right data to `<App />`.
### Handling form submission via callbacks
Inside the `App()` function in `App.jsx`, create a function named `addTask()` which has a single parameter of `name`:
```jsx
function addTask(name) {
alert(name);
}
```
Next, pass `addTask()` into `<Form />` as a prop. The prop can have whatever name you want, but pick a name you'll understand later. Something like `addTask` works, because it matches the name of the function as well as what the function will do. Your `<Form />` component call should be updated as follows:
```jsx
<Form addTask={addTask} />
```
To use this prop, we must change the signature of the `Form()` function in `Form.jsx` so that it accepts `props` as a parameter:
```jsx
function Form(props) {
// ...
}
```
Finally, we can use this prop inside the `handleSubmit()` function in your `<Form />` component! Update it as follows:
```jsx
function handleSubmit(event) {
event.preventDefault();
props.addTask("Say hello!");
}
```
Clicking on the "Add" button in your browser will prove that the `addTask()` callback function works, but it'd be nice if we could get the alert to show us what we're typing in our input field! This is what we'll do next.
### Aside: a note on naming conventions
We passed the `addTask()` function into the `<Form />` component as the prop `addTask` so that the relationship between the `addTask()` *function* and the `addTask` *prop* would remain as clear as possible. Keep in mind, though, that prop names do not *need* to be anything in particular. We could have passed `addTask()` into `<Form />` under any other name, such as this:
```diff
- <Form addTask={addTask} />
+ <Form onSubmit={addTask} />
```
This would make the `addTask()` function available to the `<Form />` component as the prop `onSubmit`. That prop could be used in `App.jsx` like this:
```diff
function handleSubmit(event) {
event.preventDefault();
- props.addTask("Say hello!");
+ props.onSubmit("Say hello!");
}
```
Here, the `on` prefix tells us that the prop is a callback function; `Submit` is our clue that a submit event will trigger this function.
While callback props often match the names of familiar event handlers, like `onSubmit` or `onClick`, they can be named just about anything that helps make their meaning clear. A hypothetical `<Menu />` component might include a callback function that runs when the menu is opened, as well as a separate callback function that runs when it's closed:
```jsx
<Menu onOpen={() => console.log("Hi!")} onClose={() => console.log("Bye!")} />
```
This `on*` naming convention is very common in the React ecosystem, so keep it in mind as you continue your learning. For the sake of clarity, we're going to stick with `addTask` and similar prop names for the rest of this tutorial. If you changed any prop names while reading this section, be sure to change them back before continuing!
Persisting and changing data with state
---------------------------------------
So far, we've used props to pass data through our components and this has served us just fine. Now that we're dealing with interactivity, however, we need the ability to create new data, retain it, and update it later. Props are not the right tool for this job because they are immutable β a component cannot change or create its own props.
This is where **state** comes in. If we think of props as a way to communicate between components, we can think of state as a way to give components "memory" β information they can hold onto and update as needed.
React provides a special function for introducing state to a component, aptly named `useState()`.
**Note:** `useState()` is part of a special category of functions called **hooks**, each of which can be used to add new functionality to a component. We'll learn about other hooks later on.
To use `useState()`, we need to import it from the React module. Add the following line to the top of your `Form.jsx` file, above the `Form()` function definition:
```jsx
import { useState } from "react";
```
`useState()` takes a single argument that determines the initial value of the state. This argument can be a string, a number, an array, an object, or any other JavaScript data type. `useState()` returns an array containing two items. The first item is the current value of the state; the second item is a function that can be used to update the state.
Let's create a `name` state. Write the following above your `handleSubmit()` function, inside `Form()`:
```jsx
const [name, setName] = useState("Learn React");
```
Several things are happening in this line of code:
* We are defining a `name` constant with the value `"Learn React"`.
* We are defining a function whose job it is to modify `name`, called `setName()`.
* `useState()` returns these two things in an array, so we are using array destructuring to capture them both in separate variables.
### Reading state
You can see the `name` state in action right away. Add a `value` attribute to the form's input, and set its value to `name`. Your browser will render "Learn React" inside the input.
```jsx
<input
type="text"
id="new-todo-input"
className="input input\_\_lg"
name="text"
autoComplete="off"
value={name}
/>
```
Change "Learn React" to an empty string once you're done; this is what we want for our initial state:
```jsx
const [name, setName] = useState("");
```
### Reading user input
Before we can change the value of `name`, we need to capture a user's input as they type. For this, we can listen to the `onChange` event. Let's write a `handleChange()` function, and listen for it on the `<input />` element.
```jsx
// near the top of the `Form` component
function handleChange() {
console.log("Typing!");
}
...
// Down in the return statement
<input
type="text"
id="new-todo-input"
className="input input\_\_lg"
name="text"
autoComplete="off"
value={name}
onChange={handleChange}
/>;
```
Currently, our input's value will not change when you try to enter text into it, but your browser will log the word "Typing!" to the JavaScript console, so we know our event listener is attached to the input.
To read the user's keystrokes, we must access the input's `value` property. We can do this by reading the `event` object that `handleChange()` receives when it's called. `event`, in turn, has a `target` property, which represents the element that fired the `change` event. That's our input. So, `event.target.value` is the text inside the input.
You can `console.log()` this value to see it in your browser's console. Try updating the `handleChange()` function as follows, and typing in the input to see the result in your console:
```jsx
function handleChange(event) {
console.log(event.target.value);
}
```
### Updating state
Logging isn't enough β we want to actually store what the user types and render it in the input! Change your `console.log()` call to `setName()`, as shown below:
```jsx
function handleChange(event) {
setName(event.target.value);
}
```
Now when you type in the input, your keystrokes will fill out the input, as you might expect.
We have one more step: we need to change our `handleSubmit()` function so that it calls `props.addTask` with `name` as an argument. Remember our callback prop? This will serve to send the task back to the `App` component, so we can add it to our list of tasks at some later date. As a matter of good practice, you should clear the input after your form is submitted, so we'll call `setName()` again with an empty string to do so:
```jsx
function handleSubmit(event) {
event.preventDefault();
props.addTask(name);
setName("");
}
```
At last, you can type something into the input field in your browser and click *Add* β whatever you typed will appear in an alert dialog.
Your `Form.jsx` file should now read like this:
```jsx
import { useState } from "react";
function Form(props) {
const [name, setName] = useState("");
function handleChange(event) {
setName(event.target.value);
}
function handleSubmit(event) {
event.preventDefault();
props.addTask(name);
setName("");
}
return (
<form onSubmit={handleSubmit}>
<h2 className="label-wrapper">
<label htmlFor="new-todo-input" className="label\_\_lg">
What needs to be done?
</label>
</h2>
<input
type="text"
id="new-todo-input"
className="input input\_\_lg"
name="text"
autoComplete="off"
value={name}
onChange={handleChange}
/>
<button type="submit" className="btn btn\_\_primary btn\_\_lg">
Add
</button>
</form>
);
}
export default Form;
```
**Note:** You'll notice that you are able to submit empty tasks by just pressing the `Add` button without entering a task name. Can you think of a way to prevent this? As a hint, you probably need to add some kind of check into the `handleSubmit()` function.
Putting it all together: Adding a task
--------------------------------------
Now that we've practiced with events, callback props, and hooks, we're ready to write functionality that will allow a user to add a new task from their browser.
### Tasks as state
We need to import `useState` into `App.jsx` so that we can store our tasks in state. Add the following to the top of your `App.jsx` file:
```jsx
import { useState } from "react";
```
We want to pass `props.tasks` into the `useState()` hook β this will preserve its initial state. Add the following right at the top of your `App()` function definition:
```jsx
const [tasks, setTasks] = useState(props.tasks);
```
Now, we can change our `taskList` mapping so that it is the result of mapping `tasks`, instead of `props.tasks`. Your `taskList` constant declaration should now look like so:
```jsx
const taskList = tasks?.map((task) => (
<Todo
id={task.id}
name={task.name}
completed={task.completed}
key={task.id}
/>
));
```
### Adding a task
We've now got a `setTasks` hook that we can use in our `addTask()` function to update our list of tasks. There's one problem however: we can't just pass the `name` argument of `addTask()` into `setTasks`, because `tasks` is an array of objects and `name` is a string. If we tried to do this, the array would be replaced with the string.
First of all, we need to put `name` into an object that has the same structure as our existing tasks. Inside of the `addTask()` function, we will make a `newTask` object to add to the array.
We then need to make a new array with this new task added to it and then update the state of the tasks data to this new state. To do this, we can use spread syntax to copy the existing array, and add our object at the end. We then pass this array into `setTasks()` to update the state.
Putting that all together, your `addTask()` function should read like so:
```jsx
function addTask(name) {
const newTask = { id: "id", name, completed: false };
setTasks([...tasks, newTask]);
}
```
Now you can use the browser to add a task to our data! Type anything into the form and click "Add" (or press the `Enter` key) and you'll see your new todo item appear in the UI!
**However, we have another problem**: our `addTask()` function is giving each task the same `id`. This is bad for accessibility, and makes it impossible for React to tell future tasks apart with the `key` prop. In fact, React will give you a warning in your DevTools console β "Warning: Encountered two children with the same keyβ¦"
We need to fix this. Making unique identifiers is a hard problem β one for which the JavaScript community has written some helpful libraries. We'll use nanoid because it's tiny and it works.
Make sure you're in the root directory of your application and run the following terminal command:
```bash
npm install nanoid
```
**Note:** If you're using yarn, you'll need the following instead: `yarn add nanoid`.
Now we can use `nanoid` to create unique IDs for our new tasks. First of all, import it by including the following line at the top of `App.jsx`:
```jsx
import { nanoid } from "nanoid";
```
Now let's update `addTask()` so that each task ID becomes a prefix `todo-` plus a unique string generated by nanoid. Update your `newTask` constant declaration to this:
```jsx
const newTask = { id: `todo-${nanoid()}`, name, completed: false };
```
Save everything, and try your app again β now you can add tasks without getting that warning about duplicate IDs.
Detour: counting tasks
----------------------
Now that we can add new tasks, you may notice a problem: our heading reads "3 tasks remaining" no matter how many tasks we have! We can fix this by counting the length of `taskList` and changing the text of our heading accordingly.
Add this inside your `App()` definition, before the return statement:
```jsx
const headingText = `${taskList.length} tasks remaining`;
```
This is almost right, except that if our list ever contains a single task, the heading will still use the word "tasks". We can make this a variable, too. Update the code you just added as follows:
```jsx
const tasksNoun = taskList.length !== 1 ? "tasks" : "task";
const headingText = `${taskList.length} ${tasksNoun} remaining`;
```
Now you can replace the list heading's text content with the `headingText` variable. Update your `<h2>` like so:
```jsx
<h2 id="list-heading">{headingText}</h2>
```
Save the file, go back to your browser, and try adding some tasks: the count should now update as expected.
Completing a task
-----------------
You might notice that, when you click on a checkbox, it checks and unchecks appropriately. As a feature of HTML, the browser knows how to remember which checkbox inputs are checked or unchecked without our help. This feature hides a problem, however: toggling a checkbox doesn't change the state in our React application. This means that the browser and our app are now out-of-sync. We have to write our own code to put the browser back in sync with our app.
### Proving the bug
Before we fix the problem, let's observe it happening.
We'll start by writing a `toggleTaskCompleted()` function in our `App()` component. This function will have an `id` parameter, but we're not going to use it yet. For now, we'll log the first task in the array to the console β we're going to inspect what happens when we check or uncheck it in our browser:
Add this just above your `taskList` constant declaration:
```jsx
function toggleTaskCompleted(id) {
console.log(tasks[0]);
}
```
Next, we'll add `toggleTaskCompleted` to the props of each `<Todo />` component rendered inside our `taskList`; update it like so:
```jsx
const taskList = tasks.map((task) => (
<Todo
id={task.id}
name={task.name}
completed={task.completed}
key={task.id}
toggleTaskCompleted={toggleTaskCompleted}
/>
));
```
Next, go over to your `Todo.jsx` component and add an `onChange` handler to your `<input />` element, which should use an anonymous function to call `props.toggleTaskCompleted()` with a parameter of `props.id`. The `<input />` should now look like this:
```jsx
<input
id={props.id}
type="checkbox"
defaultChecked={props.completed}
onChange={() => props.toggleTaskCompleted(props.id)}
/>
```
Save everything and return to your browser and notice that our first task, Eat, is checked. Open your JavaScript console, then click on the checkbox next to Eat. It unchecks, as we expect. Your JavaScript console, however, will log something like this:
```
Object { id: "task-0", name: "Eat", completed: true }
```
The checkbox unchecks in the browser, but our console tells us that Eat is still completed. We will fix that next!
### Synchronizing the browser with our data
Let's revisit our `toggleTaskCompleted()` function in `App.jsx`. We want it to change the `completed` property of only the task that was toggled, and leave all the others alone. To do this, we'll `map()` over the task list and just change the one we completed.
Update your `toggleTaskCompleted()` function to the following:
```jsx
function toggleTaskCompleted(id) {
const updatedTasks = tasks.map((task) => {
// if this task has the same ID as the edited task
if (id === task.id) {
// use object spread to make a new object
// whose `completed` prop has been inverted
return { ...task, completed: !task.completed };
}
return task;
});
setTasks(updatedTasks);
}
```
Here, we define an `updatedTasks` constant that maps over the original `tasks` array. If the task's `id` property matches the `id` provided to the function, we use object spread syntax to create a new object, and toggle the `completed` property of that object before returning it. If it doesn't match, we return the original object.
Then we call `setTasks()` with this new array in order to update our state.
Deleting a task
---------------
Deleting a task will follow a similar pattern to toggling its completed state: we need to define a function for updating our state, then pass that function into `<Todo />` as a prop and call it when the right event happens.
### The `deleteTask` callback prop
Here we'll start by writing a `deleteTask()` function in your `App` component. Like `toggleTaskCompleted()`, this function will take an `id` parameter, and we will log that `id` to the console to start with. Add the following below `toggleTaskCompleted()`:
```jsx
function deleteTask(id) {
console.log(id);
}
```
Next, add another callback prop to our array of `<Todo />` components:
```jsx
const taskList = tasks.map((task) => (
<Todo
id={task.id}
name={task.name}
completed={task.completed}
key={task.id}
toggleTaskCompleted={toggleTaskCompleted}
deleteTask={deleteTask}
/>
));
```
In `Todo.jsx`, we want to call `props.deleteTask()` when the "Delete" button is pressed. `deleteTask()` needs to know the ID of the task that called it, so it can delete the correct task from the state.
Update the "Delete" button inside `Todo.jsx`, like so:
```jsx
<button
type="button"
className="btn btn\_\_danger"
onClick={() => props.deleteTask(props.id)}>
Delete <span className="visually-hidden">{props.name}</span>
</button>
```
Now when you click on any of the "Delete" buttons in the app, your browser console should log the ID of the related task.
At this point, your `Todo.jsx` file should look like this:
```jsx
function Todo(props) {
return (
<li className="todo stack-small">
<div className="c-cb">
<input
id={props.id}
type="checkbox"
defaultChecked={props.completed}
onChange={() => props.toggleTaskCompleted(props.id)}
/>
<label className="todo-label" htmlFor={props.id}>
{props.name}
</label>
</div>
<div className="btn-group">
<button type="button" className="btn">
Edit <span className="visually-hidden">{props.name}</span>
</button>
<button
type="button"
className="btn btn\_\_danger"
onClick={() => props.deleteTask(props.id)}>
Delete <span className="visually-hidden">{props.name}</span>
</button>
</div>
</li>
);
}
export default Todo;
```
Deleting tasks from state and UI
--------------------------------
Now that we know `deleteTask()` is invoked correctly, we can call our `setTasks()` hook in `deleteTask()` to actually delete that task from the app's state as well as visually in the app UI. Since `setTasks()` expects an array as an argument, we should provide it with a new array that copies the existing tasks, *excluding* the task whose ID matches the one passed into `deleteTask()`.
This is a perfect opportunity to use `Array.prototype.filter()`. We can test each task, and exclude a task from the new array if its `id` prop matches the `id` argument passed into `deleteTask()`.
Update the `deleteTask()` function inside your `App.jsx` file as follows:
```jsx
function deleteTask(id) {
const remainingTasks = tasks.filter((task) => id !== task.id);
setTasks(remainingTasks);
}
```
Try your app out again. Now you should be able to delete a task from your app!
At this point, your `App.jsx` file should look like this:
```jsx
import { useState } from "react";
import { nanoid } from "nanoid";
import Todo from "./components/Todo";
import Form from "./components/Form";
import FilterButton from "./components/FilterButton";
function App(props) {
function addTask(name) {
const newTask = { id: `todo-${nanoid}`, name, completed: false };
setTasks([...tasks, newTask]);
}
function toggleTaskCompleted(id) {
const updatedTasks = tasks.map((task) => {
// if this task has the same ID as the edited task
if (id === task.id) {
// use object spread to make a new object
// whose `completed` prop has been inverted
return { ...task, completed: !task.completed };
}
return task;
});
setTasks(updatedTasks);
}
function deleteTask(id) {
const remainingTasks = tasks.filter((task) => id !== task.id);
setTasks(remainingTasks);
}
const [tasks, setTasks] = useState(props.tasks);
const taskList = tasks?.map((task) => (
<Todo
id={task.id}
name={task.name}
completed={task.completed}
key={task.id}
toggleTaskCompleted={toggleTaskCompleted}
deleteTask={deleteTask}
/>
));
const tasksNoun = taskList.length !== 1 ? "tasks" : "task";
const headingText = `${taskList.length} ${tasksNoun} remaining`;
return (
<div className="todoapp stack-large">
<h1>TodoMatic</h1>
<Form addTask={addTask} />
<div className="filters btn-group stack-exception">
<FilterButton />
<FilterButton />
<FilterButton />
</div>
<h2 id="list-heading">{headingText}</h2>
<ul
role="list"
className="todo-list stack-large stack-exception"
aria-labelledby="list-heading">
{taskList}
</ul>
</div>
);
}
export default App;
```
Summary
-------
That's enough for one article. Here we've given you the lowdown on how React deals with events and handles state, and implemented functionality to add tasks, delete tasks, and toggle tasks as completed. We are nearly there. In the next article we'll implement functionality to edit existing tasks and filter the list of tasks between all, completed, and incomplete tasks. We'll look at conditional UI rendering along the way.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Beginning our React todo list - Learn web development | Beginning our React todo list
=============================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
Let's say that we've been tasked with creating a proof-of-concept in React β an app that allows users to add, edit, and delete tasks they want to work on, and also mark tasks as complete without deleting them. This article will walk you through the basic structure and styling of such an application, ready for individual component definition and interactivity, which we'll add later.
**Note:** If you need to check your code against our version, you can find a finished version of the sample React app code in our todo-react repository. For a running live version, see https://mdn.github.io/todo-react/.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
|
| Objective: |
To introduce our todo list case study, and get the basic
`App` structure and styling in place.
|
Our app's user stories
----------------------
In software development, a user story is an actionable goal from the perspective of the user. Defining user stories before we begin our work will help us focus our work. Our app should fulfill the following stories:
As a user, I can
* read a list of tasks.
* add a task using the mouse or keyboard.
* mark any task as completed, using the mouse or keyboard.
* delete any task, using the mouse or keyboard.
* edit any task, using the mouse or keyboard.
* view a specific subset of tasks: All tasks, only the active task, or only the completed tasks.
We'll tackle these stories one-by-one.
Pre-project housekeeping
------------------------
Vite has given us some code that we won't be using at all for our project. The following terminal commands will delete it to make way for our new project. Make sure you're starting in the app's root directory!
```bash
# Move into the src directory
cd src
# Delete the App.css file and the React logo provided by Vite
rm App.css assets/react.svg
# Empty the contents of App.jsx and index.css
echo -n > App.jsx && echo -n > index.css
# Move back up to the root of the project
cd ..
```
**Note:** If you stopped your server to do the terminal tasks mentioned above, you'll have to start it again using `npm run dev`.
Project starter code
--------------------
As a starting point for this project, we're going to provide two things: an `App()` function to replace the one you just deleted, and some CSS to style your app.
### The JSX
Copy the following snippet to your clipboard, then paste it into `App.jsx`:
```jsx
function App(props) {
return (
<div className="todoapp stack-large">
<h1>TodoMatic</h1>
<form>
<h2 className="label-wrapper">
<label htmlFor="new-todo-input" className="label\_\_lg">
What needs to be done?
</label>
</h2>
<input
type="text"
id="new-todo-input"
className="input input\_\_lg"
name="text"
autoComplete="off"
/>
<button type="submit" className="btn btn\_\_primary btn\_\_lg">
Add
</button>
</form>
<div className="filters btn-group stack-exception">
<button type="button" className="btn toggle-btn" aria-pressed="true">
<span className="visually-hidden">Show </span>
<span>all</span>
<span className="visually-hidden"> tasks</span>
</button>
<button type="button" className="btn toggle-btn" aria-pressed="false">
<span className="visually-hidden">Show </span>
<span>Active</span>
<span className="visually-hidden"> tasks</span>
</button>
<button type="button" className="btn toggle-btn" aria-pressed="false">
<span className="visually-hidden">Show </span>
<span>Completed</span>
<span className="visually-hidden"> tasks</span>
</button>
</div>
<h2 id="list-heading">3 tasks remaining</h2>
<ul
role="list"
className="todo-list stack-large stack-exception"
aria-labelledby="list-heading">
<li className="todo stack-small">
<div className="c-cb">
<input id="todo-0" type="checkbox" defaultChecked />
<label className="todo-label" htmlFor="todo-0">
Eat
</label>
</div>
<div className="btn-group">
<button type="button" className="btn">
Edit <span className="visually-hidden">Eat</span>
</button>
<button type="button" className="btn btn\_\_danger">
Delete <span className="visually-hidden">Eat</span>
</button>
</div>
</li>
<li className="todo stack-small">
<div className="c-cb">
<input id="todo-1" type="checkbox" />
<label className="todo-label" htmlFor="todo-1">
Sleep
</label>
</div>
<div className="btn-group">
<button type="button" className="btn">
Edit <span className="visually-hidden">Sleep</span>
</button>
<button type="button" className="btn btn\_\_danger">
Delete <span className="visually-hidden">Sleep</span>
</button>
</div>
</li>
<li className="todo stack-small">
<div className="c-cb">
<input id="todo-2" type="checkbox" />
<label className="todo-label" htmlFor="todo-2">
Repeat
</label>
</div>
<div className="btn-group">
<button type="button" className="btn">
Edit <span className="visually-hidden">Repeat</span>
</button>
<button type="button" className="btn btn\_\_danger">
Delete <span className="visually-hidden">Repeat</span>
</button>
</div>
</li>
</ul>
</div>
);
}
export default App;
```
Now open `index.html` and change the `<title>` element's text to `TodoMatic`. This way, it will match the `<h1>` at the top of our app.
```html
<title>TodoMatic</title>
```
When your browser refreshes, you should see something like this:
![todo-matic app, unstyled, showing a jumbled mess of labels, inputs, and buttons](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning/unstyled-app.png)
It's ugly, and doesn't function yet, but that's okay β we'll style it in a moment. First, consider the JSX we have, and how it corresponds to our user stories:
* We have a `<form>` element, with an `<input type="text">` for writing out a new task, and a button to submit the form.
* We have an array of buttons that will be used to filter our tasks.
* We have a heading that tells us how many tasks remain.
* We have our 3 tasks, arranged in an unordered list. Each task is a list item (`<li>`), and has buttons to edit and delete it and a checkbox to check it off as done.
The form will allow us to *make* tasks; the buttons will let us *filter* them; the heading and list are our way to *read* them. The UI for *editing* a task is conspicuously absent for now. That's okay β we'll write that later.
### Accessibility features
You may notice some unusual markup here. For example:
```jsx
<button type="button" className="btn toggle-btn" aria-pressed="true">
<span className="visually-hidden">Show </span>
<span>all</span>
<span className="visually-hidden"> tasks</span>
</button>
```
Here, `aria-pressed` tells assistive technology (like screen readers) that the button can be in one of two states: `pressed` or `unpressed`. Think of these as analogs for `on` and `off`. Setting a value of `"true"` means that the button is pressed by default.
The class `visually-hidden` has no effect yet, because we have not included any CSS. Once we have put our styles in place, though, any element with this class will be hidden from sighted users and still available to assistive technology users β this is because these words are not needed by sighted users; they are there to provide more information about what the button does for assistive technology users that do not have the extra visual context to help them.
Further down, you can find our `<ul>` element:
```html
<ul
role="list"
className="todo-list stack-large stack-exception"
aria-labelledby="list-heading">
β¦
</ul>
```
The `role` attribute helps assistive technology explain what kind of element a tag represents. A `<ul>` is treated like a list by default, but the styles we're about to add will break that functionality. This role will restore the "list" meaning to the `<ul>` element. If you want to learn more about why this is necessary, you can check out Scott O'Hara's article, "Fixing Lists".
The `aria-labelledby` attribute tells assistive technologies that we're treating our list heading as the label that describes the purpose of the list beneath it. Making this association gives the list a more informative context, which could help assistive technology users better understand the list's purpose.
Finally, the labels and inputs in our list items have some attributes unique to JSX:
```jsx
<input id="todo-0" type="checkbox" defaultChecked />
<label className="todo-label" htmlFor="todo-0">
Eat
</label>
```
The `defaultChecked` attribute in the `<input />` tag tells React to check this checkbox initially. If we were to use `checked`, as we would in regular HTML, React would log some warnings into our browser console relating to handling events on the checkbox, which we want to avoid. Don't worry too much about this for now β we will cover this later on when we get to using events.
The `htmlFor` attribute corresponds to the `for` attribute used in HTML. We cannot use `for` as an attribute in JSX because `for` is a reserved word, so React uses `htmlFor` instead.
### A note on boolean attributes in JSX
The `defaultChecked` attribute in the previous section is a boolean attribute β an attribute whose value is either `true` or `false`. Like in HTML, a boolean attribute is `true` if it's present and `false` if it's absent; the assignment on the right-hand side of the expression is optional. You can explicitly set its value by passing it in curly braces β for example, `defaultChecked={true}` or `defaultChecked={false}`.
Because JSX is JavaScript, there's a gotcha to be aware of with boolean attributes: writing `defaultChecked="false"` will set a *string* value of `"false"` rather than a *boolean* value. Non-empty strings are truthy, so React will consider `defaultChecked` to be `true` and check the checkbox by default. This is not what we want, so we should avoid it.
If you'd like, you can practice writing boolean attributes with another attribute you may have seen before, `hidden`, which prevents elements from being rendered on the page. Try adding `hidden` to the `<h1>` element in `App.jsx` to see what happens, then try explicitly setting its value to `{false}`. Note, again, that writing `hidden="false"` results in a truthy value so the `<h1>` *will* hide. Don't forget to remove this code when you're done.
**Note:** The `aria-pressed` attribute used in our earlier code snippet has a value of `"true"` because `aria-pressed` is not a true boolean attribute in the way `checked` is.
### Implementing our styles
Paste the following CSS code into `src/index.css`:
```css
/\* Resets \*/
\*,
\*::before,
\*::after {
box-sizing: border-box;
}
\*:focus-visible {
outline: 3px dashed #228bec;
outline-offset: 0;
}
html {
font: 62.5% / 1.15 sans-serif;
}
h1,
h2 {
margin-bottom: 0;
}
ul {
list-style: none;
padding: 0;
}
button {
-moz-osx-font-smoothing: inherit;
-webkit-font-smoothing: inherit;
appearance: none;
background: transparent;
border: none;
color: inherit;
font: inherit;
line-height: normal;
margin: 0;
overflow: visible;
padding: 0;
width: auto;
}
button::-moz-focus-inner {
border: 0;
}
button,
input,
optgroup,
select,
textarea {
font-family: inherit;
font-size: 100%;
line-height: 1.15;
margin: 0;
}
button,
input {
overflow: visible;
}
input[type="text"] {
border-radius: 0;
}
body {
background-color: #f5f5f5;
color: #4d4d4d;
font:
1.6rem/1.25 Arial,
sans-serif;
margin: 0 auto;
max-width: 68rem;
width: 100%;
}
@media screen and (min-width: 620px) {
body {
font-size: 1.9rem;
line-height: 1.31579;
}
}
/\* End resets \*/
/\* Global styles \*/
.form-group > input[type="text"] {
display: inline-block;
margin-top: 0.4rem;
}
.btn {
border: 0.2rem solid #4d4d4d;
cursor: pointer;
padding: 0.8rem 1rem 0.7rem;
text-transform: capitalize;
}
.btn.toggle-btn {
border-color: #d3d3d3;
border-width: 1px;
}
.btn.toggle-btn[aria-pressed="true"] {
border-color: #4d4d4d;
text-decoration: underline;
}
.btn\_\_danger {
background-color: #ca3c3c;
border-color: #bd2130;
color: #fff;
}
.btn\_\_filter {
border-color: lightgrey;
}
.btn\_\_primary {
background-color: #000;
color: #fff;
}
.btn-group {
display: flex;
justify-content: space-between;
}
.btn-group > \* {
flex: 1 1 49%;
}
.btn-group > \* + \* {
margin-left: 0.8rem;
}
.label-wrapper {
flex: 0 0 100%;
margin: 0;
text-align: center;
}
.visually-hidden {
clip: rect(1px 1px 1px 1px);
clip: rect(1px, 1px, 1px, 1px);
height: 1px;
overflow: hidden;
position: absolute !important;
white-space: nowrap;
width: 1px;
}
[class\*="stack"] > \* {
margin-bottom: 0;
margin-top: 0;
}
.stack-small > \* + \* {
margin-top: 1.25rem;
}
.stack-large > \* + \* {
margin-top: 2.5rem;
}
@media screen and (min-width: 550px) {
.stack-small > \* + \* {
margin-top: 1.4rem;
}
.stack-large > \* + \* {
margin-top: 2.8rem;
}
}
.stack-exception {
margin-top: 1.2rem;
}
/\* End global styles \*/
/\* General app styles \*/
.todoapp {
background: #fff;
box-shadow:
0 2px 4px 0 rgb(0 0 0 / 20%),
0 2.5rem 5rem 0 rgb(0 0 0 / 10%);
margin: 2rem 0 4rem 0;
padding: 1rem;
position: relative;
}
@media screen and (min-width: 550px) {
.todoapp {
padding: 4rem;
}
}
.todoapp > \* {
margin-left: auto;
margin-right: auto;
max-width: 50rem;
}
.todoapp > form {
max-width: 100%;
}
.todoapp > h1 {
display: block;
margin: 0;
margin-bottom: 1rem;
max-width: 100%;
text-align: center;
}
.label\_\_lg {
line-height: 1.01567;
font-weight: 300;
margin-bottom: 1rem;
padding: 0.8rem;
text-align: center;
}
.input\_\_lg {
border: 2px solid #000;
padding: 2rem;
}
.input\_\_lg:focus-visible {
border-color: #4d4d4d;
box-shadow: inset 0 0 0 2px;
}
[class\*="\_\_lg"] {
display: inline-block;
font-size: 1.9rem;
width: 100%;
}
[class\*="\_\_lg"]:not(:last-child) {
margin-bottom: 1rem;
}
@media screen and (min-width: 620px) {
[class\*="\_\_lg"] {
font-size: 2.4rem;
}
}
/\* End general app styles \*/
/\* Todo item styles \*/
.todo {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.todo > \* {
flex: 0 0 100%;
}
.todo-text {
border: 2px solid #565656;
min-height: 4.4rem;
padding: 0.4rem 0.8rem;
width: 100%;
}
.todo-text:focus-visible {
box-shadow: inset 0 0 0 2px;
}
/\* End todo item styles \*/
/\* Checkbox styles \*/
.c-cb {
-webkit-font-smoothing: antialiased;
box-sizing: border-box;
clear: left;
display: block;
font-family: Arial, sans-serif;
font-size: 1.6rem;
font-weight: 400;
line-height: 1.25;
min-height: 44px;
padding-left: 40px;
position: relative;
}
.c-cb > label::before,
.c-cb > input[type="checkbox"] {
box-sizing: border-box;
height: 44px;
left: -2px;
top: -2px;
width: 44px;
}
.c-cb > input[type="checkbox"] {
-webkit-font-smoothing: antialiased;
cursor: pointer;
margin: 0;
opacity: 0;
position: absolute;
z-index: 1;
}
.c-cb > label {
cursor: pointer;
display: inline-block;
font-family: inherit;
font-size: inherit;
line-height: inherit;
margin-bottom: 0;
padding: 8px 15px 5px;
touch-action: manipulation;
}
.c-cb > label::before {
background: transparent;
border: 2px solid currentcolor;
content: "";
position: absolute;
}
.c-cb > input[type="checkbox"]:focus-visible + label::before {
border-width: 4px;
outline: 3px dashed #228bec;
}
.c-cb > label::after {
background: transparent;
border: solid;
border-width: 0 0 5px 5px;
border-top-color: transparent;
box-sizing: content-box;
content: "";
height: 7px;
left: 9px;
opacity: 0;
position: absolute;
top: 11px;
transform: rotate(-45deg);
width: 18px;
}
.c-cb > input[type="checkbox"]:checked + label::after {
opacity: 1;
}
/\* End checkbox styles \*/
```
Save and look back at your browser, and your app should now have reasonable styling.
Summary
-------
Now our todo list app actually looks a bit more like a real app! The problem is: it doesn't actually do anything. We'll start fixing that in the next chapter!
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Starting our Svelte to-do list app - Learn web development | Starting our Svelte to-do list app
==================================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
Now that we have a basic understanding of how things work in Svelte, we can start building our example app: a to-do list. In this article we will first have a look at the desired functionality of our app, and then we'll create a `Todos.svelte` component and put static markup and styles in place, leaving everything ready to start developing our to-do list app features, which we'll go on to in subsequent articles.
We want our users to be able to browse, add and delete tasks, and also to mark them as complete. This will be the basic functionality that we'll be developing in this tutorial series, and we'll look at some more advanced concepts along the way too.
| | |
| --- | --- |
| Prerequisites: |
At minimum, it is recommended that you are familiar with the core
HTML,
CSS, and
JavaScript languages, and
have knowledge of the
terminal/command line.
You'll need a terminal with node + npm installed to compile and build
your app.
|
| Objective: |
To learn how to create a Svelte component, render it inside another
component, pass data into it using props, and save its state.
|
Code along with us
------------------
### Git
Clone the GitHub repo (if you haven't already done it) with:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then to get to the current app state, run
```bash
cd mdn-svelte-tutorial/02-starting-our-todo-app
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/02-starting-our-todo-app
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To code along with us using the REPL, start at
https://svelte.dev/repl/b7b831ea3a354d3789cefbc31e2ca495?version=3.23.2
To-do list app features
-----------------------
This is what our to-do list app will look like once it's ready:
![typical to-do list app, with a title of 'what needs to be done', an input to enter more to-dos, and a list of to-dos with checkboxes](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_Todo_list_beginning/01-todo-list-app.png)
Using this UI our user will be able to:
* Browse their tasks
* Mark tasks as completed/pending without deleting them
* Remove tasks
* Add new tasks
* Filter tasks by status: all tasks, active tasks, or completed tasks
* Edit tasks
* Mark all tasks as active/completed
* Remove all completed tasks
Building our first component
----------------------------
Let's create a `Todos.svelte` component. This will contain our list of to-dos.
1. Create a new folder β `src/components`.
**Note:** You can put your components anywhere inside the `src` folder, but the `components` folder is a recognized convention to follow, allowing you to find your components easily.
2. Create a file named `src/components/Todos.svelte` with the following content:
```svelte
<h1>Svelte to-do list</h1>
```
3. Change the `title` element in `public/index.html` to contain the text *Svelte to-do list*:
```svelte
<title>Svelte to-do list</title>
```
4. Open `src/App.svelte` and replace its contents with the following:
```svelte
<script>
import Todos from "./components/Todos.svelte";
</script>
<Todos />
```
5. In development mode, Svelte will issue a warning in the browser console when specifying a prop that doesn't exist in the component; in this case we have a `name` prop being specified when we instantiate the `App` component inside `src/main.js`, which isn't used inside `App`. The console should currently give you a message along the lines of "<App> was created with unknown prop 'name'". To get rid of this, remove the `name` prop from `src/main.js`; it should now look like so:
```js
import App from "./App.svelte";
const app = new App({
target: document.body,
});
export default app;
```
Now if you check your testing server URL you'll see our `Todos.svelte` component being rendered:
![basic component rendering which a title that says 'Svelte to-do list'](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_Todo_list_beginning/02-todos-component-rendered.png)
Adding static markup
--------------------
For the moment we will start with a static markup representation of our app, so you can see what it will look like. Copy and paste the following into our `Todos.svelte` component file, replacing the existing content:
```svelte
<!-- Todos.svelte -->
<div class="todoapp stack-large">
<!-- NewTodo -->
<form>
<h2 class="label-wrapper">
<label for="todo-0" class="label\_\_lg"> What needs to be done? </label>
</h2>
<input type="text" id="todo-0" autocomplete="off" class="input input\_\_lg" />
<button type="submit" disabled="" class="btn btn\_\_primary btn\_\_lg">
Add
</button>
</form>
<!-- Filter -->
<div class="filters btn-group stack-exception">
<button class="btn toggle-btn" aria-pressed="true">
<span class="visually-hidden">Show</span>
<span>All</span>
<span class="visually-hidden">tasks</span>
</button>
<button class="btn toggle-btn" aria-pressed="false">
<span class="visually-hidden">Show</span>
<span>Active</span>
<span class="visually-hidden">tasks</span>
</button>
<button class="btn toggle-btn" aria-pressed="false">
<span class="visually-hidden">Show</span>
<span>Completed</span>
<span class="visually-hidden">tasks</span>
</button>
</div>
<!-- TodosStatus -->
<h2 id="list-heading">2 out of 3 items completed</h2>
<!-- Todos -->
<ul role="list" class="todo-list stack-large" aria-labelledby="list-heading">
<!-- todo-1 (editing mode) -->
<li class="todo">
<div class="stack-small">
<form class="stack-small">
<div class="form-group">
<label for="todo-1" class="todo-label">
New name for 'Create a Svelte starter app'
</label>
<input
type="text"
id="todo-1"
autocomplete="off"
class="todo-text" />
</div>
<div class="btn-group">
<button class="btn todo-cancel" type="button">
Cancel
<span class="visually-hidden">renaming Create a Svelte starter app</span>
</button>
<button class="btn btn\_\_primary todo-edit" type="submit">
Save
<span class="visually-hidden">new name for Create a Svelte starter app</span>
</button>
</div>
</form>
</div>
</li>
<!-- todo-2 -->
<li class="todo">
<div class="stack-small">
<div class="c-cb">
<input type="checkbox" id="todo-2" checked />
<label for="todo-2" class="todo-label">
Create your first component
</label>
</div>
<div class="btn-group">
<button type="button" class="btn">
Edit
<span class="visually-hidden">Create your first component</span>
</button>
<button type="button" class="btn btn\_\_danger">
Delete
<span class="visually-hidden">Create your first component</span>
</button>
</div>
</div>
</li>
<!-- todo-3 -->
<li class="todo">
<div class="stack-small">
<div class="c-cb">
<input type="checkbox" id="todo-3" />
<label for="todo-3" class="todo-label">
Complete the rest of the tutorial
</label>
</div>
<div class="btn-group">
<button type="button" class="btn">
Edit
<span class="visually-hidden">Complete the rest of the tutorial</span>
</button>
<button type="button" class="btn btn\_\_danger">
Delete
<span class="visually-hidden">Complete the rest of the tutorial</span>
</button>
</div>
</div>
</li>
</ul>
<hr />
<!-- MoreActions -->
<div class="btn-group">
<button type="button" class="btn btn\_\_primary">Check all</button>
<button type="button" class="btn btn\_\_primary">Remove completed</button>
</div>
</div>
```
Check the rendered out again, and you'll see something like this:
![A to-do list app, but unstyled, with a title of what needs to be done, inputs, checkboxes, etc.](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_Todo_list_beginning/03-unstyled-todo-app.png)
The HTML markup above is not very nicely styled and it's also functionally useless. Nevertheless, let's have a look at the markup and see how it relates to our desired features:
* A label and a text box for entering new tasks
* Three buttons to filter by task status
* A label showing the total number of tasks and the completed tasks
* An unordered list, which holds a list item for each task
* When the task is being edited, the list item has an input and two button to cancel or save modifications
* If the task is not being edited, there's a checkbox to set the completed status, and two buttons to edit or delete the task
* Finally there are two buttons to check/uncheck all task and to remove completed tasks
In subsequent articles we'll get all these features working, and more besides.
### Accessibility features of the to-do list
You may notice some unusual attributes here. For example:
```svelte
<button class="btn toggle-btn" aria-pressed="true">
<span class="visually-hidden">Show</span>
<span>All</span>
<span class="visually-hidden">tasks</span>
</button>
```
Here, `aria-pressed` tells assistive technology (like screen readers) that the button can be in one of two states: `pressed` or `unpressed`. Think of these as analogs for on and off. Setting a value of `true` means that the button is pressed by default.
The class `visually-hidden` has no effect yet, because we have not included any CSS. Once we have put our styles in place, though, any element with this class will be hidden from sighted users and still available to screen reader users β this is because these words are not needed by sighted users; they are there to provide more information about what the button does for screen reader users that do not have the extra visual context to help them.
Further down, you can find the following `<ul>` element:
```svelte
<ul
role="list"
class="todo-list stack-large"
aria-labelledby="list-heading">
```
The `role` attribute helps assistive technology explain what kind of semantic value an element has β or what its purpose is. A `<ul>` is treated like a list by default, but the styles we're about to add will break that functionality. This role will restore the "list" meaning to the `<ul>` element. If you want to learn more about why this is necessary, you can check out Scott O'Hara's article "Fixing Lists" (2019).
The `aria-labelledby` attribute tells assistive technologies that we're treating our `<h2>` with an `id` of `list-heading` as the label that describes the purpose of the list beneath it. Making this association gives the list a more informative context, which could help screen reader users better understand the purpose of it.
This seems like a good time to talk about how Svelte deals with accessibility; let's do that now.
Svelte accessibility support
----------------------------
Svelte has a special emphasis on accessibility. The intention is to encourage developers to write more accessible code "by default". Being a compiler, Svelte can statically analyze our HTML templates to provide accessibility warnings when components are being compiled.
Accessibility (shortened to a11y) isn't always easy to get right, but Svelte will help by warning you if you write inaccessible markup.
For example, if we add an `<img>` element to our `todos.svelte` component without its corresponding `alt` prop:
```svelte
<h1>Svelte To-Do list</h1>
<img height="32" width="88" src="https://www.w3.org/WAI/wcag2A" />
```
The compiler will issue the following warning:
```bash
(!) Plugin svelte: A11y: <img> element should have an alt attribute
src/components/Todos.svelte
1: <h1>Svelte To-Do list</h1>
2:
3: <img height="32" width="88" src="https://www.w3.org/WAI/wcag2A">
^
created public/build/bundle.js in 220ms
[2020-07-15 04:07:43] waiting for changes...
```
Moreover, our editor can display this warning even before calling the compiler:
![A code editor window showing an image tag, with a popup error message saying that the element should have an alt attribute](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_Todo_list_beginning/04-svelte-accessibility-support.png)
You can tell Svelte to ignore this warning for the next block of markup with a comment beginning with `svelte-ignore`, like this:
```svelte
<!-- svelte-ignore a11y-missing-attribute -->
<img height="32" width="88" src="https://www.w3.org/WAI/wcag2A" />
```
**Note:** With VSCode you can automatically add this ignore comment by clicking on the *Quick fixβ¦* link or pressing `Ctrl` + `.`.
If you want to globally disable this warning, you can add this `onwarn` handler to your `rollup.config.js` file inside the configuration for the `Svelte` plugin, like this:
```js
plugins: [
svelte({
dev: !production,
css: (css) => {
css.write("public/build/bundle.css");
},
// Warnings are normally passed straight to Rollup. You can
// optionally handle them here, for example to squelch
// warnings with a particular code
onwarn: (warning, handler) => {
// e.g. I don't care about screen readers -> please DON'T DO THIS!!!
if (warning.code === "a11y-missing-attribute") {
return;
}
// let Rollup handle all other warnings normally
handler(warning);
},
}),
// β¦
];
```
By design, these warnings are implemented in the compiler itself, and not as a plug-in that you may choose to add to your project. The idea is to check for a11y issues in your markup by default and let you opt out of specific warnings.
**Note:** You should only disable these warnings if you have good reasons to do so, for example while building a quick prototype. It's important to be a good web citizen and make your pages accessible to the broadest possible userbase.
The accessibility rules checked by Svelte are taken from eslint-plugin-jsx-a11y, a plugin for ESLint that provides static checks for many accessibility rules on JSX elements. Svelte aims to implement all of them in its compiler, and most of them have already been ported to Svelte. On GitHub you can see which accessibility checks are still missing. You can check the meaning of each rule by clicking on its link.
Styling our markup
------------------
Let's make the to-do list look a little better. Replace the contents of the file `public/global.css` with the following:
```css
/\* RESETS \*/
\*,
\*::before,
\*::after {
box-sizing: border-box;
}
\*:focus {
outline: 3px dashed #228bec;
outline-offset: 0;
}
html {
font: 62.5% / 1.15 sans-serif;
}
h1,
h2 {
margin-bottom: 0;
}
ul {
list-style: none;
padding: 0;
}
button {
border: none;
margin: 0;
padding: 0;
width: auto;
overflow: visible;
background: transparent;
color: inherit;
font: inherit;
line-height: normal;
-webkit-font-smoothing: inherit;
-moz-osx-font-smoothing: inherit;
appearance: none;
}
button::-moz-focus-inner {
border: 0;
}
button,
input,
optgroup,
select,
textarea {
font-family: inherit;
font-size: 100%;
line-height: 1.15;
margin: 0;
}
button,
input {
overflow: visible;
}
input[type="text"] {
border-radius: 0;
}
body {
width: 100%;
max-width: 68rem;
margin: 0 auto;
font:
1.6rem/1.25 Arial,
sans-serif;
background-color: #f5f5f5;
color: #4d4d4d;
}
@media screen and (min-width: 620px) {
body {
font-size: 1.9rem;
line-height: 1.31579;
}
}
/\*END RESETS\*/
/\* GLOBAL STYLES \*/
.form-group > input[type="text"] {
display: inline-block;
margin-top: 0.4rem;
}
.btn {
padding: 0.8rem 1rem 0.7rem;
border: 0.2rem solid #4d4d4d;
cursor: pointer;
text-transform: capitalize;
}
.btn.toggle-btn {
border-width: 1px;
border-color: #d3d3d3;
}
.btn.toggle-btn[aria-pressed="true"] {
text-decoration: underline;
border-color: #4d4d4d;
}
.btn\_\_danger {
color: #fff;
background-color: #ca3c3c;
border-color: #bd2130;
}
.btn\_\_filter {
border-color: lightgrey;
}
.btn\_\_primary {
color: #fff;
background-color: #000;
}
.btn\_\_primary:disabled {
color: darkgrey;
background-color: #565656;
}
.btn-group {
display: flex;
justify-content: space-between;
}
.btn-group > \* {
flex: 1 1 49%;
}
.btn-group > \* + \* {
margin-left: 0.8rem;
}
.label-wrapper {
margin: 0;
flex: 0 0 100%;
text-align: center;
}
.visually-hidden {
position: absolute !important;
height: 1px;
width: 1px;
overflow: hidden;
clip: rect(1px 1px 1px 1px);
clip: rect(1px, 1px, 1px, 1px);
white-space: nowrap;
}
[class\*="stack"] > \* {
margin-top: 0;
margin-bottom: 0;
}
.stack-small > \* + \* {
margin-top: 1.25rem;
}
.stack-large > \* + \* {
margin-top: 2.5rem;
}
@media screen and (min-width: 550px) {
.stack-small > \* + \* {
margin-top: 1.4rem;
}
.stack-large > \* + \* {
margin-top: 2.8rem;
}
}
.stack-exception {
margin-top: 1.2rem;
}
/\* END GLOBAL STYLES \*/
.todoapp {
background: #fff;
margin: 2rem 0 4rem 0;
padding: 1rem;
position: relative;
box-shadow:
0 2px 4px 0 rgb(0 0 0 / 20%),
0 2.5rem 5rem 0 rgb(0 0 0 / 10%);
}
@media screen and (min-width: 550px) {
.todoapp {
padding: 4rem;
}
}
.todoapp > \* {
max-width: 50rem;
margin-left: auto;
margin-right: auto;
}
.todoapp > form {
max-width: 100%;
}
.todoapp > h1 {
display: block;
max-width: 100%;
text-align: center;
margin: 0;
margin-bottom: 1rem;
}
.label\_\_lg {
line-height: 1.01567;
font-weight: 300;
padding: 0.8rem;
margin-bottom: 1rem;
text-align: center;
}
.input\_\_lg {
padding: 2rem;
border: 2px solid #000;
}
.input\_\_lg:focus {
border-color: #4d4d4d;
box-shadow: inset 0 0 0 2px;
}
[class\*="\_\_lg"] {
display: inline-block;
width: 100%;
font-size: 1.9rem;
}
[class\*="\_\_lg"]:not(:last-child) {
margin-bottom: 1rem;
}
@media screen and (min-width: 620px) {
[class\*="\_\_lg"] {
font-size: 2.4rem;
}
}
.filters {
width: 100%;
margin: unset auto;
}
/\* Todo item styles \*/
.todo {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.todo > \* {
flex: 0 0 100%;
}
.todo-text {
width: 100%;
min-height: 4.4rem;
padding: 0.4rem 0.8rem;
border: 2px solid #565656;
}
.todo-text:focus {
box-shadow: inset 0 0 0 2px;
}
/\* CHECKBOX STYLES \*/
.c-cb {
box-sizing: border-box;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
font-weight: 400;
font-size: 1.6rem;
line-height: 1.25;
display: block;
position: relative;
min-height: 44px;
padding-left: 40px;
clear: left;
}
.c-cb > label::before,
.c-cb > input[type="checkbox"] {
box-sizing: border-box;
top: -2px;
left: -2px;
width: 44px;
height: 44px;
}
.c-cb > input[type="checkbox"] {
-webkit-font-smoothing: antialiased;
cursor: pointer;
position: absolute;
z-index: 1;
margin: 0;
opacity: 0;
}
.c-cb > label {
font-size: inherit;
font-family: inherit;
line-height: inherit;
display: inline-block;
margin-bottom: 0;
padding: 8px 15px 5px;
cursor: pointer;
touch-action: manipulation;
}
.c-cb > label::before {
content: "";
position: absolute;
border: 2px solid currentcolor;
background: transparent;
}
.c-cb > input[type="checkbox"]:focus + label::before {
border-width: 4px;
outline: 3px dashed #228bec;
}
.c-cb > label::after {
box-sizing: content-box;
content: "";
position: absolute;
top: 11px;
left: 9px;
width: 18px;
height: 7px;
transform: rotate(-45deg);
border: solid;
border-width: 0 0 5px 5px;
border-top-color: transparent;
opacity: 0;
background: transparent;
}
.c-cb > input[type="checkbox"]:checked + label::after {
opacity: 1;
}
```
With our markup styled, everything now looks better:
![Our to-do list app, styled, with a title of 'what needs to be done', an input to enter more to-dos, and a list of to-dos with checkboxes](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_Todo_list_beginning/05-styled-todo-app.png)
The code so far
---------------
### Git
To see the state of the code as it should be at the end of this article, access your copy of our repo like this:
```bash
cd mdn-svelte-tutorial/03-adding-dynamic-behavior
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/03-adding-dynamic-behavior
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To see the current state of the code in a REPL, visit:
https://svelte.dev/repl/c862d964d48d473ca63ab91709a0a5a0?version=3.23.2
Summary
-------
With our markup and styling in place, our to-do list app is starting to take shape, and we have everything ready so that we can start to focus on the features we have to implement.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
React interactivity: Editing, filtering, conditional rendering - Learn web development | React interactivity: Editing, filtering, conditional rendering
==============================================================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
As we near the end of our React journey (for now at least), we'll add the finishing touches to the main areas of functionality in our Todo list app. This includes allowing you to edit existing tasks, and filtering the list of tasks between all, completed, and incomplete tasks. We'll look at conditional UI rendering along the way.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
|
| Objective: |
To learn about conditional rendering in React, and implementing list
filtering and an editing UI in our app.
|
Editing the name of a task
--------------------------
We don't have a user interface for editing the name of a task yet. We'll get to that in a moment. To start with, we can at least implement an `editTask()` function in `App.jsx`. It'll be similar to `deleteTask()` because it'll take an `id` to find its target object, but it'll also take a `newName` property containing the name to update the task to. We'll use `Array.prototype.map()` instead of `Array.prototype.filter()` because we want to return a new array with some changes, instead of deleting something from the array.
Add the `editTask()` function inside your `<App />` component, in the same place as the other functions:
```jsx
function editTask(id, newName) {
const editedTaskList = tasks.map((task) => {
// if this task has the same ID as the edited task
if (id === task.id) {
// Copy the task and update its name
return { ...task, name: newName };
}
// Return the original task if it's not the edited task
return task;
});
setTasks(editedTaskList);
}
```
Pass `editTask` into our `<Todo />` components as a prop in the same way we did with `deleteTask`:
```jsx
const taskList = tasks.map((task) => (
<Todo
id={task.id}
name={task.name}
completed={task.completed}
key={task.id}
toggleTaskCompleted={toggleTaskCompleted}
deleteTask={deleteTask}
editTask={editTask}
/>
));
```
Now open `Todo.jsx`. We're going to do some refactoring.
A UI for editing
----------------
In order to allow users to edit a task, we have to provide a user interface for them to do so. First, import `useState` into the `<Todo />` component like we did before with the `<App />` component:
```jsx
import { useState } from "react";
```
We'll use this to set an `isEditing` state with a default value of `false`. Add the following line just inside the top of your `<Todo />` component definition:
```jsx
const [isEditing, setEditing] = useState(false);
```
Next, we're going to rethink the `<Todo />` component. From now on, we want it to display one of two possible "templates", rather than the single template it has used so far:
* The "view" template, when we are just viewing a todo; this is what we've used in the tutorial thus far.
* The "editing" template, when we are editing a todo. We're about to create this.
Copy this block of code into the `Todo()` function, beneath your `useState()` hook but above the `return` statement:
```jsx
const editingTemplate = (
<form className="stack-small">
<div className="form-group">
<label className="todo-label" htmlFor={props.id}>
New name for {props.name}
</label>
<input id={props.id} className="todo-text" type="text" />
</div>
<div className="btn-group">
<button type="button" className="btn todo-cancel">
Cancel
<span className="visually-hidden">renaming {props.name}</span>
</button>
<button type="submit" className="btn btn\_\_primary todo-edit">
Save
<span className="visually-hidden">new name for {props.name}</span>
</button>
</div>
</form>
);
const viewTemplate = (
<div className="stack-small">
<div className="c-cb">
<input
id={props.id}
type="checkbox"
defaultChecked={props.completed}
onChange={() => props.toggleTaskCompleted(props.id)}
/>
<label className="todo-label" htmlFor={props.id}>
{props.name}
</label>
</div>
<div className="btn-group">
<button type="button" className="btn">
Edit <span className="visually-hidden">{props.name}</span>
</button>
<button
type="button"
className="btn btn\_\_danger"
onClick={() => props.deleteTask(props.id)}>
Delete <span className="visually-hidden">{props.name}</span>
</button>
</div>
</div>
);
```
We've now got the two different template structures β "edit" and "view" β defined inside two separate constants. This means that the `return` statement of `<Todo />` is now repetitious β it also contains a definition of the "view" template. We can clean this up by using **conditional rendering** to determine which template the component returns, and is therefore rendered in the UI.
Conditional rendering
---------------------
In JSX, we can use a condition to change what is rendered by the browser. To write a condition in JSX, we can use a ternary operator.
In the case of our `<Todo />` component, our condition is "Is this task being edited?" Change the `return` statement inside `Todo()` so that it reads like so:
```jsx
return <li className="todo">{isEditing ? editingTemplate : viewTemplate}</li>;
```
Your browser should render all your tasks just like before. To see the editing template, you will have to change the default `isEditing` state from `false` to `true` in your code for now; we will look at making the edit button toggle this in the next section!
Toggling the `<Todo />` templates
---------------------------------
At long last, we are ready to make our final core feature interactive. To start with, we want to call `setEditing()` with a value of `true` when a user presses the "Edit" button in our `viewTemplate`, so that we can switch templates.
Update the "Edit" button in the `viewTemplate` like so:
```jsx
<button type="button" className="btn" onClick={() => setEditing(true)}>
Edit <span className="visually-hidden">{props.name}</span>
</button>
```
Now we'll add the same `onClick` handler to the "Cancel" button in the `editingTemplate`, but this time we'll set `isEditing` to `false` so that it switches us back to the view template.
Update the "Cancel" button in the `editingTemplate` like so:
```jsx
<button
type="button"
className="btn todo-cancel"
onClick={() => setEditing(false)}>
Cancel
<span className="visually-hidden">renaming {props.name}</span>
</button>
```
With this code in place, you should be able to press the "Edit" and "Cancel" buttons in your todo items to toggle between templates.
![The eat todo item showing the view template, with edit and delete buttons available](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering/view.png)
![The eat todo item showing the edit template, with an input field to enter a new name, and cancel and save buttons available](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering/edit.png)
The next step is to actually make the editing functionality work.
Editing from the UI
-------------------
Much of what we're about to do will mirror the work we did in `Form.jsx`: as the user types in our new input field, we need to track the text they enter; once they submit the form, we need to use a callback prop to update our state with the new name of the task.
We'll start by making a new hook for storing and setting the new name. Still in `Todo.jsx`, put the following underneath the existing hook:
```jsx
const [newName, setNewName] = useState("");
```
Next, create a `handleChange()` function that will set the new name; put this underneath the hooks but before the templates:
```jsx
function handleChange(e) {
setNewName(e.target.value);
}
```
Now we'll update our `editingTemplate`'s `<input />` field, setting a `value` attribute of `newName`, and binding our `handleChange()` function to its `onChange` event. Update it as follows:
```jsx
<input
id={props.id}
className="todo-text"
type="text"
value={newName}
onChange={handleChange}
/>
```
Finally, we need to create a function to handle the edit form's `onSubmit` event. Add the following just below `handleChange()`:
```jsx
function handleSubmit(e) {
e.preventDefault();
props.editTask(props.id, newName);
setNewName("");
setEditing(false);
}
```
Remember that our `editTask()` callback prop needs the ID of the task we're editing as well as its new name.
Bind this function to the form's `submit` event by adding the following `onSubmit` handler to the `editingTemplate`'s `<form>`:
```jsx
<form className="stack-small" onSubmit={handleSubmit}>
```
You should now be able to edit a task in your browser. At this point, your `Todo.jsx` file should look like this:
```jsx
function Todo(props) {
const [isEditing, setEditing] = useState(false);
const [newName, setNewName] = useState("");
function handleChange(e) {
setNewName(e.target.value);
}
function handleSubmit(e) {
e.preventDefault();
props.editTask(props.id, newName);
setNewName("");
setEditing(false);
}
const editingTemplate = (
<form className="stack-small" onSubmit={handleSubmit}>
<div className="form-group">
<label className="todo-label" htmlFor={props.id}>
New name for {props.name}
</label>
<input
id={props.id}
className="todo-text"
type="text"
value={newName}
onChange={handleChange}
/>
</div>
<div className="btn-group">
<button
type="button"
className="btn todo-cancel"
onClick={() => setEditing(false)}>
Cancel
<span className="visually-hidden">renaming {props.name}</span>
</button>
<button type="submit" className="btn btn\_\_primary todo-edit">
Save
<span className="visually-hidden">new name for {props.name}</span>
</button>
</div>
</form>
);
const viewTemplate = (
<div className="stack-small">
<div className="c-cb">
<input
id={props.id}
type="checkbox"
defaultChecked={props.completed}
onChange={() => props.toggleTaskCompleted(props.id)}
/>
<label className="todo-label" htmlFor={props.id}>
{props.name}
</label>
</div>
<div className="btn-group">
<button
type="button"
className="btn"
onClick={() => {
setEditing(true);
}}>
Edit <span className="visually-hidden">{props.name}</span>
</button>
<button
type="button"
className="btn btn\_\_danger"
onClick={() => props.deleteTask(props.id)}>
Delete <span className="visually-hidden">{props.name}</span>
</button>
</div>
</div>
);
return <li className="todo">{isEditing ? editingTemplate : viewTemplate}</li>;
}
export default Todo;
```
Back to the filter buttons
--------------------------
Now that our main features are complete, we can think about our filter buttons. Currently, they repeat the "All" label, and they have no functionality! We will be reapplying some skills we used in our `<Todo />` component to:
* Create a hook for storing the active filter.
* Render an array of `<FilterButton />` elements that allow users to change the active filter between all, completed, and incomplete.
### Adding a filter hook
Add a new hook to your `App()` function that reads and sets a filter. We want the default filter to be `All` because all of our tasks should be shown initially:
```jsx
const [filter, setFilter] = useState("All");
```
### Defining our filters
Our goal right now is two-fold:
* Each filter should have a unique name.
* Each filter should have a unique behavior.
A JavaScript object would be a great way to relate names to behaviors: each key is the name of a filter; each property is the behavior associated with that name.
At the top of `App.jsx`, beneath our imports but above our `App()` function, let's add an object called `FILTER_MAP`:
```jsx
const FILTER\_MAP = {
All: () => true,
Active: (task) => !task.completed,
Completed: (task) => task.completed,
};
```
The values of `FILTER_MAP` are functions that we will use to filter the `tasks` data array:
* The `All` filter shows all tasks, so we return `true` for all tasks.
* The `Active` filter shows tasks whose `completed` prop is `false`.
* The `Completed` filter shows tasks whose `completed` prop is `true`.
Beneath our previous addition, add the following β here we are using the `Object.keys()` method to collect an array of `FILTER_NAMES`:
```jsx
const FILTER\_NAMES = Object.keys(FILTER\_MAP);
```
**Note:** We are defining these constants outside our `App()` function because if they were defined inside it, they would be recalculated every time the `<App />` component re-renders, and we don't want that. This information will never change no matter what our application does.
### Rendering the filters
Now that we have the `FILTER_NAMES` array, we can use it to render all three of our filters. Inside the `App()` function we can create a constant called `filterList`, which we will use to map over our array of names and return a `<FilterButton />` component. Remember, we need keys here, too.
Add the following underneath your `taskList` constant declaration:
```jsx
const filterList = FILTER\_NAMES.map((name) => (
<FilterButton key={name} name={name} />
));
```
Now we'll replace the three repeated `<FilterButton />`s in `App.jsx` with this `filterList`. Replace the following:
```jsx
<FilterButton />
<FilterButton />
<FilterButton />
```
With this:
```jsx
{filterList}
```
This won't work yet. We've got a bit more work to do first.
### Interactive filters
To make our filter buttons interactive, we should consider what props they need to utilize.
* We know that the `<FilterButton />` should report whether it is currently pressed, and it should be pressed if its name matches the current value of our filter state.
* We know that the `<FilterButton />` needs a callback to set the active filter. We can make direct use of our `setFilter` hook.
Update your `filterList` constant as follows:
```jsx
const filterList = FILTER\_NAMES.map((name) => (
<FilterButton
key={name}
name={name}
isPressed={name === filter}
setFilter={setFilter}
/>
));
```
In the same way as we did earlier with our `<Todo />` component, we now have to update `FilterButton.jsx` to utilize the props we have given it. Do each of the following, and remember to use curly braces to read these variables!
* Replace `all` with `{props.name}`.
* Set the value of `aria-pressed` to `{props.isPressed}`.
* Add an `onClick` handler that calls `props.setFilter()` with the filter's name.
With all of that done, your `FilterButton.jsx` file should read like this:
```jsx
function FilterButton(props) {
return (
<button
type="button"
className="btn toggle-btn"
aria-pressed={props.isPressed}
onClick={() => props.setFilter(props.name)}>
<span className="visually-hidden">Show </span>
<span>{props.name}</span>
<span className="visually-hidden"> tasks</span>
</button>
);
}
export default FilterButton;
```
Visit your browser again. You should see that the different buttons have been given their respective names. When you press a filter button, you should see its text take on a new outline β this tells you it has been selected. And if you look at your DevTool's Page Inspector while clicking the buttons, you'll see the `aria-pressed` attribute values change accordingly.
![The three filter buttons of the app - all, active, and completed - with a focus highlight around completed](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering/filter-buttons.png)
However, our buttons still don't actually filter the todos in the UI! Let's finish this off.
### Filtering tasks in the UI
Right now, our `taskList` constant in `App()` maps over the tasks state and returns a new `<Todo />` component for all of them. This is not what we want! A task should only render if it is included in the results of applying the selected filter. Before we map over the tasks state, we should filter it (with `Array.prototype.filter()`) to eliminate objects we don't want to render.
Update your `taskList` like so:
```jsx
const taskList = tasks
.filter(FILTER\_MAP[filter])
.map((task) => (
<Todo
id={task.id}
name={task.name}
completed={task.completed}
key={task.id}
toggleTaskCompleted={toggleTaskCompleted}
deleteTask={deleteTask}
editTask={editTask}
/>
));
```
In order to decide which callback function to use in `Array.prototype.filter()`, we access the value in `FILTER_MAP` that corresponds to the key of our filter state. When filter is `All`, for example, `FILTER_MAP[filter]` will evaluate to `() => true`.
Choosing a filter in your browser will now remove the tasks that do not meet its criteria. The count in the heading above the list will also change to reflect the list!
![The app with the filter buttons in place. Active is highlighted, so only the active todo items are being shown.](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering/filtered-todo-list.png)
Summary
-------
So that's it β our app is now functionally complete. However, now that we've implemented all of our features, we can make a few improvements to ensure that a wider range of users can use our app. Our next article rounds things off for our React tutorials by looking at including focus management in React, which can improve usability and reduce confusion for both keyboard-only and screen reader users.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Using Vue computed properties - Learn web development | Using Vue computed properties
=============================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
In this article we'll add a counter that displays the number of completed todo items, using a feature of Vue called computed properties. These work similarly to methods, but only re-run when one of their dependencies changes.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with node + npm installed.
|
| Objective: | To learn how to use Vue computed properties. |
Using computed properties
-------------------------
The aim here is to add a summary count of our to-do list. This can be useful for users, while also serving to label the list for assistive technology. If we have 2 of 5 items completed in our to-do list, our summary could read "2 items completed out of 5". While it might be tempting to do something like this:
```markup
<h2>
{{ToDoItems.filter(item => item.done).length}} out of
{{ToDoItems.length}} items completed
</h2>
```
It would be recalculated on every render. For a small app like this, that probably doesn't matter too much. For bigger apps, or when the expression is more complicated, that could cause a serious performance problem.
A better solution is to use Vue's computed properties. Computed Properties work similarly to methods, but only re-run when one of their dependencies changes. In our case, this would only re-run when the `ToDoItems` array changes.
To create a computed property, we need to add a `computed` property to our component object, much like the `methods` property we've used previously.
Adding a summary counter
------------------------
Add the following code to your `App` component object, below the `methods` property. The list summary method will get the number of finished `ToDoItems`, and return a string reporting this.
```js
computed: {
listSummary() {
const numberFinishedItems = this.ToDoItems.filter((item) =>item.done).length
return `${numberFinishedItems} out of ${this.ToDoItems.length} items completed`
}
}
```
Now we can add `{{listSummary}}` directly to our template; we'll add this inside an `<h2>` element, just above our `<ul>`. We'll also add an `id` and an `aria-labelledby` attribute to assign the `<h2>` contents to be a label for the `<ul>` element.
Add the described `<h2>` and update the `<ul>` inside your `App`'s template as follows:
```markup
<h2 id="list-summary">{{listSummary}}</h2>
<ul aria-labelledby="list-summary" class="stack-large">
<li v-for="item in ToDoItems" :key="item.id">
<to-do-item
:label="item.label"
:done="item.done"
:id="item.id"></to-do-item>
</li>
</ul>
```
You should now see the list summary in your app, and the total number of items update as you add more todo items! However, if you try checking and unchecking some items, you'll reveal a bug. Currently, we're not actually tracking the "done" data in any fashion, so the number of completed items does not change.
Tracking changes to "done"
--------------------------
We can use events to capture the checkbox update and manage our list accordingly.
Since we're not relying on a button press to trigger the change, we can attach a `@change` event handler to each checkbox instead of using `v-model`.
Update the `<input>` element in `ToDoItem.vue` to look like this.
```markup
<input
type="checkbox"
class="checkbox"
:id="id"
:checked="isDone"
@change="$emit('checkbox-changed')" />
```
Since all we need to do is emit that the checkbox was checked, we can include the `$emit()` inline.
In `App.vue`, add a new method called `updateDoneStatus()`, below your `addToDo()` method. This method should take one parameter: the todo item *id*. We want to find the item with the matching `id` and update its `done` status to be the opposite of its current status:
```js
updateDoneStatus(toDoId) {
const toDoToUpdate = this.ToDoItems.find((item) => item.id === toDoId)
toDoToUpdate.done = !toDoToUpdate.done
}
```
We want to run this method whenever a `ToDoItem` emits a `checkbox-changed` event, and pass in its `item.id` as the parameter. Update your `<to-do-item></to-do-item>` call as follows:
```markup
<to-do-item
:label="item.label"
:done="item.done"
:id="item.id"
@checkbox-changed="updateDoneStatus(item.id)">
</to-do-item>
```
Now if you check a `ToDoItem`, you should see the summary update appropriately!
![Our app, with a completed todo counter added. It currently reads 3 out of 5 items completed](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_computed_properties/todo-counter.png)
Summary
-------
In this article we've used a computed property to add a nice little feature to our app. We do however have bigger fish to fry β in the next article we will look at conditional rendering, and how we can use it to show an edit form when we want to edit existing todo items.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Working with Svelte stores - Learn web development | Working with Svelte stores
==========================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
In the last article we completed the development of our app, finished organizing it into components, and discussed some advanced techniques for dealing with reactivity, working with DOM nodes, and exposing component functionality. In this article we will show another way to handle state management in Svelte: Stores. Stores are global data repositories that hold values. Components can subscribe to stores and receive notifications when their values change.
| | |
| --- | --- |
| Prerequisites: |
At minimum, it is recommended that you are familiar with the core
HTML,
CSS, and
JavaScript languages, and
have knowledge of the
terminal/command line.
You'll need a terminal with node and npm installed to compile and build
your app.
|
| Objective: | Learn how to use Svelte stores |
Using stores we will create an `Alert` component that shows notifications on screen, which can receive messages from any component. In this case, the `Alert` component is independent of the rest β it is not a parent or child of any other β so the messages don't fit into the component hierarchy.
We will also see how to develop our own custom store to persist the todo information to web storage, allowing our to-dos to persist over page reloads.
Code along with us
------------------
### Git
Clone the GitHub repo (if you haven't already done it) with:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then to get to the current app state, run
```bash
cd mdn-svelte-tutorial/06-stores
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/06-stores
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To code along with us using the REPL, start at
https://svelte.dev/repl/d1fa84a5a4494366b179c87395940039?version=3.23.2
Dealing with our app state
--------------------------
We have already seen how our components can communicate with each other using props, two-way data binding, and events. In all these cases we were dealing with communication between parent and child components.
But not all application state belongs inside your application's component hierarchy. For example, information about the logged-in user, or whether the dark theme is selected or not.
Sometimes, your app state will need to be accessed by multiple components that are not hierarchically related, or by a regular JavaScript module.
Moreover, when your app becomes complicated and your component hierarchy gets complex, it might become too difficult for components to relay data between each other. In that case, moving to a global data store might be a good option. If you've already worked with Redux or Vuex, then you'll be familiar with how this kind of store works. Svelte stores offer similar features for state management.
A store is an object with a `subscribe()` method that allows interested parties to be notified whenever the store value changes and an optional `set()` method that allows you to set new values for the store. This minimal API is known as the store contract.
Svelte provides functions for creating readable, writable, and derived stores in the `svelte/store` module.
Svelte also provides a very intuitive way to integrate stores into its reactivity system using the reactive `$store` syntax. If you create your own stores honoring the store contract, you get this reactivity syntactic sugar for free.
Creating the Alert component
----------------------------
To show how to work with stores, we will create an `Alert` component. These kinds of widgets might also be known as popup notifications, toast, or notification bubbles.
Our `Alert` component will be displayed by the `App` component, but any component can send notifications to it. Whenever a notification arrives, the `Alert` component will be in charge of displaying it on screen.
### Creating a store
Let's start by creating a writable store. Any component will be able to write to this store, and the `Alert` component will subscribe to it and display a message whenever the store is modified.
1. Create a new file, `stores.js`, inside your `src` directory.
2. Give it the following content:
```js
import { writable } from "svelte/store";
export const alert = writable("Welcome to the to-do list app!");
```
**Note:** Stores can be defined and used outside Svelte components, so you can organize them in any way you please.
In the above code we import the `writable()` function from `svelte/store` and use it to create a new store called `alert` with an initial value of "Welcome to the to-do list app!". We then `export` the store.
### Creating the actual component
Let's now create our `Alert` component and see how we can read values from the store.
1. Create another new file named `src/components/Alert.svelte`.
2. Give it the following content:
```svelte
<script>
import { alert } from '../stores.js'
import { onDestroy } from 'svelte'
let alertContent = ''
const unsubscribe = alert.subscribe((value) => alertContent = value)
onDestroy(unsubscribe)
</script>
{#if alertContent}
<div on:click={() => alertContent = ''}>
<p>{ alertContent }</p>
</div>
{/if}
<style>
div {
position: fixed;
cursor: pointer;
margin-right: 1.5rem;
margin-left: 1.5rem;
margin-top: 1rem;
right: 0;
display: flex;
align-items: center;
border-radius: 0.2rem;
background-color: #565656;
color: #fff;
font-weight: 700;
padding: 0.5rem 1.4rem;
font-size: 1.5rem;
z-index: 100;
opacity: 95%;
}
div p {
color: #fff;
}
div svg {
height: 1.6rem;
fill: currentcolor;
width: 1.4rem;
margin-right: 0.5rem;
}
</style>
```
Let's walk through this piece of code in detail.
* At the beginning we import the `alert` store.
* Next we import the `onDestroy()` lifecycle function, which lets us execute a callback after the component has been unmounted.
* We then create a local variable named `alertContent`. Remember that we can access top-level variables from the markup, and whenever they are modified, the DOM will update accordingly.
* Then we call the method `alert.subscribe()`, passing it a callback function as a parameter. Whenever the value of the store changes, the callback function will be called with the new value as its parameter. In the callback function we just assign the value we receive to the local variable, which will trigger the update of the component's DOM.
* The `subscribe()` method also returns a cleanup function, which takes care of releasing the subscription. So we subscribe when the component is being initialized, and use `onDestroy` to unsubscribe when the component is unmounted.
* Finally we use the `alertContent` variable in our markup, and if the user clicks on the alert we clean it.
* At the end we include a few CSS lines to style our `Alert` component.
This setup allows us to work with stores in a reactive way. When the value of the store changes, the callback is executed. There we assign a new value to a local variable, and thanks to Svelte reactivity all our markup and reactive dependencies are updated accordingly.
### Using the component
Let's now use our component.
1. In `App.svelte` we'll import the component. Add the following import statement below the existing one:
```js
import Alert from "./components/Alert.svelte";
```
2. Then call the `Alert` component just above the `Todos` call, like this:
```svelte
<Alert />
<Todos {todos} />
```
3. Load your test app now, and you should now see the `Alert` message on screen. You can click on it to dismiss it.
![A simple notification in the top right-hand corner of an app saying welcome to the to-do list app](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores/01-alert-message.png)
Making stores reactive with the reactive `$store` syntax
--------------------------------------------------------
This works, but you'll have to copy and paste all this code every time you want to subscribe to a store:
```svelte
<script>
import myStore from "./stores.js";
import { onDestroy } from "svelte";
let myStoreContent = "";
const unsubscribe = myStore.subscribe((value) => (myStoreContent = value));
onDestroy(unsubscribe);
</script>
{myStoreContent}
```
That's too much boilerplate for Svelte! Being a compiler, Svelte has more resources to make our lives easier. In this case Svelte provides the reactive `$store` syntax, also known as auto-subscription. In simple terms, you just prefix the store with the `$` sign and Svelte will generate the code to make it reactive automatically. So our previous code block can be replaced with this:
```svelte
<script>
import myStore from "./stores.js";
</script>
{$myStore}
```
And `$myStore` will be fully reactive. This also applies to your own custom stores. If you implement the `subscribe()` and `set()` methods, as we'll do later, the reactive `$store` syntax will also apply to your stores.
1. Let's apply this to our `Alert` component. Update the `<script>` and markup sections of `Alert.svelte` as follows:
```svelte
<script>
import { alert } from '../stores.js'
</script>
{#if $alert}
<div on:click={() => $alert = ''}>
<p>{ $alert }</p>
</div>
{/if}
```
2. Check your app again and you'll see that this works just like before. That's much better!
Behind the scenes Svelte has generated the code to declare the local variable `$alert`, subscribe to the `alert` store, update `$alert` whenever the store's content is modified, and unsubscribe when the component is unmounted. It will also generate the `alert.set()` statements whenever we assign a value to `$alert`.
The end result of this nifty trick is that you can access global stores just as easily as using reactive local variables.
This is a perfect example of how Svelte puts the compiler in charge of better developer ergonomics, not only saving us from typing boilerplate, but also generating less error-prone code.
Writing to our store
--------------------
Writing to our store is just a matter of importing it and executing `$store = 'new value'`. Let's use it in our `Todos` component.
1. Add the following `import` statement below the existing ones:
```js
import { alert } from "../stores.js";
```
2. Update your `addTodo()` function like so:
```js
function addTodo(name) {
todos = [...todos, { id: newTodoId, name, completed: false }];
$alert = `Todo '${name}' has been added`;
}
```
3. Update `removeTodo()` like so:
```js
function removeTodo(todo) {
todos = todos.filter((t) => t.id !== todo.id);
todosStatus.focus(); // give focus to status heading
$alert = `Todo '${todo.name}' has been deleted`;
}
```
4. Update the `updateTodo()` function to this:
```js
function updateTodo(todo) {
const i = todos.findIndex((t) => t.id === todo.id);
if (todos[i].name !== todo.name)
$alert = `todo '${todos[i].name}' has been renamed to '${todo.name}'`;
if (todos[i].completed !== todo.completed)
$alert = `todo '${todos[i].name}' marked as ${
todo.completed ? "completed" : "active"
}`;
todos[i] = { ...todos[i], ...todo };
}
```
5. Add the following reactive block beneath the block that starts with `let filter = 'all'`:
```js
$: {
if (filter === "all") {
$alert = "Browsing all to-dos";
} else if (filter === "active") {
$alert = "Browsing active to-dos";
} else if (filter === "completed") {
$alert = "Browsing completed to-dos";
}
}
```
6. And finally for now, update the `const checkAllTodos` and `const removeCompletedTodos` blocks as follows:
```js
const checkAllTodos = (completed) => {
todos = todos.map((t) => ({ ...t, completed }));
$alert = `${completed ? "Checked" : "Unchecked"} ${todos.length} to-dos`;
};
const removeCompletedTodos = () => {
$alert = `Removed ${todos.filter((t) => t.completed).length} to-dos`;
todos = todos.filter((t) => !t.completed);
};
```
7. So basically, we've imported the store and updated it on every event, which causes a new alert to show each time. Have a look at your app again, and try adding/deleting/updating a few to-dos!
As soon as we execute `$alert = β¦`, Svelte will run `alert.set()`. Our `Alert` component β like every subscriber to the alert store β will be notified when it receives a new value, and thanks to Svelte reactivity its markup will be updated.
We could do the same within any component or `.js` file.
**Note:** Outside Svelte components you cannot use the `$store` syntax. That's because the Svelte compiler won't touch anything outside Svelte components. In that case you'll have to rely on the `store.subscribe()` and `store.set()` methods.
Improving our Alert component
-----------------------------
It's a bit annoying having to click on the alert to get rid of it. It would be better if the notification just disappeared after a couple of seconds.
Let's see how to do that. We'll specify a prop with the milliseconds to wait before clearing the notification, and we'll define a timeout to remove the alert. We'll also take care of clearing the timeout when the `Alert` component is unmounted to prevent memory leaks.
1. Update the `<script>` section of your `Alert.svelte` component like so:
```js
import { onDestroy } from "svelte";
import { alert } from "../stores.js";
export let ms = 3000;
let visible;
let timeout;
const onMessageChange = (message, ms) => {
clearTimeout(timeout);
if (!message) {
// hide Alert if message is empty
visible = false;
} else {
visible = true; // show alert
if (ms > 0) timeout = setTimeout(() => (visible = false), ms); // and hide it after ms milliseconds
}
};
$: onMessageChange($alert, ms); // whenever the alert store or the ms props changes run onMessageChange
onDestroy(() => clearTimeout(timeout)); // make sure we clean-up the timeout
```
2. And update the `Alert.svelte` markup section like so:
```svelte
{#if visible}
<div on:click={() => visible = false}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M12.432 0c1.34 0 2.01.912 2.01 1.957 0 1.305-1.164 2.512-2.679 2.512-1.269 0-2.009-.75-1.974-1.99C9.789 1.436 10.67 0 12.432 0zM8.309 20c-1.058 0-1.833-.652-1.093-3.524l1.214-5.092c.211-.814.246-1.141 0-1.141-.317 0-1.689.562-2.502 1.117l-.528-.88c2.572-2.186 5.531-3.467 6.801-3.467 1.057 0 1.233 1.273.705 3.23l-1.391 5.352c-.246.945-.141 1.271.106 1.271.317 0 1.357-.392 2.379-1.207l.6.814C12.098 19.02 9.365 20 8.309 20z"/></svg>
<p>{ $alert }</p>
</div>
{/if}
```
Here we first create the prop `ms` with a default value of 3000 (milliseconds). Then we create an `onMessageChange()` function that will take care of controlling whether the Alert is visible or not. With `$: onMessageChange($alert, ms)` we tell Svelte to run this function whenever the `$alert` store or the `ms` prop changes.
Whenever the `$alert` store changes, we'll clean up any pending timeout. If `$alert` is empty, we set `visible` to `false` and the `Alert` will be removed from the DOM. If it is not empty, we set `visible` to `true` and use the `setTimeout()` function to clear the alert after `ms` milliseconds.
Finally, with the `onDestroy()` lifecycle function, we make sure to call the `clearTimeout()` function.
We also added an SVG icon above the alert paragraph, to make it look a bit nicer. Try it out again, and you should see the changes.
Making our Alert component accessible
-------------------------------------
Our `Alert` component is working fine, but it's not very friendly to assistive technologies. The problem is elements that are dynamically added and removed from the page. While visually evident to users who can see the page, they may not be so obvious to users of assistive technologies, like screen readers. To handle those situations, we can take advantage of ARIA live regions, which provide a way to programmatically expose dynamic content changes so that they can be detected and announced by assistive technologies.
We can declare a region that contains dynamic content that should be announced by assistive technologies with the `aria-live` property followed by the politeness setting, which is used to set the priority with which screen readers should handle updates to that regions. The possible settings are `off`, `polite`, or `assertive`.
For common situations, you also have several predefined specialized `role` values that can be used, like `log`, `status` and `alert`.
In our case, just adding a `role="alert"` to the `<div>` container will do the trick, like this:
```svelte
<div role="alert" on:click={() => visible = false}>
```
In general, testing your applications using screen readers is a good idea, not only to discover accessibility issues but also to get used to how visually impaired people use the Web. You have several options, like NVDA for Windows, ChromeVox for Chrome, Orca on Linux, and VoiceOver for macOS and iOS, among other options.
To learn more about detecting and fixing accessibility issues, check out our Handling common accessibility problems article.
Using the store contract to persist our to-dos
----------------------------------------------
Our little app lets us manage our to-dos quite easily, but is rather useless if we always get the same list of hardcoded to-dos when we reload it. To make it truly useful, we have to find out how to persist our to-dos.
First we need some way for our `Todos` component to give back the updated to-dos to its parent. We could emit an updated event with the list of to-dos, but it's easier just to bind the `todos` variable. Let's open `App.svelte` and try it.
1. First, add the following line below your `todos` array:
```js
$: console.log("todos", todos);
```
2. Next, update your `Todos` component call as follows:
```svelte
<Todos bind:todos />
```
**Note:** `<Todos bind:todos />` is just a shortcut for `<Todos bind:todos={todos} />`.
3. Go back to your app, try adding some to-dos, then go to your developer tools web console. You'll see that every modification we make to our to-dos is reflected in the `todos` array defined in `App.svelte` thanks to the `bind` directive.
Now we have to find a way to persist these to-dos. We could implement some code in our `App.svelte` component to read and save our to-dos to web storage or to a web service.
But wouldn't it be better if we could develop some generic store that allows us to persist its content? This would allow us to use it just like any other store, and abstract away the persistence mechanism. We could create a store that syncs its content to web storage, and later develop another one that syncs against a web service. Switching between them would be trivial and we wouldn't have to touch `App.svelte` at all.
### Saving our to-dos
So let's start by using a regular writable store to save our to-dos.
1. Open the file `stores.js` and add the following store below the existing one:
```js
export const todos = writable([]);
```
2. That was easy. Now we need to import the store and use it in `App.svelte`. Just remember that to access the to-dos now we have to use the `$todos` reactive `$store` syntax.
Update your `App.svelte` file like this:
```svelte
<script>
import Todos from "./components/Todos.svelte";
import Alert from "./components/Alert.svelte";
import { todos } from "./stores.js";
$todos = [
{ id: 1, name: "Create a Svelte starter app", completed: true },
{ id: 2, name: "Create your first component", completed: true },
{ id: 3, name: "Complete the rest of the tutorial", completed: false }
];
</script>
<Alert />
<Todos bind:todos={$todos} />
```
3. Try it out; everything should work. Next we'll see how to define our own custom stores.
### How to implement a store contract: The theory
You can create your own stores without relying on `svelte/store` by implementing the store contract. Its features must work like so:
1. A store must contain a `subscribe()` method, which must accept as its argument a subscription function. All of a store's active subscription functions must be called whenever the store's value changes.
2. The `subscribe()` method must return an `unsubscribe()` function, which when called must stop its subscription.
3. A store may optionally contain a `set()` method, which must accept as its argument a new value for the store, and which synchronously calls all of the store's active subscription functions. A store with a `set()` method is called a writable store.
First, let's add the following `console.log()` statements to our `App.svelte` component to see the `todos` store and its content in action. Add these lines below the `todos` array:
```js
console.log("todos store - todos:", todos);
console.log("todos store content - $todos:", $todos);
```
When you run the app now, you'll see something like this in your web console:
![web console showing the functions and contents of the todos store](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores/02-svelte-store-in-action.png)
As you can see, our store is just an object containing `subscribe()`, `set()`, and `update()` methods, and `$todos` is our array of to-dos.
Just for reference, here's a basic working store implemented from scratch:
```js
export const writable = (initial\_value = 0) => {
let value = initial_value; // content of the store
let subs = []; // subscriber's handlers
const subscribe = (handler) => {
subs = [...subs, handler]; // add handler to the array of subscribers
handler(value); // call handler with current value
return () => (subs = subs.filter((sub) => sub !== handler)); // return unsubscribe function
};
const set = (new\_value) => {
if (value === new_value) return; // same value, exit
value = new_value; // update value
subs.forEach((sub) => sub(value)); // update subscribers
};
const update = (update\_fn) => set(update\_fn(value)); // update function
return { subscribe, set, update }; // store contract
};
```
Here we declare `subs`, which is an array of subscribers. In the `subscribe()` method we add the handler to the `subs` array and return a function that, when executed, will remove the handler from the array.
When we call `set()`, we update the value of the store and call each handler, passing the new value as a parameter.
Usually you don't implement stores from scratch; instead you'd use the writable store to create custom stores with domain-specific logic. In the following example we create a counter store, which will only allow us to add one to the counter or reset its value:
```js
import { writable } from "svelte/store";
function myStore() {
const { subscribe, set, update } = writable(0);
return {
subscribe,
addOne: () => update((n) => n + 1),
reset: () => set(0),
};
}
```
If our to-do list app gets too complex, we could let our to-dos store handle every state modification. We could move all the methods that modify the `todo` array (like `addTodo()`, `removeTodo()`, etc.) from our `Todos` component to the store. If you have a central place where all the state modification is applied, components could just call those methods to modify the app's state and reactively display the info exposed by the store. Having a unique place to handle state modifications makes it easier to reason about the state flow and spot issues.
Svelte won't force you to organize your state management in a specific way; it just provides the tools for you to choose how to handle it.
### Implementing our custom to-dos store
Our to-do list app is not particularly complex, so we won't move all our modification methods into a central place. We'll just leave them as they are, and instead concentrate on persisting our to-dos.
**Note:** If you are following this guide working from the Svelte REPL, you won't be able to complete this step. For security reasons the Svelte REPL works in a sandboxed environment which will not let you access web storage, and you will get a "The operation is insecure" error. In order to follow this section, you'll have to clone the repo and go to the `mdn-svelte-tutorial/06-stores` folder, or you can directly download the folder's content with `npx degit opensas/mdn-svelte-tutorial/06-stores`.
To implement a custom store that saves its content to web storage, we will need a writable store that does the following:
* Initially reads the value from web storage, and if it's not present, initializes it with a default value
* Whenever the value is modified, updates the store itself and also the data in local storage
Moreover, because web storage only supports saving string values, we will have to convert from object to string when saving, and vice versa when we are loading the value from local storage.
1. Create a new file called `localStore.js`, in your `src` directory.
2. Give it the following content:
```js
import { writable } from "svelte/store";
export const localStore = (key, initial) => {
// receives the key of the local storage and an initial value
const toString = (value) => JSON.stringify(value, null, 2); // helper function
const toObj = JSON.parse; // helper function
if (localStorage.getItem(key) === null) {
// item not present in local storage
localStorage.setItem(key, toString(initial)); // initialize local storage with initial value
}
const saved = toObj(localStorage.getItem(key)); // convert to object
const { subscribe, set, update } = writable(saved); // create the underlying writable store
return {
subscribe,
set: (value) => {
localStorage.setItem(key, toString(value)); // save also to local storage as a string
return set(value);
},
update,
};
};
```
* Our `localStore` will be a function that when executed initially reads its content from web storage, and returns an object with three methods: `subscribe()`, `set()`, and `update()`.
* When we create a new `localStore`, we'll have to specify the key of the web storage and an initial value. We then check if the value exists in web storage and, if not, we create it.
* We use the `localStorage.getItem(key)` and `localStorage.setItem(key, value)` methods to read and write information to web storage, and the `toString()` and `toObj()` (which uses `JSON.parse()`) helper functions to convert the values.
* Next, we convert the string content received from the web storage to an object, and save that object in our store.
* Finally, every time we update the contents of the store, we also update the web storage, with the value converted to a string.Notice that we only had to redefine the `set()` method, adding the operation to save the value to web storage. The rest of the code is mostly initializing and converting stuff.
3. Now we will use our local store from `stores.js` to create our locally persisted to-dos store.
Update `stores.js` like so:
```js
import { writable } from "svelte/store";
import { localStore } from "./localStore.js";
export const alert = writable("Welcome to the to-do list app!");
const initialTodos = [
{ id: 1, name: "Visit MDN web docs", completed: true },
{ id: 2, name: "Complete the Svelte Tutorial", completed: false },
];
export const todos = localStore("mdn-svelte-todo", initialTodos);
```
Using `localStore('mdn-svelte-todo', initialTodos)`, we are configuring the store to save the data in web storage under the key `mdn-svelte-todo`. We also set a couple of todos as initial values.
4. Now let's get rid of the hardcoded to-dos in `App.svelte`. Update its contents as follows. We are basically just deleting the `$todos` array and the `console.log()` statements:
```svelte
<script>
import Todos from './components/Todos.svelte'
import Alert from './components/Alert.svelte'
import { todos } from './stores.js'
</script>
<Alert />
<Todos bind:todos={$todos} />
```
**Note:** This is the only change we have to make in order to use our custom store. `App.svelte` is completely transparent in terms of what kind of store we are using.
5. Go ahead and try your app again. Create a few to-dos and then close the browser. You may even stop the Svelte server and restart it. Upon revisiting the URL, your to-dos will still be there.
6. You can also inspect it in the DevTools console. In the web console, enter the command `localStorage.getItem('mdn-svelte-todo')`. Make some changes to your app, like pressing the *Uncheck All* button, and check the web storage content once more. You will get something like this:
![to-do app with web console view alongside it, showing that when a to-do is changed in the app, the corresponding entry is changed in web storage](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores/03-persisting-todos-to-local-storage.png)
Svelte stores provide a very simple and lightweight, but extremely powerful, way to handle complex app state from a global data store in a reactive way. And because Svelte compiles our code, it can provide the `$store` auto-subscription syntax that allows us to work with stores in the same way as local variables. Because stores have a minimal API, it's very simple to create our custom stores to abstract away the inner workings of the store itself.
Bonus track: Transitions
------------------------
Let's change the subject now and do something fun and different: add an animation to our alerts. Svelte provides a whole module to define transitions and animations so we can make our user interfaces more appealing.
A transition is applied with the transition:fn directive, and is triggered by an element entering or leaving the DOM as a result of a state change. The `svelte/transition` module exports seven functions: `fade`, `blur`, `fly`, `slide`, `scale`, `draw`, and `crossfade`.
Let's give our `Alert` component a fly `transition`. We'll open the `Alert.svelte` file and import the `fly` function from the `svelte/transition` module.
1. Put the following `import` statement below the existing ones:
```js
import { fly } from "svelte/transition";
```
2. To use it, update your opening `<div>` tag like so:
```svelte
<div role="alert" on:click={() => visible = false}
transition:fly
>
```
Transitions can also receive parameters, like this:
```svelte
<div role="alert" on:click={() => visible = false}
transition:fly="{{delay: 250, duration: 300, x: 0, y: -100, opacity: 0.5}}"
>
```
**Note:** The double curly braces are not special Svelte syntax. It's just a literal JavaScript object being passed as a parameter to the fly transition.
3. Try your app out again, and you'll see that the notifications now look a bit more appealing.
**Note:** Being a compiler allows Svelte to optimize the size of our bundle by excluding features that are not used. In this case, if we compile our app for production with `npm run build`, our `public/build/bundle.js` file will weight a little less than 22 KB. If we remove the `transitions:fly` directive Svelte is smart enough to realize the fly function is not being used and the `bundle.js` file size will drop down to just 18 KB.
This is just the tip of the iceberg. Svelte has lots of options for dealing with animations and transitions. Svelte also supports specifying different transitions to apply when the element is added or removed from the DOM with the `in:fn`/`out:fn` directives, and it also allows you to define your custom CSS and JavaScript transitions. It also has several easing functions to specify the rate of change over time. Have a look at the ease visualizer to explore the various ease functions available.
The code so far
---------------
### Git
To see the state of the code as it should be at the end of this article, access your copy of our repo like this:
```bash
cd mdn-svelte-tutorial/07-next-steps
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/07-next-steps
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To see the current state of the code in a REPL, visit:
https://svelte.dev/repl/378dd79e0dfe4486a8f10823f3813190?version=3.23.2
Summary
-------
In this article we added two new features: an `Alert` component and persisting `todos` to web storage.
* This allowed us to showcase some advanced Svelte techniques. We developed the `Alert` component to show how to implement cross-component state management using stores. We also saw how to auto-subscribe to stores to seamlessly integrate them with the Svelte reactivity system.
* Then we saw how to implement our own store from scratch, and also how to extend Svelte's writable store to persist data to web storage.
* At the end we had a look at using the Svelte `transition` directive to implement animations on DOM elements.
In the next article we will learn how add TypeScript support to our Svelte application. To take advantage of all its features, we will also port our entire application to TypeScript.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Beginning our Angular todo list app - Learn web development | Beginning our Angular todo list app
===================================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
At this point, we are ready to start creating our to-do list application using Angular. The finished application will display a list of to-do items and includes editing, deleting, and adding features. In this article you will get to know your application structure, and work up to displaying a basic list of to-do items.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
|
| Objective: |
To create our basic app structure, get it displaying a list of to-do
items, and understand fundamental Angular concepts such as component
structure, sharing data between components, and looping content
creation.
|
The to-do application structure
-------------------------------
Just like a basic application that doesn't use a framework, an Angular application has an `index.html`.
Within the `<body>` tag of the `index.html`, Angular uses a special element β `<app-root>` β to insert your main component, which in turn includes other components you create.
Generally, you don't need to touch the `index.html`, instead focusing your work within specialized areas of your application called components.
### Organize your application with components
Components are a central building block of Angular applications.
This to-do application has two components β a component as a foundation for your application, and a component for handling to-do items.
Each component is made up of a TypeScript class, HTML, and CSS.
TypeScript transpiles, or converts, into JavaScript, which means that your application ultimately ends up in plain JavaScript but you have the convenience of using Typescript's extended features and streamlined syntax.
### Dynamically change the UI with \*ngIf and \*ngFor
This tutorial also covers two important Angular directives for dynamically altering the structure of the DOM.
A directive is like a command that you can use in your HTML to affect change in your application.
The first directive that this tutorial covers is Angular's iterator, `*ngFor`.
`*ngFor` can dynamically create DOM elements based on items in an array.
The second directive that you learn in this tutorial is `*ngIf`.
You can use `*ngIf` to add or remove elements from the DOM based on a condition.
For example, if users want to edit an item in the to-do list, you can provide them with the means to edit the item.
If they do not want to edit an item, you can remove the interface for editing.
### Share data between components
In this to-do application, you configure your components to share data.
To add new items to the to do list, the main component has to send the new item to the second component.
This second component manages the items and takes care of editing, marking as done, and deleting individual items.
You accomplish sharing data between Angular components with special decorators called `@Input()` and `@Output()`.
You use these decorators to specify that certain properties allow data to go into or out of a component.
To use `@Output()`, you raise an event in one component so that the other component knows that there is data available.
Define Item
-----------
In the `app` directory, create a new file named `item.ts` with the following contents:
```ts
export interface Item {
description: string;
done: boolean;
}
```
You won't use this file until later, but it is a good time to know and record your knowledge of what an `item` is. The `Item` interface creates an `item` object model so that your application will understand what an `item` is. For this to-do list, an `item` is an object that has a description and can be done.
Add logic to AppComponent
-------------------------
Now that you know what an `item` is, you can give your application some items by adding them to the TypeScript file, `app.component.ts`.
In `app.component.ts`, replace the contents with the following:
```js
import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent {
title = "todo";
filter: "all" | "active" | "done" = "all";
allItems = [
{ description: "eat", done: true },
{ description: "sleep", done: false },
{ description: "play", done: false },
{ description: "laugh", done: false },
];
get items() {
if (this.filter === "all") {
return this.allItems;
}
return this.allItems.filter((item) =>
this.filter === "done" ? item.done : !item.done
);
}
}
```
The first line is a JavaScript import that imports Angular.
The `@Component()` decorator specifies metadata about the `AppComponent`.
The default metadata properties are as follows:
* `selector`: Tells you the name of the CSS selector that you use in a template to instantiate this component. Here it is `'app-root'`.
In the `index.html`, within the `body` tag, the Angular CLI added `<app-root></app-root>` when generating your application.
You use all component selectors in the same way by adding them to other component HTML templates.
* `templateUrl`: Specifies the HTML file to associate with this component.
Here it is, './app.component.html',
* `styleUrls`: Provides the location and name of the file for your styles that apply specifically to this component. Here it is `'./app.component.css'`.
The `filter` property is of type `union`, which means `filter` could have the value of `all`, `active`, or `done`.
With the `union` type, if you make a typo in the value you assign to the `filter` property, TypeScript lets you know so that you can catch the bug early.
This guide shows you how to add filtering in a later step, but you can also use a filter to show the default list of all the items.
The `allItems` array contains the to-do items and whether they are `done`.
The first item, `eat`, has a `done` value of true.
The getter, `get items()`, retrieves the items from the `allItems` array if the `filter` is equal to `all`.
Otherwise, `get items()` returns the `done` items or the outstanding items depending on how the user filters the view.
The getter also establishes the name of the array as `items`, which you'll use in the next section.
Add HTML to the AppComponent template
-------------------------------------
To see the list of items in the browser, replace the contents of `app.component.html` with the following HTML:
```html
<div class="main">
<h1>My To Do List</h1>
<h2>What would you like to do today?</h2>
<ul>
<li \*ngFor="let item of items">{{item.description}}</li>
</ul>
</div>
```
The `<li>` contains an `*ngFor`, a built-in Angular directive that iterates over the items in the `items` array.
For each item, `*ngFor` creates a new `<li>`.
The double curly braces that contain `item.description` instructs Angular to populate each `<li>` with the text of each item's description.
In the browser, you should see the list of items as follows:
```
My To Do List
What would you like to do today?
* eat
* sleep
* play
* laugh
```
Add items to the list
---------------------
A to-do list needs a way to add items.
In `app.component.ts`, add the following method to the class:
```ts
addItem(description: string) {
this.allItems.unshift({
description,
done: false
});
}
```
The `addItem()` method takes an item that the user provides and adds it to the array when the user clicks the **Add** button.
The `addItem()` method uses the array method `unshift()` to add a new item to the beginning of the array and the top of the list.
You could alternatively use `push()`, which would add the new item to the end of the array and the bottom of the list.
To use the `addItem()` method, edit the HTML in the `AppComponent` template.
In `app.component.html`, replace the `<h2>` with the following:
```html
<label for="addItemInput">What would you like to do today?</label>
<input
#newItem
placeholder="add an item"
(keyup.enter)="addItem(newItem.value); newItem.value = ''"
class="lg-text-input"
id="addItemInput" />
<button class="btn-primary" (click)="addItem(newItem.value)">Add</button>
```
In the above HTML, `#newItem` is a template variable. The template variable in this case uses the `<input>` element as its value. Template variables can be referred to anywhere in the component's template.
When the user types a new item in the `<input>` field and presses **Enter**, the `addItem()` method adds the value to the `allItems` array.
Pressing the **Enter** key also resets the value of `<input>` to an empty string. The template variable `#newItem` is used to access the value of the `<input>` element in the template.
Instead of pressing the **Enter** key, the user can also click the **Add** button, which calls the same `addItem()` method.
Summary
-------
By now you should have your basic list of to-dos displaying in your browser. That's great progress! Of course, we have a lot more to do. In the next article we will look at adding some styling to our application.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Accessibility in React - Learn web development | Accessibility in React
======================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
In our final tutorial article, we'll focus on (pun intended) accessibility, including focus management in React, which can improve usability and reduce confusion for both keyboard-only and screen reader users.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
|
| Objective: | To learn about implementing keyboard accessibility in React. |
Including keyboard users
------------------------
At this point, we've implemented all the features we set out to implement. Users can add a new task, check and uncheck tasks, delete tasks, or edit task names. Also, they can filter their task list by all, active, or completed tasks.
Or, at least, they can do all of these things with a mouse. Unfortunately, these features are not very accessible to keyboard-only users. Let's explore this now.
Exploring the keyboard usability problem
----------------------------------------
Start by clicking on the input at the top of our app, as if you're going to add a new task. You'll see a thick, dashed outline around that input. This outline is your visual indicator that the browser is currently focused on this element. Press the `Tab` key, and you will see the outline appear around the "Add" button beneath the input. This shows you that the browser's focus has moved.
Press `Tab` a few more times, and you will see this dashed focus indicator move between each of the filter buttons. Keep going until the focus indicator is around the first "Edit" button. Press `Enter`.
The `<Todo />` component will switch templates, as we designed, and you'll see a form that lets us edit the name of the task.
But where did our focus indicator go?
When we switch between templates in our `<Todo />` component, we completely remove the elements from the old template and replace them with the elements from the new template. That means the element that we were focused on no longer exists, so there's no visual cue as to where the browser's focus is. This could confuse a wide variety of users β particularly users who rely on the keyboard, or users who use assistive technology.
To improve the experience for keyboard and assistive technology users, we should manage the browser's focus ourselves.
### Aside: a note on our focus indicator
If you click the "All", "Active", or "Completed" filter buttons with your mouse, you *won't* see a visible focus indicator, but you will do if you move between them with the `Tab` key on your keyboard. Don't worry β your code isn't broken!
Our CSS file uses the `:focus-visible` pseudo-class to provide custom styling for the focus indicator, and the browser uses a set of internal rules to determine when to show it to the user. Generally, the browser *will* show a focus indicator in response to keyboard input, and *might* show it in response to mouse input. `<button>` elements *don't* show a focus indicator in response to mouse input, while `<input>` elements *do*.
The behavior of `:focus-visible` is more selective than the older `:focus` pseudo-class, with which you might be more familiar. `:focus` shows a focus indicator in many more situations, and you can use it instead of or in combination with `:focus-visible` if you prefer.
Focusing between templates
--------------------------
When a user changes the `<Todo />` template from viewing to editing, we should focus on the `<input>` used to rename it; when they change back from editing to viewing, we should move focus back to the "Edit" button.
### Targeting our elements
Up to this point, we've been writing JSX components and letting React build the resulting DOM behind the scenes. Most of the time, we don't need to target specific elements in the DOM because we can use React's state and props to control what gets rendered. To manage focus, however, we *do* need to be able to target specific DOM elements.
This is where the `useRef()` hook comes in.
First, change the `import` statement at the top of `Todo.jsx` so that it includes `useRef`:
```jsx
import { useRef, useState } from "react";
```
`useRef()` creates an object with a single property: `current`. Refs can store any values we want them to, and we can look up those values later. We can even store references to DOM elements, which is exactly what we're going to do here.
Next, create two new constants beneath the `useState()` hooks in your `Todo()` function. Each should be a ref β one for the "Edit" button in the view template and one for the edit field in the editing template.
```jsx
const editFieldRef = useRef(null);
const editButtonRef = useRef(null);
```
These refs have a default value of `null` to make it clear that they'll be empty until they're attached to their DOM elements. To attach them to their elements, we'll add the special `ref` attribute to each element's JSX, and set the values of those attributes to the appropriately named `ref` objects.
Update the `<input>` in your editing template so that it reads like this:
```jsx
<input
id={props.id}
className="todo-text"
type="text"
value={newName}
onChange={handleChange}
ref={editFieldRef}
/>
```
Update the "Edit" button in your view template so that it reads like this:
```jsx
<button
type="button"
className="btn"
onClick={() => setEditing(true)}
ref={editButtonRef}>
Edit <span className="visually-hidden">{props.name}</span>
</button>
```
Doing this will populate our `editFieldRef` and `editButtonRef` with references to the DOM elements they're attached to, but *only* after React has rendered the component. Test that out for yourself: add the following line somewhere in the body of your `Todo()` function, below where `editButtonRef` is initialized:
```jsx
console.log(editButtonRef.current);
```
You'll see that the value of `editButtonRef.current` is `null` when the component first renders, but if you click an "Edit" button, it will log the `<input>` element to the console. This is because the ref is populated only after the component renders, and clicking the "Edit" button causes the component to re-render. Be sure to delete this log before moving on.
**Note:** Your logs will appear 6 times because we have 3 instances of `<Todo />` in our app and React renders our components twice in development.
We're getting closer! To take advantage of our newly referenced elements, we need to use another React hook: `useEffect()`.
### Implementing `useEffect()`
`useEffect()` is so named because it runs any side-effects that we'd like to add to the render process but which can't be run inside the main function body. `useEffect()` runs right after a component renders, meaning the DOM elements we referenced in the previous section will be available for us to use.
Change the import statement of `Todo.jsx` again to add `useEffect`:
```jsx
import { useEffect, useRef, useState } from "react";
```
`useEffect()` takes a function as an argument; this function is executed *after* the component renders. To demonstrate this, put the following `useEffect()` call just above the `return` statement in the body of `Todo()`, and pass a function into it that logs the words "side effect" to your console:
```jsx
useEffect(() => {
console.log("side effect");
});
```
To illustrate the difference between the main render process and code run inside `useEffect()`, add another log β put this one below the previous addition:
```jsx
console.log("main render");
```
Now, open the app in your browser. You should see both messages in your console, with each one repeating multiple times. Note how "main render" logged first, and "side effect" logged second, even though the "side effect" log appears first in the code.
```
main render Todo.jsx
side effect Todo.jsx
```
Again, the logs are ordered this way because code inside `useEffect()` runs *after* the component renders. This takes some getting used to, just keep it in mind as you move forward. For now, delete `console.log("main render")` and we'll move on to implementing our focus management.
### Focusing on our editing field
Now that we know our `useEffect()` hook works, we can manage focus with it. As a reminder, we want to focus on the editing field when we switch to the editing template.
Update your existing `useEffect()` hook so that it reads like this:
```jsx
useEffect(() => {
if (isEditing) {
editFieldRef.current.focus();
}
}, [isEditing]);
```
These changes make it so that, if `isEditing` is true, React reads the current value of the `editFieldRef` and moves browser focus to it. We also pass an array into `useEffect()` as a second argument. This array is a list of values `useEffect()` should depend on. With these values included, `useEffect()` will only run when one of those values changes. We only want to change focus when the value of `isEditing` changes.
Try it now: use the `Tab` key to navigate to one of the "Edit" buttons, then press `Enter`. You should see the `<Todo />` component switch to its editing template, and the browser focus indicator should appear around the `<input>` element!
### Moving focus back to the edit button
At first glance, getting React to move focus back to our "Edit" button when the edit is saved or cancelled appears deceptively easy. Surely we could add a condition to our `useEffect` to focus on the edit button if `isEditing` is `false`? Let's try it now β update your `useEffect()` call like so:
```jsx
useEffect(() => {
if (isEditing) {
editFieldRef.current.focus();
} else {
editButtonRef.current.focus();
}
}, [isEditing]);
```
This kind of works. If you use your keyboard to trigger the "Edit" button (remember: `Tab` to it and press `Enter`), you'll see that your focus moves between the Edit `<input>` and "Edit" button as you start and end an edit. However, you may have noticed a new problem β the "Edit" button in the final `<Todo />` component is focused immediately on page load before we even interact with the app!
Our `useEffect()` hook is behaving exactly as we designed it: it runs as soon as the component renders, sees that `isEditing` is `false`, and focuses the "Edit" button. There are three instances of `<Todo />`, and focus is given to the "Edit" button of the one that renders last.
We need to refactor our approach so that focus changes only when `isEditing` changes from one value to another.
More robust focus management
----------------------------
To meet our refined criteria, we need to know not just the value of `isEditing`, but also *when that value has changed*. To do that, we need to be able to read the previous value of the `isEditing` constant. Using pseudocode, our logic should be something like this:
```jsx
if (wasNotEditingBefore && isEditingNow) {
focusOnEditField();
} else if (wasEditingBefore && isNotEditingNow) {
focusOnEditButton();
}
```
The React team has discussed ways to get a component's previous state, and provided an example hook we can use for the job.
### Enter `usePrevious()`
Paste the following code near the top of `Todo.jsx`, above your `Todo()` function.
```jsx
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
```
`usePrevious()` is a *custom hook* that tracks a value across renders. It:
1. Uses the `useRef()` hook to create an empty `ref`.
2. Returns the `ref`'s `current` value to the component that called it.
3. Calls `useEffect()` and updates the value stored in `ref.current` after each rendering of the calling component.
The behavior of `useEffect()` is key to this functionality. Because `ref.current` is updated inside a `useEffect()` call, it's always one step behind whatever value is in the component's main render cycle β hence the name `usePrevious()`.
### Using `usePrevious()`
Now we can define a `wasEditing` constant to track the previous value of `isEditing`; this is achieved by calling `usePrevious` with `isEditing` as an argument. Add the following inside `Todo()`, below the `useRef` lines:
```jsx
const wasEditing = usePrevious(isEditing);
```
You can see how `usePrevious()` behaves by adding a console log beneath this line:
```jsx
console.log(wasEditing);
```
In this log, the `current` value of `wasEditing` will always be the previous value of `isEditing`. Click on the "Edit" and "Cancel" button a few times to watch it change, then delete this log when you're ready to move on.
With this `wasEditing` constant, we can update our `useEffect()` hook to implement the pseudocode we discussed before:
```jsx
useEffect(() => {
if (!wasEditing && isEditing) {
editFieldRef.current.focus();
} else if (wasEditing && !isEditing) {
editButtonRef.current.focus();
}
}, [wasEditing, isEditing]);
```
Note that the logic of `useEffect()` now depends on `wasEditing`, so we provide it in the array of dependencies.
Try using your keyboard to activate the "Edit" and "Cancel" buttons in the `<Todo />` component; you'll see the browser focus indicator move appropriately, without the problem we discussed at the start of this section.
Focusing when the user deletes a task
-------------------------------------
There's one last keyboard experience gap: when a user deletes a task from the list, the focus vanishes. We're going to follow a pattern similar to our previous changes: we'll make a new ref, and utilize our `usePrevious()` hook, so that we can focus on the list heading whenever a user deletes a task.
### Why the list heading?
Sometimes, the place we want to send our focus to is obvious: when we toggled our `<Todo />` templates, we had an origin point to "go back" to β the "Edit" button. In this case however, since we're completely removing elements from the DOM, we have no place to go back to. The next best thing is an intuitive location somewhere nearby. The list heading is our best choice because it's close to the list item the user will delete, and focusing on it will tell the user how many tasks are left.
### Creating our ref
Import the `useRef()` and `useEffect()` hooks into `App.jsx` β you'll need them both below:
```jsx
import { useState, useRef, useEffect } from "react";
```
Next, declare a new ref inside the `App()` function, just above the `return` statement:
```jsx
const listHeadingRef = useRef(null);
```
### Prepare the heading
Heading elements like our `<h2>` are not usually focusable. This isn't a problem β we can make any element programmatically focusable by adding the attribute `tabindex="-1"` to it. This means *only focusable with JavaScript*. You can't press `Tab` to focus on an element with a tabindex of `-1` the same way you could do with a `<button>` or `<a>` element (this can be done using `tabindex="0"`, but that's not appropriate in this case).
Let's add the `tabindex` attribute β written as `tabIndex` in JSX β to the heading above our list of tasks, along with our `listHeadingRef`:
```jsx
<h2 id="list-heading" tabIndex="-1" ref={listHeadingRef}>
{headingText}
</h2>
```
**Note:** The `tabindex` attribute is excellent for accessibility edge cases, but you should take **great care** not to overuse it. Only apply a `tabindex` to an element when you're sure that making it focusable will benefit your user somehow. In most cases, you should utilize elements that can naturally take focus, such as buttons, anchors, and inputs. Irresponsible usage of `tabindex` could have a profoundly negative impact on keyboard and screen reader users!
### Getting previous state
We want to focus on the element associated with our ref (via the `ref` attribute) only when our user deletes a task from their list. That's going to require the `usePrevious()` hook we used earlier on. Add it to the top of your `App.jsx` file, just below the imports:
```jsx
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
```
Now add the following, above the `return` statement inside the `App()` function:
```jsx
const prevTaskLength = usePrevious(tasks.length);
```
Here we are invoking `usePrevious()` to track the previous length of the tasks array.
**Note:** Since we're now utilizing `usePrevious()` in two files, it might be more efficient to move the `usePrevious()` function into its own file, export it from that file, and import it where you need it. Try doing this as an exercise once you've got to the end.
### Using `useEffect()` to control our heading focus
Now that we've stored how many tasks we previously had, we can set up a `useEffect()` hook to run when our number of tasks changes, which will focus the heading if the number of tasks we have now is less than it previously was β that is, we deleted a task!
Add the following into the body of your `App()` function, just below your previous additions:
```jsx
useEffect(() => {
if (tasks.length < prevTaskLength) {
listHeadingRef.current.focus();
}
}, [tasks.length, prevTaskLength]);
```
We only try to focus on our list heading if we have fewer tasks now than we did before. The dependencies passed into this hook ensure it will only try to re-run when either of those values (the number of current tasks, or the number of previous tasks) changes.
Now, when you use your keyboard to delete a task in your browser, you will see our dashed focus outline appear around the heading above the list.
Finished!
---------
You've just finished building a React app from the ground up! Congratulations! The skills you've learned here will be a great foundation to build on as you continue working with React.
Most of the time, you can be an effective contributor to a React project even if all you do is think carefully about components and their state and props. Remember to always write the best HTML you can.
`useRef()` and `useEffect()` are somewhat advanced features, and you should be proud of yourself for using them! Look out for opportunities to practice them more, because doing so will allow you to create inclusive experiences for users. Remember: our app would have been inaccessible to keyboard users without them!
**Note:** If you need to check your code against our version, you can find a finished version of the sample React app code in our todo-react repository. For a running live version, see https://mdn.github.io/todo-react.
In the very last article we'll present you with a list of React resources that you can use to go further in your learning.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Styling Vue components with CSS - Learn web development | Styling Vue components with CSS
===============================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
The time has finally come to make our app look a bit nicer. In this article we'll explore the different ways of styling Vue components with CSS.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with node + npm installed.
|
| Objective: | To learn about styling Vue components. |
Styling Vue components with CSS
-------------------------------
Before we move on to add more advanced features to our app, we should add some basic CSS to make it look better. Vue has three common approaches to styling apps:
* External CSS files.
* Global styles in Single File Components (`.vue` files).
* Component-scoped styles in Single File Components.
To help familiarize you with each one, we'll use a combination of all three to give our app a nicer look and feel.
Styling with external CSS files
-------------------------------
You can include external CSS files and apply them globally to your app. Let's look at how this is done.
To start with, create a file called `reset.css` in the `src/assets` directory. Files in this folder get processed by Webpack. This means we can use CSS pre-processors (like SCSS) or post-processors (like PostCSS).
While this tutorial will not be using such tools, it's good to know that when including such code in the assets folder it will be processed automatically.
Add the following contents to the `reset.css` file:
```css
/\*reset.css\*/
/\* RESETS \*/
\*,
\*::before,
\*::after {
box-sizing: border-box;
}
\*:focus {
outline: 3px dashed #228bec;
}
html {
font: 62.5% / 1.15 sans-serif;
}
h1,
h2 {
margin-bottom: 0;
}
ul {
list-style: none;
padding: 0;
}
button {
border: none;
margin: 0;
padding: 0;
width: auto;
overflow: visible;
background: transparent;
color: inherit;
font: inherit;
line-height: normal;
-webkit-font-smoothing: inherit;
-moz-osx-font-smoothing: inherit;
appearance: none;
}
button::-moz-focus-inner {
border: 0;
}
button,
input,
optgroup,
select,
textarea {
font-family: inherit;
font-size: 100%;
line-height: 1.15;
margin: 0;
}
button,
input {
/\* 1 \*/
overflow: visible;
}
input[type="text"] {
border-radius: 0;
}
body {
width: 100%;
max-width: 68rem;
margin: 0 auto;
font:
1.6rem/1.25 "Helvetica Neue",
Helvetica,
Arial,
sans-serif;
background-color: #f5f5f5;
color: #4d4d4d;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
}
@media screen and (min-width: 620px) {
body {
font-size: 1.9rem;
line-height: 1.31579;
}
}
/\*END RESETS\*/
```
Next, in your `src/main.js` file, import the `reset.css` file like so:
```js
import "./assets/reset.css";
```
This will cause the file to get picked up during the build step and automatically added to our site.
The reset styles should be applied to the app now. The images below show the look of the app before and after the reset is applied.
Before:
![the todo app with partial styling added; the app is now in a card, but some of the internal features still need styling](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling/todo-app-unstyled.png)
After:
![the todo app with partial styling added; the app is now in a card, but some of the internal features still need styling](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling/todo-app-reset-styles.png)
Noticeable changes include the removal of the list bullets, background color changes, and changes to the base button and input styles.
Adding global styles to Single File Components
----------------------------------------------
Now that we've reset our CSS to be uniform across browsers, we need to customize the styles a bit more. There are some styles that we want to apply across components in our app. While adding these files directly to the `reset.css` stylesheet would work, we'll instead add them to the `<style>` tags in `App.vue` to demonstrate how this can be used.
There are already some styles present in the file. Let's remove those and replace them with the styles below. These styles do a few things β adding some styling to buttons and inputs, and customizing the `#app` element and its children.
Update your `App.vue` file's `<style>` element so it looks like so:
```html
<style>
/\* Global styles \*/
.btn {
padding: 0.8rem 1rem 0.7rem;
border: 0.2rem solid #4d4d4d;
cursor: pointer;
text-transform: capitalize;
}
.btn\_\_danger {
color: #fff;
background-color: #ca3c3c;
border-color: #bd2130;
}
.btn\_\_filter {
border-color: lightgrey;
}
.btn\_\_danger:focus {
outline-color: #c82333;
}
.btn\_\_primary {
color: #fff;
background-color: #000;
}
.btn-group {
display: flex;
justify-content: space-between;
}
.btn-group > \* {
flex: 1 1 auto;
}
.btn-group > \* + \* {
margin-left: 0.8rem;
}
.label-wrapper {
margin: 0;
flex: 0 0 100%;
text-align: center;
}
[class\*="\_\_lg"] {
display: inline-block;
width: 100%;
font-size: 1.9rem;
}
[class\*="\_\_lg"]:not(:last-child) {
margin-bottom: 1rem;
}
@media screen and (min-width: 620px) {
[class\*="\_\_lg"] {
font-size: 2.4rem;
}
}
.visually-hidden {
position: absolute;
height: 1px;
width: 1px;
overflow: hidden;
clip: rect(1px 1px 1px 1px);
clip: rect(1px, 1px, 1px, 1px);
clip-path: rect(1px, 1px, 1px, 1px);
white-space: nowrap;
}
[class\*="stack"] > \* {
margin-top: 0;
margin-bottom: 0;
}
.stack-small > \* + \* {
margin-top: 1.25rem;
}
.stack-large > \* + \* {
margin-top: 2.5rem;
}
@media screen and (min-width: 550px) {
.stack-small > \* + \* {
margin-top: 1.4rem;
}
.stack-large > \* + \* {
margin-top: 2.8rem;
}
}
/\* End global styles \*/
#app {
background: #fff;
margin: 2rem 0 4rem 0;
padding: 1rem;
padding-top: 0;
position: relative;
box-shadow:
0 2px 4px 0 rgb(0 0 0 / 20%),
0 2.5rem 5rem 0 rgb(0 0 0 / 10%);
}
@media screen and (min-width: 550px) {
#app {
padding: 4rem;
}
}
#app > \* {
max-width: 50rem;
margin-left: auto;
margin-right: auto;
}
#app > form {
max-width: 100%;
}
#app h1 {
display: block;
min-width: 100%;
width: 100%;
text-align: center;
margin: 0;
margin-bottom: 1rem;
}
</style>
```
If you check the app, you'll see that our todo list is now in a card, and we have some better formatting of our to-do items. Now we can go through and begin editing our components to use some of these styles.
![the todo app with partial styling added; the app is now in a card, but some of the internal features still need styling](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling/todo-app-partial-styles.png)
### Adding CSS classes in Vue
We should apply the button CSS classes to the `<button>` in our `ToDoForm` component. Since Vue templates are valid HTML, this is done in the same way to how you might do it in plain HTML β by adding a `class=""` attribute to the element.
Add `class="btn btn__primary btn__lg"` to your form's `<button>` element:
```html
<button type="submit" class="btn btn\_\_primary btn\_\_lg">Add</button>
```
While we're here, there's one more semantic and styling change we can make. Since our form denotes a specific section of our page, it could benefit from an `<h2>` element. The label, however, already denotes the purpose of the form. To avoid repeating ourselves, let's wrap our label in an `<h2>`. There are a few other global CSS styles which we can add as well. We'll also add the `input__lg` class to our `<input>` element.
Update your `ToDoForm` template so that it looks like this:
```html
<template>
<form @submit.prevent="onSubmit">
<h2 class="label-wrapper">
<label for="new-todo-input" class="label\_\_lg">
What needs to be done?
</label>
</h2>
<input
type="text"
id="new-todo-input"
name="new-todo"
autocomplete="off"
v-model.lazy.trim="label"
class="input\_\_lg" />
<button type="submit" class="btn btn\_\_primary btn\_\_lg">Add</button>
</form>
</template>
```
Let's also add the `stack-large` class to the `<ul>` tag in our `App.vue` file. This will help improve the spacing of our to-do items a bit.
Update it as follows:
```html
<ul aria-labelledby="list-summary" class="stack-large">
β¦
</ul>
```
Adding scoped styles
--------------------
The last component we want to style is our `ToDoItem` component. To keep the style definitions close to the component we can add a `<style>` element inside it. However, if these styles alter things outside of this component, it could be challenging to track down the styles responsible, and fix the problem. This is where the `scoped` attribute can be useful β this attaches a unique HTML `data` attribute selector to all of your styles, preventing them from colliding globally.
To use the `scoped` modifier, create a `<style>` element inside `ToDoItem.vue`, at the bottom of the file, and give it a `scoped` attribute:
```html
<style scoped>
/\* β¦ \*/
</style>
```
Next, copy the following CSS into the newly created `<style>` element:
```css
.custom-checkbox > .checkbox-label {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
color: #0b0c0c;
display: block;
margin-bottom: 5px;
}
.custom-checkbox > .checkbox {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
box-sizing: border-box;
width: 100%;
height: 40px;
height: 2.5rem;
margin-top: 0;
padding: 5px;
border: 2px solid #0b0c0c;
border-radius: 0;
appearance: none;
}
.custom-checkbox > input:focus {
outline: 3px dashed #fd0;
outline-offset: 0;
box-shadow: inset 0 0 0 2px;
}
.custom-checkbox {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
font-weight: 400;
font-size: 1.6rem;
line-height: 1.25;
display: block;
position: relative;
min-height: 40px;
margin-bottom: 10px;
padding-left: 40px;
clear: left;
}
.custom-checkbox > input[type="checkbox"] {
-webkit-font-smoothing: antialiased;
cursor: pointer;
position: absolute;
z-index: 1;
top: -2px;
left: -2px;
width: 44px;
height: 44px;
margin: 0;
opacity: 0;
}
.custom-checkbox > .checkbox-label {
font-size: inherit;
font-family: inherit;
line-height: inherit;
display: inline-block;
margin-bottom: 0;
padding: 8px 15px 5px;
cursor: pointer;
touch-action: manipulation;
}
.custom-checkbox > label::before {
content: "";
box-sizing: border-box;
position: absolute;
top: 0;
left: 0;
width: 40px;
height: 40px;
border: 2px solid currentcolor;
background: transparent;
}
.custom-checkbox > input[type="checkbox"]:focus + label::before {
border-width: 4px;
outline: 3px dashed #228bec;
}
.custom-checkbox > label::after {
box-sizing: content-box;
content: "";
position: absolute;
top: 11px;
left: 9px;
width: 18px;
height: 7px;
transform: rotate(-45deg);
border: solid;
border-width: 0 0 5px 5px;
border-top-color: transparent;
opacity: 0;
background: transparent;
}
.custom-checkbox > input[type="checkbox"]:checked + label::after {
opacity: 1;
}
@media only screen and (min-width: 40rem) {
label,
input,
.custom-checkbox {
font-size: 19px;
font-size: 1.9rem;
line-height: 1.31579;
}
}
```
Now we need to add some CSS classes to our template to connect the styles.
To the root `<div>`, add a `custom-checkbox` class. To the `<input>`, add a `checkbox` class. Last of all, to the `<label>` add a `checkbox-label` class. The updated template is below:
```html
<template>
<div class="custom-checkbox">
<input type="checkbox" :id="id" :checked="isDone" class="checkbox" />
<label :for="id" class="checkbox-label">{{label}}</label>
</div>
</template>
```
The app should now have custom checkboxes. Your app should look something like the screenshot below.
![the todo app with complete styling. The input form is now styled properly, and the todo items now have spacing and custom checkboxes](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling/todo-app-complete-styles.png)
Summary
-------
Our work is done on the styling of our sample app. In the next article we'll return to adding some more functionality to our app, namely using a computed property to add a count of completed todo items to our app.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Deployment and next steps - Learn web development | Deployment and next steps
=========================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
In the previous article we learned about Svelte's TypeScript support, and how to use it to make your application more robust. In this final article we will look at how to deploy your application and get it online, and also share some of the resources that you should go on to, to continue your Svelte learning journey.
| | |
| --- | --- |
| Prerequisites: |
At minimum, it is recommended that you are familiar with the core
HTML,
CSS, and
JavaScript languages, and
have knowledge of the
terminal/command line.
You'll need a terminal with node + npm installed to compile and build
your app.
|
| Objective: |
Learn how to prepare our Svelte app for production, and what learning
resources you should visit next.
|
Code along with us
------------------
### Git
Clone the GitHub repo (if you haven't already done it) with:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then to get to the current app state, run
```bash
cd mdn-svelte-tutorial/08-next-steps
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/08-next-steps
```
Remember to run `npm install && npm run dev` to start your app in development mode.
Compiling our app
-----------------
So far we've been running our app in development mode with `npm run dev`. As we saw earlier, this instruction tells Svelte to compile our components and JavaScript files into a `public/build/bundle.js` file and all the CSS sections of our components into `public/build/bundle.css`. It also starts a development server and watches for changes, recompiling the app and refreshing the page when a change occurs.
Your generated `bundle.js` and `bundle.css` files will be something like this (file size on the left):
```
504 Jul 13 02:43 bundle.css
95981 Jul 13 02:43 bundle.js
```
To compile our application for production we have to run `npm run build` instead. In this case, Svelte won't launch a web server or keep watching for changes. It will however minify and compress our JavaScript files using terser.
So, after running `npm run build`, our generated `bundle.js` and `bundle.css` files will be more like this:
```
504 Jul 13 02:43 bundle.css
21782 Jul 13 02:43 bundle.js
```
Try running `npm run build` in your app's root directory now. You might get a warning, but you can ignore this for now.
Our whole app is now just 21 KB β 8.3 KB when gzipped. There are no additional runtimes or dependencies to download, parse, execute, and keep running in memory. Svelte analyzed our components and compiled the code to vanilla JavaScript.
A look behind the Svelte compilation process
--------------------------------------------
By default, when you create a new app with `npx degit sveltejs/template my-svelte-project`, Svelte will use rollup as the module bundler.
**Note:** There is also an official template for using webpack and also many community-maintained plugins for other bundlers.
In the file `package.json` you can see that the `build` and `dev` scripts are just calling rollup:
```json
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "sirv public"
},
```
In the `dev` script we are passing the `-w` argument, which tells rollup to watch files and rebuild on changes.
If we have a look at the `rollup.config.js` file, we can see that the Svelte compiler is just a rollup plugin:
```js
import svelte from 'rollup-plugin-svelte';
// β¦
import { terser } from 'rollup-plugin-terser';
const production = !process.env.ROLLUP\_WATCH;
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
},
plugins: [
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file - better for performance
css: (css) => {
css.write('public/build/bundle.css');
}
}),
```
Later on in the same file you'll also see how rollup minimizes our scripts in production mode and launches a local server in development mode:
```js
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser()
],
```
There are many plugins for rollup that allow you to customize its behavior. A particularly useful plugin which is also maintained by the Svelte team is svelte-preprocess, which pre-processes many different languages in Svelte files such as PostCSS, SCSS, Less, CoffeeScript, SASS, and TypeScript.
Deploying your Svelte application
---------------------------------
From the point of view of a web server, a Svelte application is nothing more than a bunch of HTML, CSS, and JavaScript files. All you need is a web server capable of serving static files, which means you have plenty of options to choose from. Let's look at a couple of examples.
**Note:** the following section could be applied to any client-side static website requiring a build step, not just Svelte apps.
### Deploying with Vercel
One of the easiest ways to deploy a Svelte application is using Vercel. Vercel is a cloud platform specifically tailored for static sites, which has out-of-the-box support for most common front-end tools, Svelte being one of them.
To deploy our app, follow these steps.
1. register for an account with Vercel.
2. Navigate to the root of your app and run `npx vercel`; the first time you do it, you'll be prompted to enter your email address, and follow the steps in the email sent to that address, for security purposes.
3. Run `npx vercel` again, and you'll be prompted to answer a few questions, like this:
```bash
npx vercel
```
```
Vercel CLI 19.1.2
? Set up and deploy "./mdn-svelte-tutorial"? [Y/n] y
? Which scope do you want to deploy to? opensas
? Link to existing project? [y/N] n
? What's your project's name? mdn-svelte-tutorial
? In which directory is your code located? ./
Auto-detected Project Settings (Svelte):
- Build Command: `npm run build` or `rollup -c`
- Output Directory: public
- Development Command: sirv public --single --dev --port $PORT
? Want to override the settings? [y/N] n
Linked to opensas/mdn-svelte-tutorial (created .vercel)
Inspect: https://vercel.com/opensas/mdn-svelte-tutorial/[...] [1s]
β
Production: https://mdn-svelte-tutorial.vercel.app [copied to clipboard] [19s]
Deployed to production. Run `vercel --prod` to overwrite later (https://vercel.link/2F).
To change the domain or build command, go to https://zeit.co/opensas/mdn-svelte-tutorial/settings
```
4. Accept all the defaults, and you'll be fine.
5. Once it has finished deploying, go to the "Production" URL in your browser, and you'll see the app deployed!
You can also import a Svelte git project into Vercel from GitHub, GitLab, or BitBucket.
**Note:** you can globally install Vercel with `npm i -g vercel` so you don't have to use `npx` to run it.
### Automatic deployment to GitLab pages
For hosting static files there are several online services that allow you to automatically deploy your site whenever you push changes to a git repository. Most of them involve setting up a deployment pipeline that gets triggered on every `git push`, and takes care of building and deploying your website.
To demonstrate this, we will deploy our todos app to GitLab Pages.
1. First you'll have to register at GitLab and then create a new project. Give you new project a short, easy name like "mdn-svelte-todo". You will have a remote URL that points to your new GitLab git repository, like `[email protected]:[your-user]/[your-project].git`.
2. Before you start to upload content to your git repository, it is a good practice to add a `.gitignore` file to tell git which files to exclude from source control. In our case we will tell git to exclude files in the `node_modules` directory by creating a `.gitignore` file in the root folder of your local project, with the following content:
```bash
node_modules/
```
3. Now let's go back to GitLab. After creating a new repo GitLab will greet you with a message explaining different options to upload your existing files. Follow the steps listed under the *Push an existing folder* heading:
```bash
cd your_root_directory # Go into your project's root directory
git init
git remote add origin https://gitlab.com/[your-user]/mdn-svelte-todo.git
git add .
git commit -m "Initial commit"
git push -u origin main
```
**Note:** You could use the `git` protocol instead of `https`, which is faster and saves you from typing your username and password every time you access your origin repo. To use it you'll have to create an SSH key pair. Your origin URL will be like this: `[email protected]:[your-user]/mdn-svelte-todo.git`.
With these instructions we initialize a local git repository, then set our remote origin (where we will push our code to) as our repo on GitLab. Next we commit all the files to the local git repo, and then push those to the remote origin on GitLab.
GitLab uses a built-in tool called GitLab CI/CD to build your site and publish it to the GitLab Pages server. The sequence of scripts that GitLab CI/CD runs to accomplish this task is created from a file named `.gitlab-ci.yml`, which you can create and modify at will. A specific job called `pages` in the configuration file will make GitLab aware that you are deploying a GitLab Pages website.
Let's have a go at doing this now.
1. Create a `.gitlab-ci.yml` file inside your project's root and give it the following content:
```yaml
image: node:latest
pages:
stage: deploy
script:
- npm install
- npm run build
artifacts:
paths:
- public
only:
- main
```
Here we are telling GitLab to use an image with the latest version of node to build our app. Next we are declaring a `pages` job, to enable GitLab Pages. Whenever there's a push to our repo, GitLab will run `npm install` and `npm run build` to build our application. We are also telling GitLab to deploy the contents of the `public` folder. On the last line, we are configuring GitLab to redeploy our app only when there's a push to our main branch.
2. Since our app will be published at a subdirectory (like `https://your-user.gitlab.io/mdn-svelte-todo`), we'll have to make the references to the JavaScript and CSS files in our `public/index.html` file relative. To do this, we just remove the leading slashes (`/`) from the `/global.css`, `/build/bundle.css`, and `/build/bundle.js` URLs, like this:
```html
<title>Svelte To-Do list</title>
<link rel="icon" type="image/png" href="favicon.png" />
<link rel="stylesheet" href="global.css" />
<link rel="stylesheet" href="build/bundle.css" />
<script defer src="build/bundle.js"></script>
```
Do this now.
3. Now we just have to commit and push our changes to GitLab. Do this by running the following commands:
```bash
git add public/index.html
git add .gitlab-ci.yml
git commit -m "Added .gitlab-ci.yml file and fixed index.html absolute paths"
git push
```
Whenever there's a job running GitLab will display an icon showing the process of the job. Clicking on it will let you inspect the output of the job.
![gitlab screenshot showing a deployed commit, which add a gitlab ci file, and changes bundle paths to relative](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_deployment_next/01-gitlab-pages-deploy.png)
You can also check the progress of the current and previous jobs from the *CI / CD* > *Jobs* menu option of your GitLab project.
![a gitlab ci job shown in the gitlab ui, running a lot of commands](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_deployment_next/02-gitlab-pages-job.png)
Once GitLab finishes building and publishing your app, it will be accessible at `https://your-user.gitlab.io/mdn-svelte-todo/`; in my case it's `https://opensas.gitlab.io/mdn-svelte-todo/`. You can check your page's URL in GitLab's UI β see the *Settings* > *Pages* menu option.
With this configuration, whenever you push changes to the GitLab repo, the application will be automatically rebuilt and deployed to GitLab Pages.
Learning more about Svelte
--------------------------
In this section we'll give you some resources and projects to go and check out, to take your Svelte learning further.
### Svelte documentation
To go further and learn more about Svelte, you should definitely visit the Svelte homepage. There you'll find many articles explaining Svelte's philosophy. If you haven't already done it, make sure you go through the Svelte interactive tutorial. We already covered most of its content, so it won't take you much time to complete it β you should consider it as practice!
You can also consult the Svelte API docs and the available examples.
To understand the motivations behind Svelte, you should read Rich Harris's Rethinking reactivity presentation on YouTube. He is the creator of Svelte, so he has a couple of things to say about it. You also have the interactive slides available here which are, unsurprisingly, built with Svelte. If you liked it, you will also enjoy The Return of 'Write Less, Do More' presentation, which Rich Harris gave at JSCAMP 2019.
### Related projects
There are other projects related to Svelte that are worth checking out:
* Sapper: An application framework powered by Svelte that provides server-side rendering (SSR), code splitting, file-based routing and offline support, and more. Think of it as Next.js for Svelte. If you are planning to develop a fairly complex web application you should definitely have a look at this project.
* Svelte Native: A mobile application framework powered by Svelte. Think of it as React Native for Svelte.
* Svelte for VS Code: The officially supported VS Code plugin for working with `.svelte` files, which we looked at in our TypeScript article.
### Other learning resources
* There's a complete course about Svelte and Sapper by Rich Harris, available at Frontend Masters.
* Even though Svelte is a relatively young project there are lots of tutorials and courses available on the web, so it's difficult to make a recommendation.
* Nevertheless, Svelte.js β The Complete Guide by Academind is a very popular option with great ratings.
* The Svelte Handbook, by Flavio Copes, is also a useful reference for learning the main Svelte concepts.
* If you prefer to read books, there's Svelte and Sapper in Action by Mark Volkman, expected to be published in September 2020, but which you can already preview online for free.
* If you want dive deeper and understand the inner working of Svelte's compiler you should check Tan Li Hau's *Compile Svelte in your head* blog posts. Here's Part 1, Part 2, and Part 3.
### Interacting with the community
There are a number of different ways to get support and interact with the Svelte community:
* svelte.dev/chat: Svelte's Discord server.
* @sveltejs: The official Twitter account.
* @sveltesociety: Svelte community Twitter account.
* Svelte Recipes: Community-driven repository of recipes, tips, and best practices to solve common problems.
* Svelte questions on StackOverflow: Questions with the `svelte` tag at SO.
* Svelte reddit community: Svelte community discussion and content rating site at reddit.
* Svelte DEV community: A collection of Svelte-related technical articles and tutorials from the DEV.to community.
Finito
------
Congratulations! You have completed the Svelte tutorial. In the previous articles we went from zero knowledge about Svelte to building and deploying a complete application.
* We learned about Svelte philosophy and what sets it apart from other front-end frameworks.
* We saw how to add dynamic behavior to our website, how to organize our app in components and different ways to share information among them.
* We took advantage of the Svelte reactivity system and learned how to avoid common pitfalls.
* We also saw some advanced concepts and techniques to interact with DOM elements and to programmatically extend HTML element capabilities using the `use` directive.
* Then we saw how to use stores to work with a central data repository, and we created our own custom store to persist our application's data to Web Storage.
* We also took a look at Svelte's TypeScript support.
In this article we've learned about a couple of zero-fuss options to deploy our app in production and seen how to set up a basic pipeline to deploy our app to GitLab on every commit. Then we provided you with a list of Svelte resources to go further with your Svelte learning.
Congratulations! After completing this series of tutorials you should have a strong base from which to start developing professional web applications with Svelte.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Creating our first Vue component - Learn web development | Creating our first Vue component
================================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
Now it's time to dive deeper into Vue, and create our own custom component β we'll start by creating a component to represent each item in the todo list. Along the way, we'll learn about a few important concepts such as calling components inside other components, passing data to them via props, and saving data state.
**Note:** If you need to check your code against our version, you can find a finished version of the sample Vue app code in our todo-vue repository. For a running live version, see https://mdn.github.io/todo-vue/.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with
Node
and
npm
installed.
|
| Objective: |
To learn how to create a Vue component, render it inside another
component, pass data into it using props, and save its state.
|
Creating a ToDoItem component
-----------------------------
Let's create our first component, which will display a single todo item. We'll use this to build our list of todos.
1. In your `moz-todo-vue/src/components` directory, create a new file named `ToDoItem.vue`. Open the file in your code editor.
2. Create the component's template section by adding `<template></template>` to the top of the file.
3. Create a `<script></script>` section below your template section. Inside the `<script>` tags, add a default exported object `export default {}`, which is your component object.
Your file should now look like this:
```markup
<template></template>
<script>
export default {};
</script>
```
We can now begin to add actual content to our `ToDoItem`. Vue templates are currently only allowed a single root element β one element needs to wrap everything inside the template section (this will change when Vue 3 comes out). We'll use a `<div>` for that root element.
1. Add an empty `<div>` inside your component template now.
2. Inside that `<div>`, let's add a checkbox and a corresponding label. Add an `id` to the checkbox, and a `for` attribute mapping the checkbox to the label, as shown below.
```markup
<template>
<div>
<input type="checkbox" id="todo-item" />
<label for="todo-item">My Todo Item</label>
</div>
</template>
```
### Using TodoItem inside our app
This is all fine, but we haven't added the component to our app yet, so there's no way to test it and see if everything is working. Let's add it now.
1. Open up `App.vue` again.
2. At the top of your `<script>` tag, add the following to import your `ToDoItem` component:
```js
import ToDoItem from "./components/ToDoItem.vue";
```
3. Inside your component object, add the `components` property, and inside it add your `ToDoItem` component to register it.
Your `<script>` contents should now look like this:
```js
import ToDoItem from "./components/ToDoItem.vue";
export default {
name: "app",
components: {
ToDoItem,
},
};
```
This is the same way that the `HelloWorld` component was registered by the Vue CLI earlier.
To actually render the `ToDoItem` component in the app, you need to go up into your `<template>` element and call it as a `<to-do-item></to-do-item>` element. Note that the component file name and its representation in JavaScript is in PascalCase (e.g. `ToDoList`), and the equivalent custom element is in kebab-case (e.g. `<to-do-list>`).
It's necessary to use this casing style if you're writing Vue templates in the DOM directly
1. Underneath the `<h1>`, create an unordered list (`<ul>`) containing a single list item (`<li>`).
2. Inside the list item add `<to-do-item></to-do-item>`.
The `<template>` section of your `App.vue` file should now look something like this:
```markup
<div id="app">
<h1>To-Do List</h1>
<ul>
<li>
<to-do-item></to-do-item>
</li>
</ul>
</div>
```
If you check your rendered app again, you should now see your rendered `ToDoItem`, consisting of a checkbox and a label.
![The current rendering state of the app, which includes a title of To-Do List, and a single checkbox and label](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component/rendered-todoitem.png)
Making components dynamic with props
------------------------------------
Our `ToDoItem` component is still not very useful because we can only really include this once on a page (IDs need to be unique), and we have no way to set the label text. Nothing about this is dynamic.
What we need is some component state. This can be achieved by adding props to our component. You can think of props as being similar to inputs in a function. The value of a prop gives components an initial state that affects their display.
### Registering props
In Vue, there are two ways to register props:
* The first way is to just list props out as an array of strings. Each entry in the array corresponds to the name of a prop.
* The second way is to define props as an object, with each key corresponding to the prop name. Listing props as an object allows you to specify default values, mark props as required, perform basic object typing (specifically around JavaScript primitive types), and perform simple prop validation.
**Note:** Prop validation only happens in development mode, so you can't strictly rely on it in production. Additionally, prop validation functions are invoked before the component instance is created, so they do not have access to the component state (or other props).
For this component, we'll use the object registration method.
1. Go back to your `ToDoItem.vue` file.
2. Add a `props` property inside the export `default {}` object, which contains an empty object.
3. Inside this object, add two properties with the keys `label` and `done`.
4. The `label` key's value should be an object with 2 properties (or **props**, as they are called in the context of being available to the components).
1. The first is a `required` property, which will have a value of `true`. This will tell Vue that we expect every instance of this component to have a label field. Vue will warn us if a `ToDoItem` component does not have a label field.
2. The second property we'll add is a `type` property. Set the value for this property as the JavaScript `String` type (note the capital "S"). This tells Vue that we expect the value of this property to be a string.
5. Now on to the `done` prop.
1. First add a `default` field, with a value of `false`. This means that when no `done` prop is passed to a `ToDoItem` component, the `done` prop will have a value of false (bear in mind that this is not required β we only need `default` on non-required props).
2. Next add a `type` field with a value of `Boolean`. This tells Vue we expect the value prop to be a JavaScript boolean type.
Your component object should now look like this:
```js
export default {
props: {
label: { required: true, type: String },
done: { default: false, type: Boolean },
},
};
```
### Using registered props
With these props defined inside the component object, we can now use these variable values inside our template. Let's start by adding the `label` prop to the component template.
In your `<template>`, replace the contents of the `<label>` element with `{{label}}`.
`{{}}` is a special template syntax in Vue, which lets us print the result of JavaScript expressions defined in our class, inside our template, including values and methods. It's important to know that content inside `{{}}` is displayed as text and not HTML. In this case, we're printing the value of the `label` prop.
Your component's template section should now look like this:
```markup
<template>
<div>
<input type="checkbox" id="todo-item" />
<label for="todo-item">{{ label }}</label>
</div>
</template>
```
Go back to your browser and you'll see the todo item rendered as before, but without a label (oh no!). Go to your browser's DevTools and you'll see a warning along these lines in the console:
```
[Vue warn]: Missing required prop: "label"
found in
---> <ToDoItem> at src/components/ToDoItem.vue
<App> at src/App.vue
<Root>
```
This is because we marked the `label` as a required prop, but we never gave the component that prop β we've defined where inside the template we want it used, but we haven't passed it into the component when calling it. Let's fix that.
Inside your `App.vue` file, add a `label` prop to the `<to-do-item></to-do-item>` component, just like a regular HTML attribute:
```markup
<to-do-item label="My ToDo Item"></to-do-item>
```
Now you'll see the label in your app, and the warning won't be spat out in the console again.
So that's props in a nutshell. Next we'll move on to how Vue persists data state.
Vue's data object
-----------------
If you change the value of the `label` prop passed into the `<to-do-item></to-do-item>` call in your `App` component, you should see it update. This is great. We have a checkbox, with an updatable label. However, we're currently not doing anything with the "done" prop β we can check the checkboxes in the UI, but nowhere in the app are we recording whether a todo item is actually done.
To achieve this, we want to bind the component's `done` prop to the `checked` attribute on the `<input>` element, so that it can serve as a record of whether the checkbox is checked or not. However, it's important that props serve as one-way data binding β a component should never alter the value of its own props. There are a lot of reasons for this. In part, components editing props can make debugging a challenge. If a value is passed to multiple children, it could be hard to track where the changes to that value were coming from. In addition, changing props can cause components to re-render. So mutating props in a component would trigger the component to rerender, which may in-turn trigger the mutation again.
To work around this, we can manage the `done` state using Vue's `data` property. The `data` property is where you can manage local state in a component, it lives inside the component object alongside the `props` property and has the following structure:
```js
data() {
return {
key: value
}
}
```
You'll note that the `data` property is a function. This is to keep the data values unique for each instance of a component at runtime β the function is invoked separately for each component instance. If you declared data as just an object, all instances of that component would share the same values. This is a side-effect of the way Vue registers components and something you do not want.
You use `this` to access a component's props and other properties from inside data, as you may expect. We'll see an example of this shortly.
**Note:** Because of the way that `this` works in arrow functions (binding to the parent's context), you wouldn't be able to access any of the necessary attributes from inside `data` if you used an arrow function. So don't use an arrow function for the `data` property.
So let's add a `data` property to our `ToDoItem` component. This will return an object containing a single property that we'll call `isDone`, whose value is `this.done`.
Update the component object like so:
```js
export default {
props: {
label: { required: true, type: String },
done: { default: false, type: Boolean },
},
data() {
return {
isDone: this.done,
};
},
};
```
Vue does a little magic here β it binds all of your props directly to the component instance, so we don't have to call `this.props.done`. It also binds other attributes (`data`, which you've already seen, and others like `methods`, `computed`, etc.) directly to the instance. This is, in part, to make them available to your template. The down-side to this is that you need to keep the keys unique across these attributes. This is why we called our `data` attribute `isDone` instead of `done`.
So now we need to attach the `isDone` property to our component. In a similar fashion to how Vue uses `{{}}` expressions to display JavaScript expressions inside templates, Vue has a special syntax to bind JavaScript expressions to HTML elements and components: **`v-bind`**. The `v-bind` expression looks like this:
```
v-bind:attribute="expression"
```
In other words, you prefix whatever attribute/prop you want to bind to with `v-bind:`. In most cases, you can use a shorthand for the `v-bind` property, which is to just prefix the attribute/prop with a colon. So `:attribute="expression"` works the same as `v-bind:attribute="expression"`.
So in the case of the checkbox in our `ToDoItem` component, we can use `v-bind` to map the `isDone` property to the `checked` attribute on the `<input>` element. Both of the following are equivalent:
```markup
<input type="checkbox" id="todo-item" v-bind:checked="isDone" />
<input type="checkbox" id="todo-item" :checked="isDone" />
```
You're free to use whichever pattern you would like. It's best to keep it consistent though. Because the shorthand syntax is more commonly used, this tutorial will stick to that pattern.
So let's do this. Update your `<input>` element now to include `:checked="isDone"`.
Test out your component by passing `:done="true"` to the `ToDoItem` call in `App.vue`. Note that you need to use the `v-bind` syntax, because otherwise `true` is passed as a string. The displayed checkbox should be checked.
```markup
<template>
<div id="app">
<h1>My To-Do List</h1>
<ul>
<li>
<to-do-item label="My ToDo Item" :done="true"></to-do-item>
</li>
</ul>
</div>
</template>
```
Try changing `true` to `false` and back again, reloading your app in between to see how the state changes.
Giving Todos a unique id
------------------------
Great! We now have a working checkbox where we can set the state programmatically. However, we can currently only add one `ToDoList` component to the page because the `id` is hardcoded. This would result in errors with assistive technology since the `id` is needed to correctly map labels to their checkboxes. To fix this, we can programmatically set the `id` in the component data.
We can use the lodash package's `uniqueid()` method to help keep the index unique. This package exports a function that takes in a string and appends a unique integer to the end of the prefix. This will be sufficient for keeping component `id`s unique.
Let's add the package to our project with npm; stop your server and enter the following command into your terminal:
```bash
npm install --save lodash.uniqueid
```
**Note:** If you prefer yarn, you could instead use `yarn add lodash.uniqueid`.
We can now import this package into our `ToDoItem` component. Add the following line at the top of `ToDoItem.vue`'s `<script>` element:
```js
import uniqueId from "lodash.uniqueid";
```
Next, add an `id` field to our data property, so the component object ends up looking like so (`uniqueId()` returns the specified prefix β `todo-` β with a unique string appended to it):
```js
import uniqueId from "lodash.uniqueid";
export default {
props: {
label: { required: true, type: String },
done: { default: false, type: Boolean },
},
data() {
return {
isDone: this.done,
id: uniqueId("todo-"),
};
},
};
```
Next, bind the `id` to both our checkbox's `id` attribute and the label's `for` attribute, updating the existing `id` and `for` attributes as shown:
```markup
<template>
<div>
<input type="checkbox" :id="id" :checked="isDone" />
<label :for="id">{{ label }}</label>
</div>
</template>
```
Summary
-------
And that will do for this article. At this point we have a nicely-working `ToDoItem` component that can be passed a label to display, will store its checked state, and will be rendered with a unique `id` each time it is called. You can check if the unique `id`s are working by temporarily adding more `<to-do-item></to-do-item>` calls into `App.vue`, and then checking their rendered output with your browser's DevTools.
Now we're ready to add multiple `ToDoItem` components to our app. In our next article we'll look at adding a set of todo item data to our `App.vue` component, which we'll then loop through and display inside `ToDoItem` components using the `v-for` directive.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Componentizing our React app - Learn web development | Componentizing our React app
============================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
At this point, our app is a monolith. Before we can make it do things, we need to break it apart into manageable, descriptive components. React doesn't have any hard rules for what is and isn't a component β that's up to you! In this article we will show you a sensible way to break our app up into components.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
|
| Objective: | To show a sensible way of breaking our todo list app into components. |
Defining our first component
----------------------------
Defining a component can seem tricky until you have some practice, but the gist is:
* If it represents an obvious "chunk" of your app, it's probably a component
* If it gets reused often, it's probably a component.
That second bullet is especially valuable: making a component out of common UI elements allows you to change your code in one place and see those changes everywhere that component is used. You don't have to break everything out into components right away, either. Let's take the second bullet point as inspiration and make a component out of the most reused, most important piece of the UI: a todo list item.
Make a `<Todo />`
-----------------
Before we can make a component, we should create a new file for it. In fact, we should make a directory just for our components. Make sure you're in the root of your app before you run these commands!
```bash
# create a `components` directory
mkdir src/components
# within `components`, create a file called `Todo.jsx`
touch src/components/Todo.jsx
```
Don't forget to restart your development server if you stopped it to run the previous commands!
Let's add a `Todo()` function in `Todo.jsx`. Here, we define a function and export it:
```jsx
function Todo() {}
export default Todo;
```
This is OK so far, but our component should return something useful! Go back to `src/App.jsx`, copy the first `<li>` from inside the unordered list, and paste it into `Todo.jsx` so that it reads like this:
```jsx
function Todo() {
return (
<li className="todo stack-small">
<div className="c-cb">
<input id="todo-0" type="checkbox" defaultChecked />
<label className="todo-label" htmlFor="todo-0">
Eat
</label>
</div>
<div className="btn-group">
<button type="button" className="btn">
Edit <span className="visually-hidden">Eat</span>
</button>
<button type="button" className="btn btn\_\_danger">
Delete <span className="visually-hidden">Eat</span>
</button>
</div>
</li>
);
}
export default Todo;
```
Now we have something we can use. In `App.jsx`, add the following line at the top of the file to import `Todo`:
```jsx
import Todo from "./components/Todo";
```
With this component imported, you can replace all of the `<li>` elements in `App.jsx` with `<Todo />` component calls. Your `<ul>` should read like this:
```jsx
<ul
role="list"
className="todo-list stack-large stack-exception"
aria-labelledby="list-heading">
<Todo />
<Todo />
<Todo />
</ul>
```
When you return to your app, you'll notice something unfortunate: your list now repeats the first task three times!
![Our todo list app, with todo components repeating because the label is hardcoded into the component](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components/todo-list-repeating-todos.png)
We don't only want to eat; we have other things to β well β to do. Next we'll look at how we can make different component calls render unique content.
Make a unique `<Todo />`
------------------------
Components are powerful because they let us re-use pieces of our UI, and refer to one place for the source of that UI. The problem is, we don't typically want to reuse all of each component; we want to reuse most parts, and change small pieces. This is where props come in.
### What's in a `name`?
In order to track the names of tasks we want to complete, we should ensure that each `<Todo />` component renders a unique name.
In `App.jsx`, give each `<Todo />` a name prop. Let's use the names of our tasks that we had before:
```jsx
<Todo name="Eat" />
<Todo name="Sleep" />
<Todo name="Repeat" />
```
When your browser refreshes, you will see⦠the exact same thing as before. We gave our `<Todo />` some props, but we aren't using them yet. Let's go back to `Todo.jsx` and remedy that.
First modify your `Todo()` function definition so that it takes `props` as a parameter. You can `console.log()` your props if you'd like to check that they are being received by the component correctly.
Once you're confident that your component is getting its props, you can replace every occurrence of `Eat` with your `name` prop by reading `props.name`. Remember: `props.name` is a JSX expression, so you'll need to wrap it in curly braces.
Putting all that together, your `Todo()` function should read like this:
```jsx
function Todo(props) {
return (
<li className="todo stack-small">
<div className="c-cb">
<input id="todo-0" type="checkbox" defaultChecked={true} />
<label className="todo-label" htmlFor="todo-0">
{props.name}
</label>
</div>
<div className="btn-group">
<button type="button" className="btn">
Edit <span className="visually-hidden">{props.name}</span>
</button>
<button type="button" className="btn btn\_\_danger">
Delete <span className="visually-hidden">{props.name}</span>
</button>
</div>
</li>
);
}
export default Todo;
```
*Now* your browser should show three unique tasks. Another problem remains though: they're all still checked by default.
![Our todo list, with different todo labels now they are passed into the components as props](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components/todo-list-unique-todos.png)
### Is it `completed`?
In our original static list, only `Eat` was checked. Once again, we want to reuse *most* of the UI that makes up a `<Todo />` component, but change one thing. That's a good job for another prop! Give your first `<Todo />` call a boolean prop of `completed`, and leave the other two as they are.
```jsx
<Todo name="Eat" completed />
<Todo name="Sleep" />
<Todo name="Repeat" />
```
As before, we must go back to `Todo.jsx` to actually use these props. Change the `defaultChecked` attribute on the `<input />` so that its value is equal to the `completed` prop. Once you're done, the Todo component's `<input />` element will read like this:
```jsx
<input id="todo-0" type="checkbox" defaultChecked={props.completed} />
```
And your browser should update to show only `Eat` being checked:
![Our todo list app, now with differing checked states - some checkboxes are checked, others not](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components/todo-list-differing-checked-states.png)
If you change each `<Todo />` component's `completed` prop, your browser will check or uncheck the equivalent rendered checkboxes accordingly.
### Gimme some `id`, please
We have still *another* problem: our `<Todo />` component gives every task an `id` attribute of `todo-0`. This is bad for a couple of reasons:
* `id` attributes must be unique (they are used as unique identifiers for document fragments, by CSS, JavaScript, etc.).
* When `id`s are not unique, the functionality of label elements can break.
The second problem is affecting our app right now. If you click on the word "Sleep" next to the second checkbox, you'll notice the "Eat" checkbox toggles instead of the "Sleep" checkbox. This is because every checkbox's `<label>` element has an `htmlFor` attribute of `todo-0`. The `<label>`s only acknowledge the first element with a given `id` attribute, which causes the problem you see when clicking on the other labels.
We had unique `id` attributes before we created the `<Todo />` component. Let's bring them back, following the format of `todo-i`, where `i` gets larger by one every time. Update the `Todo` component instances inside `App.jsx` to add in `id` props, as follows:
```jsx
<Todo name="Eat" id="todo-0" completed />
<Todo name="Sleep" id="todo-1" />
<Todo name="Repeat" id="todo-2" />
```
**Note:** The `completed` prop is last here because it is a boolean with no assignment. This is purely a stylistic convention. The order of props does not matter because props are JavaScript objects, and JavaScript objects are unordered.
Now go back to `Todo.jsx` and make use of the `id` prop. It needs to replace the `<input />` element's `id` attribute value, as well as its `<label>`'s `htmlFor` attribute value:
```jsx
<div className="c-cb">
<input id={props.id} type="checkbox" defaultChecked={props.completed} />
<label className="todo-label" htmlFor={props.id}>
{props.name}
</label>
</div>
```
With these fixes in place, clicking on the labels next to each checkbox will do what we expect β check and uncheck the checkboxes next to those labels.
So far, so good?
----------------
We're making good use of React so far, but we could do better! Our code is repetitive. The three lines that render our `<Todo />` component are almost identical, with only one difference: the value of each prop.
We can clean up our code with one of JavaScript's core abilities: iteration. To use iteration, we should first re-think our tasks.
Tasks as data
-------------
Each of our tasks currently contains three pieces of information: its name, whether it has been checked, and its unique ID. This data translates nicely to an object. Since we have more than one task, an array of objects would work well in representing this data.
In `src/main.jsx`, declare a new `const` beneath the final import, but above `ReactDOM.createRoot()`:
```jsx
const DATA = [
{ id: "todo-0", name: "Eat", completed: true },
{ id: "todo-1", name: "Sleep", completed: false },
{ id: "todo-2", name: "Repeat", completed: false },
];
```
**Note:** If your text editor has an ESLint plugin, you may see a warning on this `DATA` const. This warning comes from the ESLint configuration supplied by the Vite template we used, and it doesn't apply to this code. You can safely suppress the warning by adding `// eslint-disable-next-line` to the line above the `DATA` const.
Next, we'll pass `DATA` to `<App />` as a prop, called `tasks`. Update your `<App />` component call inside `src/main.jsx` to read like this:
```jsx
<App tasks={DATA} />
```
The `DATA` array is now available inside the App component as `props.tasks`. You can `console.log()` it to check, if you'd like.
**Note:** `ALL_CAPS` constant names have no special meaning in JavaScript; they're a convention that tells other developers "this data will never change after being defined here".
Rendering with iteration
------------------------
To render our array of objects, we have to turn each object into a `<Todo />` component. JavaScript gives us an array method for transforming items into something else: `Array.prototype.map()`.
Inside `App.jsx`, create a new `const` above the `App()` function's `return` statement called `taskList`. Let's start by transforming each task in the `props.tasks` array into its `name`. The `?.` operator lets us perform optional chaining to check if `props.tasks` is `undefined` or `null` before attempting to create a new array of task names:
```jsx
const taskList = props.tasks?.map((task) => task.name);
```
Let's try replacing all the children of the `<ul>` with `taskList`:
```jsx
<ul
role="list"
className="todo-list stack-large stack-exception"
aria-labelledby="list-heading">
{taskList}
</ul>
```
This gets us some of the way towards showing all the components again, but we've got more work to do: the browser currently renders each task's name as plain text. We're missing our HTML structure β the `<li>` and its checkboxes and buttons!
![Our todo list app with the todo item labels just shown bunched up on one line](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components/todo-list-unstructured-names.png)
To fix this, we need to return a `<Todo />` component from our `map()` function β remember that JSX is JavaScript, so we can use it alongside any other, more familiar JavaScript syntax. Let's try the following instead of what we have already:
```jsx
const taskList = props.tasks?.map((task) => <Todo />);
```
Look again at your app; now our tasks look more like they used to, but they're missing the names of the tasks themselves. Remember that each task we map over contains the `id`, `name`, and `completed` properties we want to pass into our `<Todo />` component. If we put that knowledge together, we get code like this:
```jsx
const taskList = props.tasks?.map((task) => (
<Todo id={task.id} name={task.name} completed={task.completed} />
));
```
Now the app looks like it did before, and our code is less repetitive.
Unique keys
-----------
Now that React is rendering our tasks out of an array, it has to keep track of which one is which in order to render them properly. React tries to do its own guesswork to keep track of things, but we can help it out by passing a `key` prop to our `<Todo />` components. `key` is a special prop that's managed by React β you cannot use the word `key` for any other purpose.
Because keys should be unique, we're going to re-use the `id` of each task object as its key. Update your `taskList` constant like so:
```jsx
const taskList = props.tasks?.map((task) => (
<Todo
id={task.id}
name={task.name}
completed={task.completed}
key={task.id}
/>
));
```
**You should always pass a unique key to anything you render with iteration.** Nothing obvious will change in your browser, but if you do not use unique keys, React will log warnings to your console and your app may behave strangely!
Componentizing the rest of the app
----------------------------------
Now that we've got our most important component sorted out, we can turn the rest of our app into components. Remembering that components are either obvious pieces of UI, reused pieces of UI, or both, we can make two more components:
* `<Form />`
* `<FilterButton />`
Since we know we need both, we can batch some of the file creation work together in one terminal command. Run this command in your terminal, taking care that you're in the root directory of your app:
```bash
touch src/components/{Form,FilterButton}.jsx
```
### The `<Form />`
Open `components/Form.jsx` and do the following:
* Declare a `Form()` function and export it at the end of the file.
* Copy the `<form>` tags and everything between them from inside `App.jsx`, and paste them inside `Form()`'s `return` statement.
Your `Form.jsx` file should read like this:
```jsx
function Form() {
return (
<form>
<h2 className="label-wrapper">
<label htmlFor="new-todo-input" className="label\_\_lg">
What needs to be done?
</label>
</h2>
<input
type="text"
id="new-todo-input"
className="input input\_\_lg"
name="text"
autoComplete="off"
/>
<button type="submit" className="btn btn\_\_primary btn\_\_lg">
Add
</button>
</form>
);
}
export default Form;
```
### The `<FilterButton />`
Do the same things you did to create `Form.jsx` inside `FilterButton.jsx`, but call the component `FilterButton()` and copy the HTML for the first button inside `<div className="filters btn-group stack-exception">` from `App.jsx` into the `return` statement.
The file should read like this:
```jsx
function FilterButton() {
return (
<button type="button" className="btn toggle-btn" aria-pressed="true">
<span className="visually-hidden">Show </span>
<span>all </span>
<span className="visually-hidden"> tasks</span>
</button>
);
}
export default FilterButton;
```
**Note:** You might notice that we are making the same mistake here as we first made for the `<Todo />` component, in that each button will be the same. That's fine! We're going to fix up this component later on, in Back to the filter buttons.
Importing all our components
----------------------------
Let's make use of our new components. Add some more `import` statements to the top of `App.jsx` and reference the components we've just made. Then, update the `return` statement of `App()` so that it renders our components.
When you're done, `App.jsx` will read like this:
```jsx
import Form from "./components/Form";
import FilterButton from "./components/FilterButton";
import Todo from "./components/Todo";
function App(props) {
const taskList = props.tasks?.map((task) => (
<Todo
id={task.id}
name={task.name}
completed={task.completed}
key={task.id}
/>
));
return (
<div className="todoapp stack-large">
<h1>TodoMatic</h1>
<Form />
<div className="filters btn-group stack-exception">
<FilterButton />
<FilterButton />
<FilterButton />
</div>
<h2 id="list-heading">3 tasks remaining</h2>
<ul
role="list"
className="todo-list stack-large stack-exception"
aria-labelledby="list-heading">
{taskList}
</ul>
</div>
);
}
export default App;
```
With this in place, your React app should render basically the same as it did before, but using your shiny new components.
Summary
-------
And that's it for this article β we've gone into depth on how to break up your app nicely into components and render them efficiently. Next we'll look at handling events in React, and start adding some interactivity.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Vue resources - Learn web development | Vue resources
=============
* Previous
* Overview: Client-side JavaScript frameworks
* Next
Now we'll round off our study of Vue by giving you a list of resources that you can use to go further in your learning, plus some other useful tips.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages,
knowledge of the
terminal/command line.
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with node + npm installed.
|
| Objective: |
To learn where to go to find further information on Vue, to continue
your learning.
|
Further resources
-----------------
Here's where you should go to learn more about Vue:
* Vue Docs β The main Vue site. Contains comprehensive documentation, including examples, cookbooks, and reference material. This is the best place to start learning Vue in depth.
* Vue GitHub Repo β The Vue code itself. This is where you can report issues and/or contribute directly to the Vue codebase. Studying the Vue source code can help you better understand how the framework works, and write better code.
* Vue Forum β The official forum for getting help with Vue.
* Vue CLI Docs β Documentation for the Vue CLI. This contains information on customizing and extending the output you are generating via the CLI.
* NuxtJS β NuxtJS is a Server-Side Vue Framework, with some architectural opinions that can be useful to creating maintainable applications, even if you don't use any of the Server Side Rendering features it provides. This site provides detailed documentation on using NuxtJS.
* Vue Mastery β A paid education platform that specializes in Vue, including some free lessons.
* Vue School β Another paid education platform specializing in Vue.
Building and publishing your Vue app
------------------------------------
The Vue CLI also provides us with tools for preparing our app for publishing to the web. You can do this like so:
* If your local server is still running, end it by pressing `Ctrl` + `C` in the terminal.
* Next, run the `npm run build` (or `yarn build`) in the console.
This will create a new `dist` directory containing all of your production ready files. To publish your site to the web, copy the contents of this folder to your hosting environment.
**Note:** The Vue CLI docs also include a specific guide on how to publish your app to many of the common hosting platforms.
Vue 2
-----
Vue 2 support will end on December 31st, 2023 and the default Vue version for all CLI tools will be version 3 and above.
The Composition API works as an alternative to the property-based API where a `setup()` function is used on the component. Only what you return from this function is available in your `<template>`s. You are required to be explicit about "reactive" properties when using this API. Vue handles this for you using the Options API. This makes the new API typically considered a more advanced use case.
If you're upgrading from Vue 2, it's recommended you take a look at the Vue 3 migration guide.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Framework main features - Learn web development | Framework main features
=======================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
Each major JavaScript framework has a different approach to updating the DOM, handling browser events, and providing an enjoyable developer experience. This article will explore the main features of "the big 4" frameworks, looking at how frameworks tend to work from a high level, and the differences between them.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages.
|
| Objective: | To understand the main code features of frameworks. |
Domain-specific languages
-------------------------
All of the frameworks discussed in this module are powered by JavaScript, and all allow you to use domain-specific languages (DSLs) in order to build your applications. In particular, React has popularized the use of **JSX** for writing its components, while Ember utilizes **Handlebars**. Unlike HTML, these languages know how to read data variables, and this data can be used to streamline the process of writing your UI.
Angular apps often make heavy use of **TypeScript**. TypeScript is not concerned with the writing of user interfaces, but it is a domain-specific language, and has significant differences to vanilla JavaScript.
DSLs can't be read by the browser directly; they must be transformed into JavaScript or HTML first. Transformation is an extra step in the development process, but framework tooling generally includes the required tools to handle this step, or can be adjusted to include this step. While it is possible to build framework apps without using these domain-specific languages, embracing them will streamline your development process and make it easier to find help from the communities around those frameworks.
### JSX
JSX, which stands for JavaScript and XML, is an extension of JavaScript that brings HTML-like syntax to a JavaScript environment. It was invented by the React team for use in React applications, but can be used to develop other applications β like Vue apps, for instance.
The following shows a simple JSX example:
```jsx
const subject = "World";
const header = (
<header>
<h1>Hello, {subject}!</h1>
</header>
);
```
This expression represents an HTML `<header>` element with an `<h1>` element inside. The curly braces around `{subject}` tell the application to read the value of the `subject` constant and insert it into our `<h1>`.
When used with React, the JSX from the previous snippet would be compiled into this:
```js
const subject = "World";
const header = React.createElement(
"header",
null,
React.createElement("h1", null, "Hello, ", subject, "!"),
);
```
When ultimately rendered by the browser, the above snippet will produce HTML that looks like this:
```html
<header>
<h1>Hello, World!</h1>
</header>
```
### Handlebars
The Handlebars templating language is not specific to Ember applications, but it is heavily utilized in Ember apps. Handlebars code resembles HTML, but it has the option of pulling data in from elsewhere. This data can be used to influence the HTML that an application ultimately builds.
Like JSX, Handlebars uses curly braces to inject the value of a variable. Handlebars uses a double-pair of curly braces, instead of a single pair.
Given this Handlebars template:
```html
<header>
<h1>Hello, {{subject}}!</h1>
</header>
```
And this data:
```js
{
subject: "World";
}
```
Handlebars will build HTML like this:
```html
<header>
<h1>Hello, World!</h1>
</header>
```
### TypeScript
TypeScript is a *superset* of JavaScript, meaning it extends JavaScript β all JavaScript code is valid TypeScript, but not the other way around. TypeScript is useful for the strictness it allows developers to enforce on their code. For instance, consider a function `add()`, which takes integers `a` and `b` and returns their sum.
In JavaScript, that function could be written like this:
```js
function add(a, b) {
return a + b;
}
```
This code might be trivial for someone accustomed to JavaScript, but it could still be clearer. JavaScript lets us use the `+` operator to concatenate strings together, so this function would technically still work if `a` and `b` were strings β it just might not give you the result you'd expect. What if we wanted to only allow numbers to be passed into this function? TypeScript makes that possible:
```ts
function add(a: number, b: number) {
return a + b;
}
```
The `: number` written after each parameter here tells TypeScript that both `a` and `b` must be numbers. If we were to use this function and pass `'2'` into it as an argument, TypeScript would raise an error during compilation, and we would be forced to fix our mistake. We could write our own JavaScript that raises these errors for us, but it would make our source code significantly more verbose. It probably makes more sense to let TypeScript handle such checks for us.
Writing components
------------------
As mentioned in the previous chapter, most frameworks have some kind of component model. React components can be written with JSX, Ember components with Handlebars, and Angular and Vue components with a templating syntax that lightly extends HTML.
Regardless of their opinions on how components should be written, each framework's components offer a way to describe the external properties they may need, the internal state that the component should manage, and the events a user can trigger on the component's markup.
The code snippets in the rest of this section will use React as an example, and are written with JSX.
### Properties
Properties, or **props**, are external data that a component needs in order to render. Suppose you're building a website for an online magazine, and you need to be sure that each contributing writer gets credit for their work. You might create an `AuthorCredit` component to go with each article. This component needs to display a portrait of the author and a short byline about them. In order to know what image to render, and what byline to print, `AuthorCredit` needs to accept some props.
A React representation of this `AuthorCredit` component might look something like this:
```jsx
function AuthorCredit(props) {
return (
<figure>
<img src={props.src} alt={props.alt} />
<figcaption>{props.byline}</figcaption>
</figure>
);
}
```
`{props.src}`, `{props.alt}`, and `{props.byline}` represent where our props will be inserted into the component. To render this component, we would write code like this in the place where we want it rendered (which will probably be inside another component):
```jsx
<AuthorCredit
src="./assets/zelda.png"
alt="Portrait of Zelda Schiff"
byline="Zelda Schiff is editor-in-chief of the Library Times."
/>
```
This will ultimately render the following `<figure>` element in the browser, with its structure as defined in the `AuthorCredit` component, and its content as defined in the props included on the `AuthorCredit` component call:
```html
<figure>
<img src="assets/zelda.png" alt="Portrait of Zelda Schiff" />
<figcaption>Zelda Schiff is editor-in-chief of the Library Times.</figcaption>
</figure>
```
### State
We talked about the concept of **state** in the previous chapter β a robust state-handling mechanism is key to an effective framework, and each component may have data that needs its state controlled. This state will persist in some way as long as the component is in use. Like props, state can be used to affect how a component is rendered.
As an example, consider a button that counts how many times it has been clicked. This component should be responsible for tracking its own *count* state, and could be written like this:
```jsx
function CounterButton() {
const [count] = useState(0);
return <button>Clicked {count} times</button>;
}
```
`useState()` is a **React hook** which, given an initial data value, will keep track of that value as it is updated. The code will be initially rendered like so in the browser:
```html
<button>Clicked 0 times</button>
```
The `useState()` call keeps track of the `count` value in a robust way across the app, without you needing to write code to do that yourself.
### Events
In order to be interactive, components need ways to respond to browser events, so our applications can respond to our users. Frameworks each provide their own syntax for listening to browser events, which reference the names of the equivalent native browser events.
In React, listening for the `click` event requires a special property, `onClick`. Let's update our `CounterButton` code from above to allow it to count clicks:
```jsx
function CounterButton() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>Clicked {count} times</button>
);
}
```
In this version we are using additional `useState()` functionality to create a special `setCount()` function, which we can invoke to update the value of `count`. We call this function inside the `onClick` event handler to set `count` to whatever its current value is, plus one.
Styling components
------------------
Each framework offers a way to define styles for your components β or for the application as a whole. Although each framework's approach to defining the styles of a component is slightly different, all of them give you multiple ways to do so. With the addition of some helper modules, you can style your framework apps in Sass or Less, or transpile your CSS stylesheets with PostCSS.
Handling dependencies
---------------------
All major frameworks provide mechanisms for handling dependencies β using components inside other components, sometimes with multiple hierarchy levels. As with other features, the exact mechanism will differ between frameworks, but the end result is the same. Components tend to import components into other components using the standard JavaScript module syntax, or at least something similar.
### Components in components
One key benefit of component-based UI architecture is that components can be composed together. Just like you can write HTML tags inside each other to build a website, you can use components inside other components to build a web application. Each framework allows you to write components that utilize (and thus depend on) other components.
For example, our `AuthorCredit` React component might be utilized inside an `Article` component. That means that `Article` would need to import `AuthorCredit`.
```js
import AuthorCredit from "./components/AuthorCredit";
```
Once that's done, `AuthorCredit` could be used inside the `Article` component like this:
```jsx
<Article>
<AuthorCredit />
</Article>
```
### Dependency injection
Real-world applications can often involve component structures with multiple levels of nesting. An `AuthorCredit` component nested many levels deep might, for some reason, need data from the very root level of our application.
Let's say that the magazine site we're building is structured like this:
```jsx
<App>
<Home>
<Article>
<AuthorCredit {/\* props \*/} />
</Article>
</Home>
</App>
```
Our `App` component has data that our `AuthorCredit` component needs. We could rewrite `Home` and `Article` so that they know to pass props down, but this could get tedious if there are many, many levels between the origin and destination of our data. It's also excessive: `Home` and `Article` don't actually make use of the author's portrait or byline, but if we want to get that information into the `AuthorCredit`, we will need to change `Home` and `Article` to accommodate it.
The problem of passing data through many layers of components is called prop drilling, and it's not ideal for large applications.
To circumvent prop drilling, frameworks provide functionality known as dependency injection, which is a way to get certain data directly to the components that need it, without passing it through intervening levels. Each framework implements dependency injection under a different name, and in a different way, but the effect is ultimately the same.
Angular calls this process dependency injection; Vue has `provide()` and `inject()` component methods; React has a Context API; Ember shares state through services.
### Lifecycle
In the context of a framework, a component's **lifecycle** is a collection of phases a component goes through from the time it is appended to the DOM and then rendered by the browser (often called *mounting*) to the time that it is removed from the DOM (often called *unmounting*). Each framework names these lifecycle phases differently, and not all give developers access to the same phases. All of the frameworks follow the same general model: they allow developers to perform certain actions when the component *mounts*, when it *renders*, when it *unmounts*, and at many phases in between these.
The *render* phase is the most crucial to understand, because it is repeated the most times as your user interacts with your application. It's run every time the browser needs to render something new, whether that new information is an addition to what's in the browser, a deletion, or an edit of what's there.
This diagram of a React component's lifecycle offers a general overview of the concept.
Rendering elements
------------------
Just as with lifecycles, frameworks take different-but-similar approaches to how they render your applications. All of them track the current rendered version of your browser's DOM, and each makes slightly different decisions about how the DOM should change as components in your application re-render. Because frameworks make these decisions for you, you typically don't interact with the DOM yourself. This abstraction away from the DOM is more complex and more memory-intensive than updating the DOM yourself, but without it, frameworks could not allow you to program in the declarative way they're known for.
The **Virtual DOM** is an approach whereby information about your browser's DOM is stored in JavaScript memory. Your application updates this copy of the DOM, then compares it to the "real" DOM β the DOM that is actually rendered for your users β in order to decide what to render. The application builds a "diff" to compare the differences between the updated virtual DOM and the currently rendered DOM, and uses that diff to apply updates to the real DOM. Both React and Vue utilize a virtual DOM model, but they do not apply the exact same logic when diffing or rendering.
You can read more about the Virtual DOM in the React docs.
The **Incremental DOM** is similar to the virtual DOM in that it builds a DOM diff to decide what to render, but different in that it doesn't create a complete copy of the DOM in JavaScript memory. It ignores the parts of the DOM that do not need to be changed. Angular is the only framework discussed so far in this module that uses an incremental DOM.
You can read more about the Incremental DOM on the Auth0 blog.
The **Glimmer VM** is unique to Ember. It is not a virtual DOM nor an incremental DOM; it is a separate process through which Ember's templates are transpiled into a kind of "byte code" that is easier and faster to read than JavaScript.
Routing
-------
As mentioned in the previous chapter, routing is an important part of the web experience. To avoid a broken experience in sufficiently complex apps with lots of views, each of the frameworks covered in this module provides a library (or more than one library) that helps developers implement client-side routing in their applications.
Testing
-------
All applications benefit from test coverage that ensures your software continues to behave in the way that you'd expect, and web applications are no different. Each framework's ecosystem provides tooling that facilitates the writing of tests. Testing tools are not built into the frameworks themselves, but the command-line interface tools used to generate framework apps give you access to the appropriate testing tools.
Each framework has extensive tools in its ecosystem, with capabilities for unit and integration testing alike.
Testing Library is a suite of testing utilities that has tools for many JavaScript environments, including React, Vue, and Angular. The Ember docs cover the testing of Ember apps.
Here's a quick test for our `CounterButton` written with the help of React Testing Library β it tests a number of things, such as the button's existence, and whether the button is displaying the correct text after being clicked 0, 1, and 2 times:
```jsx
import { fireEvent, render, screen } from "@testing-library/react";
import CounterButton from "./CounterButton";
it("Renders a semantic button with an initial state of 0", () => {
render(<CounterButton />);
const btn = screen.getByRole("button");
expect(btn).toBeInTheDocument();
expect(btn).toHaveTextContent("Clicked 0 times");
});
it("Increments the count when clicked", () => {
render(<CounterButton />);
const btn = screen.getByRole("button");
fireEvent.click(btn);
expect(btn).toHaveTextContent("Clicked 1 times");
fireEvent.click(btn);
expect(btn).toHaveTextContent("Clicked 2 times");
});
```
Summary
-------
At this point you should have more of an idea about the actual languages, features, and tools you'll be using as you create applications with frameworks. I'm sure you're enthusiastic to get going and actually do some coding, and that's what you are going to do next! At this point you can choose which framework you'd like to start learning first:
* React
* Ember
* Vue
* Svelte
* Angular
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development | Advanced Svelte: Reactivity, lifecycle, accessibility
=====================================================
* Previous
* Overview: Client-side JavaScript frameworks
* Next
In the last article we added more features to our to-do list and started to organize our app into components. In this article we will add the app's final features and further componentize our app. We will learn how to deal with reactivity issues related to updating objects and arrays. To avoid common pitfalls, we'll have to dig a little deeper into Svelte's reactivity system. We'll also look at solving some accessibility focus issues, and more besides.
| | |
| --- | --- |
| Prerequisites: |
At minimum, it is recommended that you are familiar with the core
HTML,
CSS, and
JavaScript languages, and
have knowledge of the
terminal/command line.
You'll need a terminal with node and npm installed to compile and build
your app.
|
| Objective: |
Learn some advanced Svelte techniques involving solving reactivity
issues, keyboard accessibility problems to do with component lifecycle,
and more.
|
We'll focus on some accessibility issues involving focus management. To do so, we'll utilize some techniques for accessing DOM nodes and executing methods like `focus()` and `select()`. We will also see how to declare and clean up event listeners on DOM elements.
We also need to learn a bit about component lifecycle to understand when these DOM nodes get mounted and unmounted from the DOM and how we can access them. We will also learn about the `action` directive, which will allow us to extend the functionality of HTML elements in a reusable and declarative way.
Finally, we will learn a bit more about components. So far, we've seen how components can share data using props, and communicate with their parents using events and two-way data binding. Now we will see how components can also expose methods and variables.
The following new components will be developed throughout the course of this article:
* `MoreActions`: Displays the *Check All* and *Remove Completed* buttons, and emits the corresponding events required to handle their functionality.
* `NewTodo`: Displays the `<input>` field and *Add* button for adding a new to-do.
* `TodosStatus`: Displays the "x out of y items completed" status heading.
Code along with us
------------------
### Git
Clone the GitHub repo (if you haven't already done it) with:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then to get to the current app state, run
```bash
cd mdn-svelte-tutorial/05-advanced-concepts
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/05-advanced-concepts
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To code along with us using the REPL, start at
https://svelte.dev/repl/76cc90c43a37452e8c7f70521f88b698?version=3.23.2
Working on the MoreActions component
------------------------------------
Now we'll tackle the *Check All* and *Remove Completed* buttons. Let's create a component that will be in charge of displaying the buttons and emitting the corresponding events.
1. Create a new file, `components/MoreActions.svelte`.
2. When the first button is clicked, we'll emit a `checkAll` event to signal that all the to-dos should be checked/unchecked. When the second button is clicked, we'll emit a `removeCompleted` event to signal that all of the completed to-dos should be removed. Put the following content into your `MoreActions.svelte` file:
```svelte
<script>
import { createEventDispatcher } from "svelte";
const dispatch = createEventDispatcher();
let completed = true;
const checkAll = () => {
dispatch("checkAll", completed);
completed = !completed;
};
const removeCompleted = () => dispatch("removeCompleted");
</script>
<div class="btn-group">
<button type="button" class="btn btn\_\_primary" on:click={checkAll}>{completed ? 'Check' : 'Uncheck'} all</button>
<button type="button" class="btn btn\_\_primary" on:click={removeCompleted}>Remove completed</button>
</div>
```
We've also included a `completed` variable to toggle between checking and unchecking all tasks.
3. Back over in `Todos.svelte`, we are going to import our `MoreActions` component and create two functions to handle the events emitted by the `MoreActions` component.
Add the following import statement below the existing ones:
```js
import MoreActions from "./MoreActions.svelte";
```
4. Then add the described functions at the end of the `<script>` section:
```js
const checkAllTodos = (completed) =>
todos.forEach((t) => (t.completed = completed));
const removeCompletedTodos = () =>
(todos = todos.filter((t) => !t.completed));
```
5. Now go to the bottom of the `Todos.svelte` markup section and replace the `<div class="btn-group">` element that we copied into `MoreActions.svelte` with a call to the `MoreActions` component, like so:
```svelte
<!-- MoreActions -->
<MoreActions
on:checkAll={(e) => checkAllTodos(e.detail)}
on:removeCompleted={removeCompletedTodos}
/>
```
6. OK, let's go back into the app and try it out. You'll find that the *Remove Completed* button works fine, but the *Check All*/*Uncheck All* button just silently fails.
To find out what is happening here, we'll have to dig a little deeper into Svelte reactivity.
Reactivity gotchas: updating objects and arrays
-----------------------------------------------
To see what's happening we can log the `todos` array from the `checkAllTodos()` function to the console.
1. Update your existing `checkAllTodos()` function to the following:
```js
const checkAllTodos = (completed) => {
todos.forEach((t) => (t.completed = completed));
console.log("todos", todos);
};
```
2. Go back to your browser, open your DevTools console, and click *Check All*/*Uncheck All* a few times.
You'll notice that the array is successfully updated every time you press the button (the `todo` objects' `completed` properties are toggled between `true` and `false`), but Svelte is not aware of that. This also means that in this case, a reactive statement like `$: console.log('todos', todos)` won't be very useful.
To find out why this is happening, we need to understand how reactivity works in Svelte when updating arrays and objects.
Many web frameworks use the virtual DOM technique to update the page. Basically, the virtual DOM is an in-memory copy of the contents of the web page. The framework updates this virtual representation, which is then synced with the "real" DOM. This is much faster than directly updating the DOM and allows the framework to apply many optimization techniques.
These frameworks, by default, basically re-run all our JavaScript on every change against this virtual DOM, and apply different methods to cache expensive calculations and optimize execution. They make little to no attempt to understand what our JavaScript code is doing.
Svelte doesn't use a virtual DOM representation. Instead, it parses and analyzes our code, creates a dependency tree, and then generates the required JavaScript to update only the parts of the DOM that need to be updated. This approach usually generates optimal JavaScript code with minimal overhead, but it also has its limitations.
Sometimes Svelte cannot detect changes to variables being watched. Remember that to tell Svelte that a variable has changed, you have to assign it a new value. A simple rule to keep in mind is that **The name of the updated variable must appear on the left-hand side of the assignment.**
For example, in the following piece of code:
```js
const foo = obj.foo;
foo.bar = "baz";
```
Svelte won't update references to `obj.foo.bar`, unless you follow it up with `obj = obj`. That's because Svelte can't track object references, so we have to explicitly tell it that `obj` has changed by issuing an assignment.
**Note:** If `foo` is a top-level variable, you can easily tell Svelte to update `obj` whenever `foo` is changed with the following reactive statement: `$: foo, obj = obj`. With this we are defining `foo` as a dependency, and whenever it changes Svelte will run `obj = obj`.
In our `checkAllTodos()` function, when we run:
```js
todos.forEach((t) => (t.completed = completed));
```
Svelte will not mark `todos` as changed because it does not know that when we update our `t` variable inside the `forEach()` method, we are also modifying the `todos` array. And that makes sense, because otherwise Svelte would be aware of the inner workings of the `forEach()` method; the same would therefore be true for any method attached to any object or array.
Nevertheless, there are different techniques that we can apply to solve this problem, and all of them involve assigning a new value to the variable being watched.
As we already saw, we could just tell Svelte to update the variable with a self-assignment, like this:
```js
const checkAllTodos = (completed) => {
todos.forEach((t) => (t.completed = completed));
todos = todos;
};
```
This will solve the problem. Internally Svelte will flag `todos` as changed and remove the apparently redundant self-assignment. Apart from the fact that it looks weird, it's perfectly OK to use this technique, and sometimes it's the most concise way to do it.
We could also access the `todos` array by index, like this:
```js
const checkAllTodos = (completed) => {
todos.forEach((t, i) => (todos[i].completed = completed));
};
```
Assignments to properties of arrays and objects β e.g. `obj.foo += 1` or `array[i] = x` β work the same way as assignments to the values themselves. When Svelte analyzes this code, it can detect that the `todos` array is being modified.
Another solution is to assign a new array to `todos` containing a copy of all the to-dos with the `completed` property updated accordingly, like this:
```js
const checkAllTodos = (completed) => {
todos = todos.map((t) => ({ ...t, completed }));
};
```
In this case we are using the `map()` method, which returns a new array with the results of executing the provided function for each item. The function returns a copy of each to-do using spread syntax and overwrites the property of the completed value accordingly. This solution has the added benefit of returning a new array with new objects, completely avoiding mutating the original `todos` array.
**Note:** Svelte allows us to specify different options that affect how the compiler works. The `<svelte:options immutable={true}/>` option tells the compiler that you promise not to mutate any objects. This allows it to be less conservative about checking whether values have changed and generate simpler and more performant code. For more information on `<svelte:options>`, check the Svelte options documentation.
All of these solutions involve an assignment in which the updated variable is on the left side of the equation. Any of this techniques will allow Svelte to notice that our `todos` array has been modified.
**Choose one, and update your `checkAllTodos()` function as required. Now you should be able to check and uncheck all your to-dos at once. Try it!**
Finishing our MoreActions component
-----------------------------------
We will add one usability detail to our component. We'll disable the buttons when there are no tasks to be processed. To create this, we'll receive the `todos` array as a prop, and set the `disabled` property of each button accordingly.
1. Update your `MoreActions.svelte` component like this:
```svelte
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
export let todos;
let completed = true;
const checkAll = () => {
dispatch('checkAll', completed);
completed = !completed;
}
const removeCompleted = () => dispatch('removeCompleted');
$: completedTodos = todos.filter((t) => t.completed).length;
</script>
<div class="btn-group">
<button type="button" class="btn btn\_\_primary"
disabled={todos.length === 0} on:click={checkAll}>{completed ? 'Check' : 'Uncheck'} all</button>
<button type="button" class="btn btn\_\_primary"
disabled={completedTodos === 0} on:click={removeCompleted}>Remove completed</button>
</div>
```
We've also declared a reactive `completedTodos` variable to enable or disable the *Remove Completed* button.
2. Don't forget to pass the prop into `MoreActions` from inside `Todos.svelte`, where the component is called:
```svelte
<MoreActions {todos}
on:checkAll={(e) => checkAllTodos(e.detail)}
on:removeCompleted={removeCompletedTodos}
/>
```
Working with the DOM: focusing on the details
---------------------------------------------
Now that we have completed all of the app's required functionality, we'll concentrate on some accessibility features that will improve the usability of our app for both keyboard-only and screen reader users.
In its current state our app has a couple of keyboard accessibility problems involving focus management. Let's have a look at these issues.
Exploring keyboard accessibility issues in our to-do app
--------------------------------------------------------
Right now, keyboard users will find out that the focus flow of our app is not very predictable or coherent.
If you click on the input at the top of our app, you'll see a thick, dashed outline around that input. This outline is your visual indicator that the browser is currently focused on this element.
If you are a mouse user, you might have skipped this visual hint. But if you are working exclusively with the keyboard, knowing which control has focus is of vital importance. It tells us which control is going to receive our keystrokes.
If you press the `Tab` key repeatedly, you'll see the dashed focus indicator cycling between all the focusable elements on the page. If you move the focus to the *Edit* button and press `Enter`, suddenly the focus disappears, and you can no longer tell which control will receive our keystrokes.
Moreover, if you press the `Escape` or `Enter` key, nothing happens. And if you click on *Cancel* or *Save*, the focus disappears again. For a user working with the keyboard, this behavior will be confusing at best.
We'd also like to add some usability features, like disabling the *Save* button when required fields are empty, giving focus to certain HTML elements or auto-selecting contents when a text input receives focus.
To implement all these features, we'll need programmatic access to DOM nodes to run functions like `focus()` and `select()`. We will also have to use `addEventListener()` and `removeEventListener()` to run specific tasks when the control receives focus.
The problem is that all these DOM nodes are dynamically created by Svelte at runtime. So we'll have to wait for them to be created and added to the DOM in order to use them. To do so, we'll have to learn about the component lifecycle to understand when we can access them β more on this later.
Creating a NewTodo component
----------------------------
Let's begin by extracting our new to-do form out to its own component. With what we know so far we can create a new component file and adjust the code to emit an `addTodo` event, passing the name of the new to-do in with the additional details.
1. Create a new file, `components/NewTodo.svelte`.
2. Put the following contents inside it:
```svelte
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
let name = '';
const addTodo = () => {
dispatch('addTodo', name);
name = '';
}
const onCancel = () => name = '';
</script>
<form on:submit|preventDefault={addTodo} on:keydown={(e) => e.key === 'Escape' && onCancel()}>
<h2 class="label-wrapper">
<label for="todo-0" class="label\_\_lg">What needs to be done?</label>
</h2>
<input bind:value={name} type="text" id="todo-0" autoComplete="off" class="input input\_\_lg" />
<button type="submit" disabled={!name} class="btn btn\_\_primary btn\_\_lg">Add</button>
</form>
```
Here we are binding the `<input>` to the `name` variable with `bind:value={name}` and disabling the *Add* button when it is empty (i.e. no text content) using `disabled={!name}`. We are also taking care of the `Escape` key with `on:keydown={(e) => e.key === 'Escape' && onCancel()}`. Whenever the `Escape` key is pressed we run `onCancel()`, which just clears up the `name` variable.
3. Now we have to `import` and use it from inside the `Todos` component, and update the `addTodo()` function to receive the name of the new todo.
Add the following `import` statement below the others inside `Todos.svelte`:
```js
import NewTodo from "./NewTodo.svelte";
```
4. And update the `addTodo()` function like so:
```js
function addTodo(name) {
todos = [...todos, { id: newTodoId, name, completed: false }];
}
```
`addTodo()` now receives the name of the new to-do directly, so we no longer need the `newTodoName` variable to give it its value. Our `NewTodo` component takes care of that.
**Note:** The `{ name }` syntax is just a shorthand for `{ name: name }`. This one comes from JavaScript itself and has nothing to do with Svelte, besides providing some inspiration for Svelte's own shorthands.
5. Finally for this section, replace the NewTodo form markup with a call to `NewTodo` component, like so:
```svelte
<!-- NewTodo -->
<NewTodo on:addTodo={(e) => addTodo(e.detail)} />
```
Working with DOM nodes using the `bind:this={dom_node}` directive
-----------------------------------------------------------------
Now we want the `<input>`element of the `NewTodo` component to re-gain focus every time the *Add* button is pressed. For that we'll need a reference to the DOM node of the input. Svelte provides a way to do this with the `bind:this={dom_node}` directive. When specified, as soon as the component is mounted and the DOM node is created, Svelte assigns a reference to the DOM node to the specified variable.
We'll create a `nameEl` variable and bind it to the input using `bind:this={nameEl}`. Then inside `addTodo()`, after adding the new to-do we will call `nameEl.focus()` to refocus the `<input>` again. We will do the same when the user presses the `Escape` key, with the `onCancel()` function.
Update the contents of `NewTodo.svelte` like so:
```svelte
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
let name = '';
let nameEl; // reference to the name input DOM node
const addTodo = () => {
dispatch('addTodo', name);
name = '';
nameEl.focus(); // give focus to the name input
}
const onCancel = () => {
name = '';
nameEl.focus(); // give focus to the name input
}
</script>
<form on:submit|preventDefault={addTodo} on:keydown={(e) => e.key === 'Escape' && onCancel()}>
<h2 class="label-wrapper">
<label for="todo-0" class="label\_\_lg">What needs to be done?</label>
</h2>
<input bind:value={name} bind:this={nameEl} type="text" id="todo-0" autoComplete="off" class="input input\_\_lg" />
<button type="submit" disabled={!name} class="btn btn\_\_primary btn\_\_lg">Add</button>
</form>
```
Try the app out: type a new to-do name in to the `<input>` field, press `tab` to give focus to the *Add* button, and then hit `Enter` or `Escape` to see how the input recovers focus.
### Autofocusing our input
The next feature will add to our `NewTodo` component will be an `autofocus` prop, which will allow us to specify that we want the `<input>` field to be focused on page load.
1. Our first attempt is as follows: let's try adding the `autofocus` prop and just call `nameEl.focus()` from the `<script>` block. Update the first part of the `<script>` section of `NewTodo.svelte` (the first four lines) to look like this:
```svelte
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
export let autofocus = false;
let name = '';
let nameEl; // reference to the name input DOM node
if (autofocus) nameEl.focus();
```
2. Now go back to the `Todos` component and pass the `autofocus` prop into the `<NewTodo>` component call, like so:
```svelte
<!-- NewTodo -->
<NewTodo autofocus on:addTodo={(e) => addTodo(e.detail)} />
```
3. If you try your app out now, you'll see that the page is now blank, and in your DevTools web console you'll see an error along the lines of: `TypeError: nameEl is undefined`.
To understand what's happening here, let's talk some more about that component lifecycle we mentioned earlier.
Component lifecycle, and the `onMount()` function
-------------------------------------------------
When a component is instantiated, Svelte runs the initialization code (that is, the `<script>` section of the component). But at that moment, all the nodes that comprise the component are not attached to the DOM, in fact, they don't even exist.
So how can you know when the component has already been created and mounted on the DOM? The answer is that every component has a lifecycle that starts when it is created and ends when it is destroyed. There are a handful of functions that allow you to run code at key moments during that lifecycle.
The one you'll use most frequently is `onMount()`, which lets us run a callback as soon as the component has been mounted on the DOM. Let's give it a try and see what happens to the `nameEl` variable.
1. To start with, add the following line at the beginning of the `<script>` section of `NewTodo.svelte`:
```js
import { onMount } from "svelte";
```
2. And these lines at the end of it:
```js
console.log("initializing:", nameEl);
onMount(() => {
console.log("mounted:", nameEl);
});
```
3. Now remove the `if (autofocus) nameEl.focus()` line to avoid throwing the error we were seeing before.
4. The app will now work again, and you'll see the following in your console:
```
initializing: undefined
mounted: <input id="todo-0" class="input input__lg" type="text" autocomplete="off">
```
As you can see, while the component is initializing, `nameEl` is undefined, which makes sense because the `<input>` node doesn't even exist yet. After the component has been mounted, Svelte assigned a reference to the `<input>` DOM node to the `nameEl` variable, thanks to the `bind:this={nameEl} directive`.
5. To get the autofocus functionality working, replace the previous `console.log()`/`onMount()` block you added with this:
```js
onMount(() => autofocus && nameEl.focus()); // if autofocus is true, we run nameEl.focus()
```
6. Go to your app again, and you'll now see the `<input>` field is focused on page load.
**Note:** You can have a look at the other lifecycle functions in the Svelte docs, and you can see them in action in the interactive tutorial.
Waiting for the DOM to be updated with the `tick()` function
------------------------------------------------------------
Now we will take care of the `Todo` component's focus management details. First of all, we want a `Todo` component's edit `<input>` to receive focus when we enter editing mode by pressing its *Edit* button. In the same fashion as we saw earlier, we'll create a `nameEl` variable inside `Todo.svelte` and call `nameEl.focus()` after setting the `editing` variable to `true`.
1. Open the file `components/Todo.svelte` and add a `nameEl` variable declaration just below your editing and name declarations:
```js
let nameEl; // reference to the name input DOM node
```
2. Now update your `onEdit()` function like so:
```js
function onEdit() {
editing = true; // enter editing mode
nameEl.focus(); // set focus to name input
}
```
3. And finally, bind `nameEl` to the `<input>` field by updating it like so:
```svelte
<input
bind:value={name}
bind:this={nameEl}
type="text"
id="todo-{todo.id}"
autocomplete="off"
class="todo-text" />
```
4. However, when you try the updated app, you'll get an error along the lines of "TypeError: nameEl is undefined" in the console when you press a to-do's *Edit* button.
So, what is happening here? When you update a component's state in Svelte, it doesn't update the DOM immediately. Instead, it waits until the next microtask to see if there are any other changes that need to be applied, including in other components. Doing so avoids unnecessary work and allows the browser to batch things more effectively.
In this case, when `editing` is `false`, the edit `<input>` is not visible because it does not exist in the DOM. Inside the `onEdit()` function we set `editing = true` and immediately afterwards try to access the `nameEl` variable and execute `nameEl.focus()`. The problem here is that Svelte hasn't yet updated the DOM.
One way to solve this problem is to use `setTimeout()` to delay the call to `nameEl.focus()` until the next event cycle, and give Svelte the opportunity to update the DOM.
Try this now:
```js
function onEdit() {
editing = true; // enter editing mode
setTimeout(() => nameEl.focus(), 0); // asynchronous call to set focus to name input
}
```
The above solution works, but it is rather inelegant. Svelte provides a better way to handle these cases. The `tick()` function returns a promise that resolves as soon as any pending state changes have been applied to the DOM (or immediately, if there are no pending state changes). Let's try it now.
1. First of all, import `tick` at the top of the `<script>` section alongside your existing import:
```js
import { tick } from "svelte";
```
2. Next, call `tick()` with `await` from an async function; update `onEdit()` like so:
```js
async function onEdit() {
editing = true; // enter editing mode
await tick();
nameEl.focus();
}
```
3. If you try it now you'll see that everything works as expected.
**Note:** To see another example using `tick()`, visit the Svelte tutorial.
Adding functionality to HTML elements with the `use:action` directive
---------------------------------------------------------------------
Next up, we want the name `<input>` to automatically select all text on focus. Moreover, we want to develop this in such a way that it could be easily reused on any HTML `<input>` and applied in a declarative way. We will use this requirement as an excuse to show a very powerful feature that Svelte provides us to add functionality to regular HTML elements: actions.
To select the text of a DOM input node, we have to call `select()`. To get this function called whenever the node gets focused, we need an event listener along these lines:
```js
node.addEventListener("focus", (event) => node.select());
```
And, in order to avoid memory leaks, we should also call the `removeEventListener()` function when the node is destroyed.
**Note:** All this is just standard WebAPI functionality; nothing here is specific to Svelte.
We could achieve all this in our `Todo` component whenever we add or remove the `<input>` from the DOM, but we would have to be very careful to add the event listener after the node has been added to the DOM, and remove the listener before the node is removed from the DOM. In addition, our solution would not be very reusable.
That's where Svelte actions come into play. Basically they let us run a function whenever an element has been added to the DOM, and after removal from the DOM.
In our immediate use case, we will define a function called `selectOnFocus()` that will receive a node as a parameter. The function will add an event listener to that node so that whenever it gets focused it will select the text. Then it will return an object with a `destroy` property. The `destroy` property is what Svelte will execute after removing the node from the DOM. Here we will remove the listener to make sure we don't leave any memory leak behind.
1. Let's create the function `selectOnFocus()`. Add the following to the bottom of the `<script>` section of `Todo.svelte`:
```js
function selectOnFocus(node) {
if (node && typeof node.select === "function") {
// make sure node is defined and has a select() method
const onFocus = (event) => node.select(); // event handler
node.addEventListener("focus", onFocus); // when node gets focus call onFocus()
return {
destroy: () => node.removeEventListener("focus", onFocus), // this will be executed when the node is removed from the DOM
};
}
}
```
2. Now we need to tell the `<input>` to use that function with the `use:action` directive:
```svelte
<input use:selectOnFocus />
```
With this directive we are telling Svelte to run this function, passing the DOM node of the `<input>` as a parameter, as soon as the component is mounted on the DOM. It will also be in charge of executing the `destroy` function when the component is removed from DOM. So with the `use` directive, Svelte takes care of the component's lifecycle for us.
In our case, our `<input>` would end up like so: update the component's first label/input pair (inside the edit template) as follows:
```svelte
<label for="todo-{todo.id}" class="todo-label">New name for '{todo.name}'</label>
<input
bind:value={name}
bind:this={nameEl}
use:selectOnFocus
type="text"
id="todo-{todo.id}"
autocomplete="off"
class="todo-text" />
```
3. Let's try it out. Go to your app, press a to-do's *Edit* button, then `Tab` to take focus away from the `<input>`. Now click on the `<input>`, and you'll see that the entire input text is selected.
### Making the action reusable
Now let's make this function truly reusable across components. `selectOnFocus()` is just a function without any dependency on the `Todo.svelte` component, so we can just extract it to a file and use it from there.
1. Create a new file, `actions.js`, inside the `src` folder.
2. Give it the following content:
```js
export function selectOnFocus(node) {
if (node && typeof node.select === "function") {
// make sure node is defined and has a select() method
const onFocus = (event) => node.select(); // event handler
node.addEventListener("focus", onFocus); // when node gets focus call onFocus()
return {
destroy: () => node.removeEventListener("focus", onFocus), // this will be executed when the node is removed from the DOM
};
}
}
```
3. Now import it from inside `Todo.svelte`; add the following import statement just below the others:
```js
import { selectOnFocus } from "../actions.js";
```
4. And remove the `selectOnFocus()` definition from `Todo.svelte`, since we no longer need it there.
### Reusing our action
To demonstrate our action's reusability, let's make use of it in `NewTodo.svelte`.
1. Import `selectOnFocus()` from `actions.js` in this file too, as before:
```js
import { selectOnFocus } from "../actions.js";
```
2. Add the `use:selectOnFocus` directive to the `<input>`, like this:
```svelte
<input
bind:value={name}
bind:this={nameEl}
use:selectOnFocus
type="text"
id="todo-0"
autocomplete="off"
class="input input\_\_lg" />
```
With a few lines of code we can add functionality to regular HTML elements in a very reusable and declarative way. It just takes an `import` and a short directive like `use:selectOnFocus` that clearly describes its purpose. And we can achieve this without the need to create a custom wrapper element like `TextInput`, `MyInput`, or similar. Moreover, you can add as many `use:action` directives as you want to an element.
Also, we didn't have to struggle with `onMount()`, `onDestroy()`, or `tick()` β the `use` directive takes care of the component lifecycle for us.
### Other actions improvements
In the previous section, while working with the `Todo` components, we had to deal with `bind:this`, `tick()`, and `async` functions just to give focus to our `<input>` as soon as it was added to the DOM.
1. This is how we can implement it with actions instead:
```js
const focusOnInit = (node) =>
node && typeof node.focus === "function" && node.focus();
```
2. And then in our markup we just need to add another `use:` directive:
```svelte
<input bind:value={name} use:selectOnFocus use:focusOnInit />
```
3. Our `onEdit()` function can now be much simpler:
```js
function onEdit() {
editing = true; // enter editing mode
}
```
As a last example before we move on, let's go back to our `Todo.svelte` component and give focus to the *Edit* button after the user presses *Save* or *Cancel*.
We could try just reusing our `focusOnInit` action again, adding `use:focusOnInit` to the *Edit* button. But we'd be introducing a subtle bug. When you add a new to-do, the focus will be put on the *Edit* button of the recently added to-do. That's because the `focusOnInit` action is running when the component is created.
That's not what we want β we want the *Edit* button to receive focus only when the user has pressed *Save* or *Cancel*.
1. So, go back to your `Todo.svelte` file.
2. First we'll create a flag named `editButtonPressed` and initialize it to `false`. Add this just below your other variable definitions:
```js
let editButtonPressed = false; // track if edit button has been pressed, to give focus to it after cancel or save
```
3. Next we'll modify the *Edit* button's functionality to save this flag, and create the action for it. Update the `onEdit()` function like so:
```js
function onEdit() {
editButtonPressed = true; // user pressed the Edit button, focus will come back to the Edit button
editing = true; // enter editing mode
}
```
4. Below it, add the following definition for `focusEditButton()`:
```js
const focusEditButton = (node) => editButtonPressed && node.focus();
```
5. Finally we `use` the `focusEditButton` action on the *Edit* button, like so:
```svelte
<button type="button" class="btn" on:click={onEdit} use:focusEditButton>
Edit<span class="visually-hidden"> {todo.name}</span>
</button>
```
6. Go back and try your app again. At this point, every time the *Edit* button is added to the DOM, the `focusEditButton` action is executed, but it will only give focus to the button if the `editButtonPressed` flag is `true`.
**Note:** We have barely scratched the surface of actions here. Actions can also have reactive parameters, and Svelte lets us detect when any of those parameters change. So we can add functionality that integrates nicely with the Svelte reactive system. For a more detailed introduction to actions, consider checking out the Svelte Interactive tutorial or the Svelte `use:action` documentation.
Component binding: exposing component methods and variables using the `bind:this={component}` directive
-------------------------------------------------------------------------------------------------------
There's still one accessibility annoyance left. When the user presses the *Delete* button, the focus vanishes.
The last feature we will be looking at in this article involves setting the focus on the status heading after a to-do has been deleted.
Why the status heading? In this case, the element that had the focus has been deleted, so there's not a clear candidate to receive focus. We've picked the status heading because it's near the list of to-dos, and it's a way to give a visual feedback about the removal of the task, as well as indicating what's happened to screen reader users.
First we'll extract the status heading to its own component.
1. Create a new file, `components/TodosStatus.svelte`.
2. Add the following contents to it:
```svelte
<script>
export let todos;
$: totalTodos = todos.length;
$: completedTodos = todos.filter((todo) => todo.completed).length;
</script>
<h2 id="list-heading">
{completedTodos} out of {totalTodos} items completed
</h2>
```
3. Import the file at the beginning of `Todos.svelte`, adding the following `import` statement below the others:
```js
import TodosStatus from "./TodosStatus.svelte";
```
4. Replace the `<h2>` status heading inside `Todos.svelte` with a call to the `TodosStatus` component, passing `todos` to it as a prop, like so:
```svelte
<TodosStatus {todos} />
```
5. You can also do a bit of cleanup, removing the `totalTodos` and `completedTodos` variables from `Todos.svelte`. Just remove the `$: totalTodos = β¦` and the `$: completedTodos = β¦` lines, and also remove the reference to `totalTodos` when we calculate `newTodoId` and use `todos.length` instead. To do this, replace the block that begins with `let newTodoId` with this:
```js
$: newTodoId = todos.length ? Math.max(...todos.map((t) => t.id)) + 1 : 1;
```
6. Everything works as expected β we just extracted the last piece of markup to its own component.
Now we need to find a way to give focus to the `<h2>` status label after a to-do has been removed.
So far we saw how to send information to a component via props, and how a component can communicate with its parent by emitting events or using two-way data binding. The child component could get a reference to the `<h2>` node `using bind:this={dom_node}` and expose it to the outside using two-way data binding. But doing so would break the component encapsulation; setting focus on it should be its own responsibility.
So we need the `TodosStatus` component to expose a method that its parent can call to give focus to it. It's a very common scenario that a component needs to expose some behavior or information to the consumer; let's see how to achieve it with Svelte.
We've already seen that Svelte uses `export let varname = β¦` to declare props. But if instead of using `let` you export a `const`, `class`, or `function`, it is read-only outside the component. Function expressions are valid props, however. In the following example, the first three declarations are props, and the rest are exported values:
```svelte
<script>
export let bar = "optional default initial value"; // prop
export let baz = undefined; // prop
export let format = (n) => n.toFixed(2); // prop
// these are readonly
export const thisIs = "readonly"; // read-only export
export function greet(name) {
// read-only export
alert(`Hello, ${name}!`);
}
export const greet = (name) => alert(`Hello, ${name}!`); // read-only export
</script>
```
With this in mind, let's go back to our use case. We'll create a function called `focus()` that gives focus to the `<h2>` heading. For that we'll need a `headingEl` variable to hold the reference to the DOM node, and we'll have to bind it to the `<h2>` element using `bind:this={headingEl}`. Our focus method will just run `headingEl.focus()`.
1. Update the contents of `TodosStatus.svelte` like so:
```svelte
<script>
export let todos;
$: totalTodos = todos.length;
$: completedTodos = todos.filter((todo) => todo.completed).length;
let headingEl;
export function focus() {
// shorter version: export const focus = () => headingEl.focus()
headingEl.focus();
}
</script>
<h2 id="list-heading" bind:this={headingEl} tabindex="-1">
{completedTodos} out of {totalTodos} items completed
</h2>
```
Note that we've added a `tabindex` attribute to the `<h2>` to allow the element to receive focus programmatically.
As we saw earlier, using the `bind:this={headingEl}` directive gives us a reference to the DOM node in the variable `headingEl`. Then we use `export function focus()` to expose a function that gives focus to the `<h2>` heading.
How can we access those exported values from the parent? Just as you can bind to DOM elements with the `bind:this={dom_node}` directive, you can also bind to component instances themselves with `bind:this={component}`. So, when you use `bind:this` on an HTML element, you get a reference to the DOM node, and when you do it on a Svelte component, you get a reference to the instance of that component.
2. So to bind to the instance of `TodosStatus`, we'll first create a `todosStatus` variable in `Todos.svelte`. Add the following line below your `import` statements:
```js
let todosStatus; // reference to TodosStatus instance
```
3. Next, add a `bind:this={todosStatus}` directive to the call, as follows:
```svelte
<!-- TodosStatus -->
<TodosStatus bind:this={todosStatus} {todos} />
```
4. Now we can call the `exported focus()` method from our `removeTodo()` function:
```js
function removeTodo(todo) {
todos = todos.filter((t) => t.id !== todo.id);
todosStatus.focus(); // give focus to status heading
}
```
5. Go back to your app. Now if you delete any to-do, the status heading will be focussed. This is useful to highlight the change in numbers of to-dos, both to sighted users and screen reader users.
**Note:** You might be wondering why we need to declare a new variable for component binding. Why can't we just call `TodosStatus.focus()`? You might have multiple `TodosStatus` instances active, so you need a way to reference each particular instance. That's why you have to specify a variable to bind each specific instance to.
The code so far
---------------
### Git
To see the state of the code as it should be at the end of this article, access your copy of our repo like this:
```bash
cd mdn-svelte-tutorial/06-stores
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/06-stores
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To see the current state of the code in a REPL, visit:
https://svelte.dev/repl/d1fa84a5a4494366b179c87395940039?version=3.23.2
Summary
-------
In this article we have finished adding all the required functionality to our app, plus we've taken care of a number of accessibility and usability issues. We also finished splitting our app into manageable components, each one with a unique responsibility.
In the meantime, we saw a few advanced Svelte techniques, like:
* Dealing with reactivity gotchas when updating objects and arrays
* Working with DOM nodes using `bind:this={dom_node}` (binding DOM elements)
* Using the component lifecycle `onMount()` function
* Forcing Svelte to resolve pending state changes with the `tick()` function
* Adding functionality to HTML elements in a reusable and declarative way with the `use:action` directive
* Accessing component methods using `bind:this={component}` (binding components)
In the next article we will see how to use stores to communicate between components, and add animations to our components.
* Previous
* Overview: Client-side JavaScript frameworks
* Next |
Handling common accessibility problems - Learn web development | Handling common accessibility problems
======================================
* Previous
* Overview: Cross browser testing
* Next
Next we turn our attention to accessibility, providing information on common problems, how to do simple testing, and how to make use of auditing/automation tools for finding accessibility issues.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages; an idea
of the high level
principles of cross browser testing.
|
| Objective: |
To be able to diagnose common Accessibility problems, and use
appropriate tools and techniques to fix them.
|
What is accessibility?
----------------------
When we say accessibility in the context of web technology, most people immediately think of making sure websites/apps are usable by people with disabilities, for example:
* Visually impaired people using screen readers or magnification/zoom to access text
* People with motor function impairments using the keyboard (or other non-mouse features) to activate website functionality.
* People with hearing impairments relying on captions/subtitles or other text alternatives for audio/video content.
However, it is wrong to say that accessibility is just about disabilities. Really, the aim of accessibility is to make your websites/apps usable by as many people in as many contexts as possible, not just those users using high-powered desktop computers. Some examples might include:
* Users on mobile devices.
* Users on alternative browsing devices such as TVs, watches, etc.
* Users of older devices that might not have the latest browsers.
* Users of lower spec devices that might have slow processors.
In a way, this whole module is about accessibility β cross browser testing makes sure that your sites can be used by as many people as possible. What is accessibility? defines accessibility more completely and thoroughly than this article does.
That said, this article will cover cross browser and testing issues surrounding people with disabilities, and how they use the Web. We've already talked about other spheres such as responsive design and performance in other places in the module.
**Note:** Like many things in web development, accessibility isn't about 100% success or not; 100% accessibility is pretty much impossible to achieve for all content, especially as sites get more complex. Instead, it is more about making a reasonable effort to make as much of your content accessible to as many people as possible via defensive coding and sticking to best practices.
Common accessibility issues
---------------------------
In this section we'll detail some of the main issues that arise around web accessibility, connected with specific technologies, along with best practices to follow, and some quick tests you can do to see if your sites are going in the right direction.
**Note:** Accessibility is morally the right thing to do, and good for business (numbers of disabled users, users on mobile devices, etc. present significant market segments), but it is also a legal requirement in many parts of the world to make web content accessible to people with disabilities. Read Accessibility guidelines and the law for more information.
### HTML
Semantic HTML (where the elements are used for their correct purpose) is accessible right out of the box β such content is readable by sighted viewers (provided you don't do anything silly like make the text way too small or hide it using CSS), but will also be usable by assistive technologies like screen readers (apps that literally read out a web page to their user), and confer other advantages too.
#### Semantic structure
The most important quick win in semantic HTML is to use a structure of headings and paragraphs for your content; this is because screen reader users tend to use the headings of a document as signposts to find the content they need more quickly. If your content has no headings, all they will get is a huge wall of text with no signposts to find anything. Examples of bad and good HTML:
```html
<font size="7">My heading</font>
<br /><br />
This is the first section of my document.
<br /><br />
I'll add another paragraph here too.
<br /><br />
<font size="5">My subheading</font>
<br /><br />
This is the first subsection of my document. I'd love people to be able to find
this content!
<br /><br />
<font size="5">My 2nd subheading</font>
<br /><br />
This is the second subsection of my content. I think it is more interesting than
the last one.
```
```html
<h1>My heading</h1>
<p>This is the first section of my document.</p>
<p>I'll add another paragraph here too.</p>
<h2>My subheading</h2>
<p>
This is the first subsection of my document. I'd love people to be able to
find this content!
</p>
<h2>My 2nd subheading</h2>
<p>
This is the second subsection of my content. I think it is more interesting
than the last one.
</p>
```
In addition, your content should make logical sense in its source order β you can always place it where you want using CSS later on, but you should get the source order right to start with.
As a test, you can turn off a site's CSS and see how understandable it is without it. You could do this manually by just removing the CSS from your code, but the easiest way is to use browser features, for example:
* Firefox: Select *View > Page Style > No Style* from the main menu.
* Safari: Select *Develop > Disable Styles* from the main menu (to enable the *Develop* menu, choose *Safari > Preferences > Advanced > Show Develop menu in menu bar*).
* Chrome: Install the Web Developer Toolbar extension, then restart the browser. Click the gear icon that will appear, then select *CSS > Disable All Styles*.
* Edge: Select *View > Style > No Style* from the main menu.
#### Using native keyboard accessibility
Certain HTML features can be selected using only the keyboard β this is default behavior, available since the early days of the web. The elements that have this capability are the common ones that allow user to interact with web pages, namely links, `<button>`s, and form elements like `<input>`.
You can try this out using our native-keyboard-accessibility.html example (see the source code) β open this in a new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements; the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused.
![A screenshot of three buttons demonstrating sample of the default behavior of interactive native elements. The third button is highlighted by a blue border to indicate its focus state.](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility/button-focused-unfocused.png)
**Note:** In Firefox, you can also enable an overlay that shows the page tabbing order. For more information see: Accessibility Inspector > Show web page tabbing order.
You can then press Enter/Return to follow a focused link or press a button (we've included some JavaScript to make the buttons alert a message), or start typing to enter text in a text input (other form elements have different controls, for example the `<select>` element can have its options displayed and cycled between using the up and down arrow keys).
Note that different browsers may have different keyboard control options available. Most modern browsers follow the tab pattern described above (you can also do Shift + Tab to move backwards through the focusable elements), but some browsers have their own idiosyncrasies:
* Firefox for the Mac doesn't do tabbing by default. To turn it on, you have to go to *Preferences > Advanced > General*, then uncheck "Always use the cursor keys to navigate within pages". Next, you have to open your Mac's System Preferences app, then go to *Keyboard > Shortcuts*, then select the *All Controls* radio button.
* Safari doesn't allow you to tab through links by default; to enable this, you need to open Safari's *Preferences*, go to Advanced, and check the *Press Tab to highlight each item on a webpage* checkbox.
**Warning:** You should perform this kind of test/review on any new page you write β make sure that functionality can be accessed by the keyboard, and that the tab order provides a sensible navigation path through the document.
This example highlights the importance of using the correct semantic element for the correct job. It is possible to style *any* element to look like a link or button with CSS, and to behave like a link or button with JavaScript, but they won't actually be links or buttons, and you'll lose a lot of the accessibility these elements give you for free. So don't do it if you can avoid it.
Another tip β as shown in our example, you can control how your focusable elements look when focused, using the :focus pseudo-class. It is a good idea to double up focus and hover styles, so your users get that visual clue that a control will do something when activated, whether they are using mouse or keyboard:
```css
a:hover,
input:hover,
button:hover,
select:hover,
a:focus,
input:focus,
button:focus,
select:focus {
font-weight: bold;
}
```
**Note:** If you do decide to remove the default focus styling using CSS, make sure you replace it with something else that fits in with your design better β it is a very valuable accessibility tool, and should not be removed.
#### Building in keyboard accessibility
Sometimes it is not possible to avoid losing keyboard accessibility. You might have inherited a site where the semantics are not very good (perhaps you've ended up with a horrible CMS that generates buttons made with `<div>`s), or you are using a complex control that does not have keyboard accessibility built in, like the HTML `<video>` element (amazingly, Opera is the only browser that allows you to tab through the `<video>` element's default browser controls). You have a few options here:
1. Create custom controls using `<button>` elements (which we can tab to by default!) and JavaScript to wire up their functionality. See Creating a cross-browser video player for some good examples of this.
2. Create keyboard shortcuts via JavaScript, so functionality is activated when you press certain keys on the keyboard. See Desktop mouse and keyboard controls for some game-related examples that can be adapted for any purpose.
3. Use some interesting tactics to fake button behavior. Take for example our fake-div-buttons.html example (see source code). Here we've given our fake `<div>` buttons the ability to be focused (including via tab) by giving each one the attribute `tabindex="0"` (see WebAIM's tabindex article for more really useful details). This allows us to tab to the buttons, but not to activate them via the Enter/Return key. To do that, we had to add the following bit of JavaScript trickery:
```js
document.onkeydown = (e) => {
if (e.keyCode === 13) {
// The Enter/Return key
document.activeElement.onclick(e);
}
};
```
Here we add a listener to the `document` object to detect when a button has been pressed on the keyboard. We check what button was pressed via the event object's keyCode property; if it is the keycode that matches Return/Enter, we run the function stored in the button's `onclick` handler using `document.activeElement.onclick()`. `activeElement` gives us the element that is currently focused on the page.
**Note:** This technique will only work if you set your original event handlers via event handler properties (e.g. `onclick`). `addEventListener` won't work. This is a lot of extra hassle to build the functionality back in. And there's bound to be other problems with it. Better to just use the right element for the right job in the first place.
#### Text alternatives
Text alternatives are very important for accessibility β if a person has a visual or hearing impairment that stops them being able to see or hear some content, then this is a problem. The simplest text alternative available is the humble `alt` attribute, which we should include on all images that contain relevant content. This should contain a description of the image that successfully conveys its meaning and content on the page, to be picked up by a screen reader and read out to the user.
**Note:** For more information, read Text alternatives.
Missing alt text can be tested for in a number of ways, for example using accessibility Auditing tools.
Alt text is slightly more complex for video and audio content. There is a way to define text tracks (e.g. subtitles) and display them when video is being played, in the form of the `<track>` element, and the WebVTT format (see Adding captions and subtitles to HTML video for a detailed tutorial). Browser compatibility for these features is fairly good, but if you want to provide text alternatives for audio or support older browsers, a simple text transcript presented somewhere on the page or on a separate page might be a good idea.
#### Element relationships and context
There are certain features and best practices in HTML designed to provide context and relationships between elements where none otherwise exists. The three most common examples are links, form labels, and data tables.
The key to accessible link text is that people using screen readers will often use a common feature whereby they pull up a list of all the links on the page. In this case, the link text needs to make sense out of context. For example, a list of links labeled "click here", "click me", etc. is really bad for accessibility. It is better for link text to make sense in context and out of context.
Next on our list, the form `<label>` element is one of the central features that allows us to make forms accessible. The trouble with forms is that you need labels to say what data should be entered into each form input. Each label needs to be included inside a `<label>` to link it unambiguously to its partner form input (the `for` attribute value of each `<label>` needs to match the form element `id` value), and it will make sense even if the source order is not completely logical (which to be fair it should be).
**Note:** For more information about link text and form labels, read Meaningful text labels.
Finally, a quick word about data tables. A basic data table can be written with very simple markup (see `bad-table.html` live, and source), but this has problems β there is no way for a screen reader user to associate rows or columns together as groupings of data β to do this you need to know what the header rows are, and if they are heading up rows, columns, etc. This can only be done visually for such a table.
If you instead look at our `punk-bands-complete.html` example (live, source), you can see a few accessibility aids at work here, such as table headers (`<th>` and `scope` attributes), `<caption>` element, etc.
**Note:** For more information about accessible tables, read Accessible data tables.
### CSS
CSS tends to provide a lot fewer fundamental accessibility features than HTML, but it can still do just as much damage to accessibility if used incorrectly. We have already mentioned a couple of accessibility tips involving CSS:
* Use the correct semantic elements to mark up different content in HTML; if you want to create a different visual effect, use CSS β don't abuse an HTML element to get the look you want. For example, if you want bigger text, use `font-size`, not an h1 element.
* Make sure your source order makes sense without CSS; you can always use CSS to style the page any way you want afterward.
* You should make sure interactive elements like buttons and links have appropriate focus/hover/active states set, to give the user visual clues as to their function. If you remove the defaults for stylistic reasons, make sure you include some replacement styles.
There are a few other considerations you should take into account.
#### Color and color contrast
When choosing a color scheme for your website, you should make sure that the text (foreground) color contrasts well with the background color. Your design might look cool, but it is no good if people with visual impairments like color blindness can't read your content. Use a tool like WebAIM's Color Contrast Checker to check whether your scheme is contrasting enough.
Another tip is to not rely on color alone for signposts/information, as this will be no good for those who can't see the color. Instead of marking required form fields in red, for example, mark them with an asterisk and in red.
**Note:** A high contrast ratio will also allow anyone using a smartphone or tablet with a glossy screen to better read pages when in a bright environment, such as sunlight.
#### Hiding content
There are many instances where a visual design will require that not all content is shown at once. For example, in our Tabbed info box example (see source code) we have three panels of information, but we are positioning them on top of one another and providing tabs that can be clicked to show each one (it is also keyboard accessible β you can alternatively use Tab and Enter/Return to select them).
![A screenshot demonstrating an example of accessible hiding and showing content in tabs. The example has three tabs namely Tab 1, Tab 2 and Tab 3. Tab 1 is currently focused and activated to display content.](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility/20191022144107.png)
Screen reader users don't care about any of this β they are happy with the content as long as the source order makes sense, and they can get to it all. Absolute positioning (as used in this example) is generally seen as one of the best mechanisms of hiding content for visual effect, because it doesn't stop screen readers from getting to it.
On the other hand, you shouldn't use `visibility``:hidden` or `display``:none`, because they do hide content from screen readers. Unless of course, there is a good reason why you want this content to be hidden from screen readers.
**Note:** Invisible Content Just for Screen Reader Users has a lot more useful detail surrounding this topic.
### JavaScript
JavaScript has the same kind of problems as CSS with respect to accessibility β it can be disastrous for accessibility if used badly, or overused. We've already hinted at some accessibility problems related to JavaScript, mainly in the area of semantic HTML β you should always use appropriate semantic HTML to implement functionality wherever it is available, for example use links and buttons as appropriate. Don't use `<div>` elements with JavaScript code to fake functionality if at all possible β it is error-prone, and more work than using the free functionality HTML gives you.
#### Simple functionality
Generally simple functionality should work with just the HTML in place β JavaScript should only be used to enhance functionality, not build it in entirely. Good uses of JavaScript include:
* Providing client-side form validation, which alerts users to problems with their form entries quickly, without having to wait for the server to check the data. If it isn't available, the form will still work, but validation might be slower.
* Providing custom controls for HTML `<video>`s that are accessible to keyboard-only users (as we said earlier, the default browser controls aren't keyboard-accessible in most browsers).
**Note:** WebAIM's Accessible JavaScript provides some useful further details about considerations for accessible JavaScript.
More complex JavaScript implementations can create issues with accessibility β you need to do what you can. For example, it would be unreasonable to expect you to make a complex 3D game written using WebGL 100% accessible to a blind person, but you could implement keyboard controls so it is usable by non-mouse users, and make the color scheme contrasting enough to be usable by those with color deficiencies.
#### Complex functionality
One of the main areas problematic for accessibility is complex apps that involve complicated form controls (such as date pickers) and dynamic content that is updated often and incrementally.
Non-native complicated form controls are problematic because they tend to involve a lot of nested `<div>`s, and the browser does not know what to do with them by default. If you are inventing them yourself, you need to make sure that they are keyboard accessible; if you are using some kind of third-party framework, carefully review the options available to see how accessible they are before diving in. Bootstrap looks to be fairly good for accessibility, for example, although Making Bootstrap a Little More Accessible by Rhiana Heath explores some of its issues (mainly related to color contrast), and looks at some solutions.
Regularly updated dynamic content can be a problem because screen reader users might miss it, especially if it updates unexpectedly. If you have a single-page app with a main content panel that is regularly updated using XMLHttpRequest or Fetch, a screen reader user might miss those updates.
#### WAI-ARIA
Do you need to use such complex functionality, or will plain old semantic HTML do instead? If you do need complexity, you should consider using WAI-ARIA (Accessible Rich Internet Applications), a specification that provides semantics (in the form of new HTML attributes) for items such as complex form controls and updating panels that can be understood by most browsers and screen readers.
To deal with complex form widgets, you need to use ARIA attributes like `roles` to state what role different elements have in a widget (for example, are they a tab, or a tab panel?), `aria-disabled` to say whether a control is disabled or not, etc.
To deal with regularly updating regions of content, you can use the `aria-live` attribute, which identifies an updating region. Its value indicates how urgently the screen reader should read it out:
* `off:` The default. Updates should not be announced.
* `polite`: Updates should be announced only if the user is idle.
* `assertive`: Updates should be announced to the user as soon as possible.
* `rude`: Updates should be announced straight away, even if this interrupts the user.
Here's an example:
```html
<p><span id="LiveRegion1" aria-live="polite" aria-atomic="false"></span></p>
```
You can see an example in action at Freedom Scientific's ARIA (Accessible Rich Internet Applications) Live Regions example β the highlighted paragraph should update its content every 10 seconds, and a screen reader should read this out to the user. ARIA Live Regions - Atomic provides another useful example.
We don't have space to cover WAI-ARIA in detail here, you can learn a lot more about it at WAI-ARIA basics.
Accessibility tools
-------------------
Now we've covered accessibility considerations for different web technologies, including a few testing techniques (like keyboard navigation and color contrast checkers), let's have a look at other tools you can make use of when doing accessibility testing.
### Auditing tools
There are a number of auditing tools available that you can feed your web pages into. They will look over them and return a list of accessibility issues present on the page. Examples include:
* Wave: A rather nice online accessibility testing tool that accepts a web address and returns a useful annotated view of that page with accessibility problems highlighted.
* Tenon: Another nice online tool that goes through the code at a provided URL and returns results on accessibility errors including metrics, specific errors along with the WCAG criteria they affect, and suggested fixes. It requires a free trial signup to view the results.
Let's look at an example, using Wave.
1. Go to the Wave homepage.
2. Enter the URL of our bad-semantics.html example into the text input box near the top of the page. Then press enter or click/tap the arrow at the far right edge of the input box.
3. The site should respond with a description of the accessibility problems. Click the icons displayed to see more information about each of the issues identified by Wave's evaluation.
**Note:** Such tools aren't good enough to solve all your accessibility problems on their own. You'll need a combination of these, knowledge and experience, user testing, etc. to get a full picture.
### Automation tools
Deque's aXe tool goes a bit further than the auditing tools we mentioned above. Like the others, it checks pages and returns accessibility errors. Its most immediately useful form is probably the browser extensions:
* aXe for Chrome
* aXe for Firefox
These add an accessibility tab to the browser developer tools. For example, we installed the Firefox version, then used it to audit our bad-table.html example. We got the following results:
![A screenshot of accessibility issues identified by the Axe tool.](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility/axe-screenshot.png)
aXe is also installable using `npm`, and can be integrated with task runners like Grunt and Gulp, automation frameworks like Selenium and Cucumber, unit testing frameworks like Jasmine, and more besides (again, see the main aXe page for details).
### Screen readers
It is definitely worth testing with a screen reader to get used to how severely visually impaired people use the Web. There are a number of screen readers available:
* Some are paid-for commercial products, like JAWS (Windows) and Window Eyes (Windows).
* Some are free products, like NVDA (Windows), ChromeVox (Chrome, Windows, and macOS), and Orca (Linux).
* Some are built into the operating system, like VoiceOver (macOS and iOS), ChromeVox (on Chromebooks), and TalkBack (Android).
Generally, screen readers are separate apps that run on the host operating system and can read not only web pages, but text in other apps as well. This is not always the case (ChromeVox is a browser extension), but usually, screen readers tend to act in slightly different ways and have different controls, so you'll have to consult the documentation for your chosen screen reader to get all the details β saying that, they all work in basically the same sort of way.
Let's go through some tests with a couple of different screen readers to give you a general idea of how they work and how to test with them.
**Note:** WebAIM's Designing for Screen Reader Compatibility provides some useful information about screen reader usage and what works best for screen readers. Also see Screen Reader User Survey #9 Results for some interesting screen reader usage statistics.
#### VoiceOver
VoiceOver (VO) comes free with your Mac/iPhone/iPad, so it's useful for testing on desktop/mobile if you use Apple products. We'll be testing it on Mac OS X on a MacBook Pro.
To turn it on, press Cmd + F5. If you've not used VO before, you will be given a welcome screen where you can choose to start VO or not, and run through a rather useful tutorial to learn how to use it. To turn it off again, press Cmd + F5 again.
**Note:** You should go through the tutorial at least once β it is a really useful way to learn VO.
When VO is on, the display will look mostly the same, but you'll see a black box at the bottom left of the screen that contains information on what VO currently has selected. The current selection will also be highlighted, with a black border β this highlight is known as the **VO cursor**.
![A sample screenshot demonstrating accessibility testing using VoiceOver on the MDN homepage. The bottom left of the image is a highlight of the information selected on the webpage.](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility/voiceover.png)
To use VO, you will make a lot of use of the "VO modifier" β this is a key or key combination that you need to press in addition to the actual VO keyboard shortcuts to get them to work. Using a modifier like this is common with screen readers, to enable them to keep their commands from clashing with other commands. In the case of VO, the modifier can either be CapsLock, or Ctrl + Option.
VO has many keyboard commands, and we won't list them all here. The basic ones you'll need for web page testing are in the following table. In the keyboard shortcuts, "VO" means "the VoiceOver modifier".
Most common VoiceOver keyboard shortcuts| Keyboard shortcut | Description |
| --- | --- |
| VO + Cursor keys | Move the VO cursor up, right, down, left. |
| VO + Spacebar |
Select/activate items highlighted by the VO cursor. This includes items
selected in the Rotor (see below).
|
| VO + Shift + down cursor |
Move into a group of items (such as an HTML table, or a form, etc.) Once
inside a group you can move around and select items inside that group
using the above commands as normal.
|
| VO + Shift + up cursor | Move out of a group. |
| VO + C | (when inside a table) Read the header of the current column. |
| VO + R | (when inside a table) Read the header of the current row. |
| VO + C + C (two Cs in succession) | (when inside a table) Read the entire current column, including header. |
| VO + R + R (two Rs in succession) |
(when inside a table) Read the entire current row, including the headers
that correspond to each cell.
|
| VO + left cursor, VO + right cursor |
(when inside some horizontal options, such as a date or time picker)
Move between options.
|
| VO + up cursor, VO + down cursor |
(when inside some horizontal options, such as a date or time picker)
Change the current option.
|
| VO + U |
Use the Rotor, which displays lists of headings, links, form controls,
etc. for easy navigation.
|
| VO + left cursor, VO + right cursor | (when inside Rotor) Move between different lists available in the Rotor. |
| VO + up cursor, VO + down cursor |
(when inside Rotor) Move between different items in the current Rotor
list.
|
| Esc | (when inside Rotor) Exit Rotor. |
| Ctrl | (when VO is speaking) Pause/Resume speech. |
| VO + Z | Restart the last bit of speech. |
| VO + D | Go into the Mac's Dock, so you can select apps to run inside it. |
This seems like a lot of commands, but it isn't so bad when you get used to it, and VO regularly gives you reminders of what commands to use in certain places. Have a play with VO now; you can then go on to play with some of our examples in the Screen reader testing section.
#### NVDA
NVDA is Windows-only, and you'll need to install it.
1. Download it from nvaccess.org. You can choose whether to make a donation or download it for free; you'll also need to give them your email address before you can download it.
2. Once downloaded, install it β you double-click the installer, accept the license and follow the prompts.
3. To start NVDA, double-click on the program file/shortcut, or use the keyboard shortcut Ctrl + Alt + N. You'll see the NVDA welcome dialog when you start it. Here you can choose from a couple of options, then press the *OK* button to get going.
NVDA will now be active on your computer.
To use NVDA, you will make a lot of use of the "NVDA modifier" β this is a key that you need to press in addition to the actual NVDA keyboard shortcuts to get them to work. Using a modifier like this is common with screen readers, to enable them to keep their commands from clashing with other commands. In the case of NVDA, the modifier can either be Insert (the default), or CapsLock (can be chosen by checking the first checkbox in the NVDA welcome dialog before pressing *OK*).
**Note:** NVDA is more subtle than VoiceOver in terms of how it highlights where it is and what it is doing. When you are scrolling through headings, lists, etc., items you are selected on will generally be highlighted with a subtle outline, but this is not always the case for all things. If you get completely lost, you can press Ctrl + F5 to refresh the current page and begin from the top again.
NVDA has many keyboard commands, and we won't list them all here. The basic ones you'll need for web page testing are in the following table. In the keyboard shortcuts, "NVDA" means "the NVDA modifier".
Most common NVDA keyboard shortcuts| Keyboard shortcut | Description |
| --- | --- |
| NVDA + Q | Turn NVDA off again after you've started it. |
| NVDA + up cursor | Read the current line. |
| NVDA + down cursor | Start reading at the current position. |
| Up cursor and down cursor, or Shift + Tab and Tab | Move to previous/next item on page and read it. |
| Left cursor and right cursor | Move to previous/next character in current item and read it. |
| Shift + H and H | Move to previous/next heading and read it. |
| Shift + K and K | Move to previous/next link and read it. |
| Shift + D and D |
Move to previous/next document landmark (e.g. `<nav>`)
and read it.
|
| Shift + 1β6 and 1β6 | Move to previous/next heading (level 1β6) and read it. |
| Shift + F and F | Move to previous/next form input and focus on it. |
| Shift + T and T | Move to previous/next data table and focus on it. |
| Shift + B and B | Move to previous/next button and read its label. |
| Shift + L and L | Move to previous/next list and read its first list item. |
| Shift + I and I | Move to previous/next list item and read it. |
| Enter/Return | (when link/button or other activatable item is selected) Activate item. |
| NVDA + Space |
(when form is selected) Enter form so individual items can be selected,
or leave form if you are already in it.
|
| Shift Tab and Tab | (when inside form) Move between form inputs. |
| Up cursor and down cursor |
(when inside form) Change form input values (in the case of things like
select boxes).
|
| Spacebar | (when inside form) Select chosen value. |
| Ctrl + Alt + cursor keys | (when a table is selected) Move between table cells. |
#### Screen reader testing
Now you've gotten used to using a screen reader, we'd like you to use it to do some quick accessibility tests, to get an idea of how screen readers deal with good and bad webpage features:
* Look at good-semantics.html, and note how the headers are found by the screen reader and available to use for navigation. Now look at bad-semantics.html, and note how the screen reader gets none of this information. Imagine how annoying this would be when trying to navigate a really long page of text.
* Look at good-links.html, and note how they make sense when viewed out of context. This is not the case with bad-links.html β they are all just "click here".
* Look at good-form.html, and note how the form inputs are described using their labels because we've used `<label>` elements properly. In bad-form.html, they get an unhelpful label along the lines of "blank".
* Look at our punk-bands-complete.html example, and see how the screen reader is able to associate columns and rows of content and read them out all together because we've defined headers properly. In bad-table.html, none of the cells can be associated at all. Note that NVDA seems to behave slightly strangely when you've only got a single table on a page; you could try WebAIM's table test page instead.
* Have a look at the WAI-ARIA live regions example we saw earlier, and note how the screen reader will keep reading out the constantly updating section as it updates.
### User testing
As mentioned above, you can't rely on automated tools alone for determining accessibility problems on your site. It is recommended that when you draw up your testing plan, you should include some accessibility user groups if at all possible (see our User Testing section earlier on in the course for some more context). Try to get some screen reader users involved, some keyboard-only users, some non-hearing users, and perhaps other groups too, as suits your requirements.
Accessibility testing checklist
-------------------------------
The following list provides a checklist for you to follow to make sure you've carried out the recommended accessibility testing for your project:
1. Make sure your HTML is as semantically correct as possible. Validating it is a good start, as is using an Auditing tool.
2. Check that your content makes sense when the CSS is turned off.
3. Make sure your functionality is keyboard accessible. Test using Tab, Return/Enter, etc.
4. Make sure your non-text content has text alternatives. An Auditing tool is good for catching such problems.
5. Make sure your site's color contrast is acceptable, using a suitable checking tool.
6. Make sure hidden content is visible by screen readers.
7. Make sure that functionality is usable without JavaScript wherever possible.
8. Use ARIA to improve accessibility where appropriate.
9. Run your site through an Auditing tool.
10. Test it with a screen reader.
11. Include an accessibility policy/statement somewhere findable on your site to say what you did.
Finding help
------------
There are many other issues you'll encounter with accessibility; the most important thing to know really is how to find answers online. Consult the HTML and CSS article's Finding help section for some good pointers.
Summary
-------
Hopefully this article has given you a good grounding in the main accessibility problems you might encounter, and how to test and overcome them.
In the next article we'll look at feature detection in more detail.
* Previous
* Overview: Cross browser testing
* Next |
Implementing feature detection - Learn web development | Implementing feature detection
==============================
* Previous
* Overview: Cross browser testing
* Next
Feature detection involves working out whether a browser supports a certain block of code, and running different code depending on whether it does (or doesn't), so that the browser can always provide a working experience rather than crashing/erroring in some browsers. This article details how to write your own simple feature detection, how to use a library to speed up implementation, and native features for feature detection such as `@supports`.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages; an idea
of the high-level
principles of cross-browser testing.
|
| Objective: |
To understand what the concept of feature detection is, and be able to
implement suitable solutions in CSS and JavaScript.
|
The concept of feature detection
--------------------------------
The idea behind feature detection is that you can run a test to determine whether a feature is supported in the current browser, and then conditionally run code to provide an acceptable experience both in browsers that *do* support the feature, and browsers that *don't*. If you don't do this, browsers that don't support the features you are using in your code may not display your sites properly or might fail altogether, creating a bad user experience.
Let's recap and look at the example we touched on in our Handling common JavaScript problems β the Geolocation API (which exposes available location data for the device the web browser is running on) has the main entry point for its use, a `geolocation` property available on the global Navigator object. Therefore, you can detect whether the browser supports geolocation or not by using something like the following:
```js
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function (position) {
// show the location on a map, such as the Google Maps API
});
} else {
// Give the user a choice of static maps
}
```
Before we move on, we'd like to say one thing upfront β don't confuse feature detection with **browser sniffing** (detecting what specific browser is accessing the site) β this is a terrible practice that should be discouraged at all costs. See Using bad browser sniffing code for more details.
Writing your own feature detection tests
----------------------------------------
In this section, we'll look at implementing your own feature detection tests, in both CSS and JavaScript.
### CSS
You can write tests for CSS features by testing for the existence of *element.style.property* (e.g. `paragraph.style.rotate`) in JavaScript.
A classic example might be to test for Subgrid support in a browser; for browsers that support the `subgrid` value for a subgrid value for `grid-template-columns` and `grid-template-rows`, we can use subgrid in our layout. For browsers that don't, we could use regular grid that works fine but is not as cool-looking.
Using this as an example, we could include a subgrid stylesheet if the value is supported and a regular grid stylesheet if not. To do so, we could include two stylesheets in the head of our HTML file: one for all the styling, and one that implements the default layout if subgrid is not supported:
```html
<link href="basic-styling.css" rel="stylesheet" />
<link class="conditional" href="grid-layout.css" rel="stylesheet" />
```
Here, `basic-styling.css` handles all the styling that we want to give to every browser. We have two additional CSS files, `grid-layout.css` and `subgrid-layout.css`, which contain the CSS we want to selectively apply to browsers depending on their support levels.
We use JavaScript to test the support for the subgrid value, then update the `href` of our conditional stylesheet based on browser support.
We can add a `<script></script>` to our document, filled with the following JavaScript
```js
const conditional = document.querySelector(".conditional");
if (CSS.supports("grid-template-columns", "subgrid")) {
conditional.setAttribute("href", "subgrid-layout.css");
}
```
In our conditional statement, we test to see if the`grid-template-columns` property supports the `subgrid` value using `CSS.supports()`.
#### @supports
CSS has a native feature detection mechanism: the `@supports` at-rule. This works in a similar manner to media queries except that instead of selectively applying CSS depending on a media feature like a resolution, screen width or aspect ratio, it selectively applies CSS depending on whether a CSS feature is supported, similar to `CSS.supports()`.
For example, we could rewrite our previous example to use `@supports`:
```css
@supports (grid-template-columns: subgrid) {
main {
display: grid;
grid-template-columns: repeat(9, 1fr);
grid-template-rows: repeat(4, minmax(100px, auto));
}
.item {
display: grid;
grid-column: 2 / 7;
grid-row: 2 / 4;
grid-template-columns: subgrid;
grid-template-rows: repeat(3, 80px);
}
.subitem {
grid-column: 3 / 6;
grid-row: 1 / 3;
}
}
```
This at-rule block applies the CSS rule within only if the current browser supports the `grid-template-columns: subgrid;` declaration. For a condition with a value to work, you need to include a complete declaration (not just a property name) and NOT include the semicolon on the end.
`@supports` also has `AND`, `OR`, and `NOT` logic available β the other block applies the regular grid layout if the subgrid option is not available:
```css
@supports not (grid-template-columns: subgrid) {
/\* rules in here \*/
}
```
This is more convenient than the previous example β we can do all of our feature detection in CSS, no JavaScript required, and we can handle all the logic in a single CSS file, cutting down on HTTP requests. For this reason it is the preferred method of determining browser support for CSS features.
### JavaScript
We already saw an example of a JavaScript feature detection test earlier on. Generally, such tests are done via one of a few common patterns.
Common patterns for detectable features include:
Members of an object
Check whether a particular method or property (typically an entry point into using the API or other feature you are detecting) exists in its parent `Object`.
Our earlier example used this pattern to detect Geolocation support by testing the `navigator` object for a `geolocation` member:
```js
if ("geolocation" in navigator) {
// Access navigator.geolocation APIs
}
```
Properties of an element
Create an element in memory using `Document.createElement()` and then check if a property exists on it.
This example shows a way of detecting Canvas API support:
```js
function supports\_canvas() {
return !!document.createElement("canvas").getContext;
}
if (supports\_canvas()) {
// Create and draw on canvas elements
}
```
**Note:** The double `NOT` in the above example (`!!`) is a way to force a return value to become a "proper" boolean value, rather than a Truthy/Falsy value that may skew the results.
Specific return values of a method on an element
Create an element in memory using `Document.createElement()` and then check if a method exists on it. If it does, check what value it returns. See the feature test in Dive into HTML Video Format detection for an example of this pattern.
Retention of assigned property value by an element
Create an element in memory using `Document.createElement()`, set a property to a specific value, then check to see if the value is retained. See the feature test in Dive into HTML <input> type detection for an example of this pattern.
Bear in mind that some features are, however, known to be undetectable. In these cases, you'll need to use a different approach, such as using a polyfill.
#### matchMedia
We also wanted to mention the `Window.matchMedia` JavaScript feature at this point too. This is a property that allows you to run media query tests inside JavaScript. It looks like this:
```js
if (window.matchMedia("(max-width: 480px)").matches) {
// run JavaScript in here.
}
```
As an example, our Snapshot demo makes use of it to selectively apply the Brick JavaScript library and use it to handle the UI layout, but only for the small screen layout (480px wide or less). We first use the `media` attribute to only apply the Brick CSS to the page if the page width is 480px or less:
```html
<link
href="dist/brick.css"
rel="stylesheet"
media="all and (max-width: 480px)" />
```
We then use `matchMedia()` in the JavaScript several times, to only run Brick navigation functions if we are on the small screen layout (in wider screen layouts, everything can be seen at once, so we don't need to navigate between different views).
```js
if (window.matchMedia("(max-width: 480px)").matches) {
deck.shuffleTo(1);
}
```
Summary
-------
This article covered feature detection in a reasonable amount of detail, going through the main concepts and showing you how to implement your own feature detection tests.
Next up, we'll start looking at automated testing.
* Previous
* Overview: Cross browser testing
* Next |
Handling common JavaScript problems - Learn web development | Handling common JavaScript problems
===================================
* Previous
* Overview: Cross browser testing
* Next
Now we'll look at common cross-browser JavaScript problems and how to fix them.
This includes information on using browser dev tools to track down and fix problems, using Polyfills and libraries to work around problems, getting modern JavaScript features working in older browsers, and more.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages; an idea of the high-level principles of cross browser testing.
|
| Objective: | To be able to diagnose common JavaScript cross-browser problems, and use appropriate tools and techniques to fix them. |
The trouble with JavaScript
---------------------------
Historically, JavaScript was plagued with cross-browser compatibility problems β back in the 1990s, the main browser choices back then (Internet Explorer and Netscape) had scripting implemented in different language flavors (Netscape had JavaScript, IE had JScript and also offered VBScript as an option), and while at least JavaScript and JScript were compatible to some degree (both based on the ECMAScript specification), things were often implemented in conflicting, incompatible ways, causing developers many nightmares.
Such incompatibility problems persisted well into the early 2000s, as old browsers were still being used and still needed supporting. For example, code to create `XMLHttpRequest` objects had to have special handling for Internet Explorer 6:
```js
if (window.XMLHttpRequest) {
// Mozilla, Safari, IE7+ ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// IE 6 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
```
This is one of the main reasons why libraries like jQuery came into existence β to abstract away differences in browser implementations, so a developer could just use, for example, `jQuery.ajax()`, which would then handle the differences in the background.
Things have improved significantly since then; modern browsers do a good job of supporting "classic JavaScript features", and the requirement to use such code has diminished as the requirement to support older browsers has lessened (although bear in mind that they have not gone away altogether).
These days, most cross-browser JavaScript problems are seen:
* When poor-quality browser-sniffing code, feature-detection code, and vendor prefix usage block browsers from running code they could otherwise use just fine.
* When developers make use of new/nascent JavaScript features, modern Web APIs, etc.) in their code, and find that such features don't work in older browsers.
We'll explore all these problems and more below.
Fixing general JavaScript problems
----------------------------------
As we said in the previous article on HTML/CSS, you should make sure your code is working generally, before going on to concentrate on the cross-browser issues. If you are not already familiar with the basics of Troubleshooting JavaScript, you should study that article before moving on. There are a number of common JavaScript problems that you will want to be mindful of, such as:
* Basic syntax and logic problems (again, check out Troubleshooting JavaScript).
* Making sure variables, etc. are defined in the correct scope, and you are not running into conflicts between items declared in different places (see Function scope and conflicts).
* Confusion about this, in terms of what scope it applies to, and therefore if its value is what you intended. You can read What is "this"? for a light introduction; you should also study examples like this one, which shows a typical pattern of saving a `this` scope to a separate variable, then using that variable in nested functions so you can be sure you are applying functionality to the correct `this` scope.
* Incorrectly using functions inside loops that iterate with a global variable (more generally "getting the scope wrong").
For example, in bad-for-loop.html (see source code), we loop through 10 iterations using a variable defined with `var`, each time creating a paragraph and adding an onclick event handler to it. When clicked, we want each one to display an alert message containing its number (the value of `i` at the time it was created). Instead they all report `i` as 11 β because the `for` loop does all its iterating before nested functions are invoked.
The easiest solution is to declare the iteration variable with `let` instead of `var`βthe value of `i` associated with the function is then unique to each iteration. See good-for-loop.html (see the source code also) for a version that works.
* Making sure asynchronous operations have completed before trying to use the values they return. This usually means understanding how to use *promises*: using `await` appropriately or running the code to handle the result of an asynchronous call in the promise's `then()` handler. See How to use promises for an introduction to this topic.
**Note:** Buggy JavaScript Code: The 10 Most Common Mistakes JavaScript Developers Make has some nice discussions of these common mistakes and more.
### Linters
As with HTML and CSS, you can ensure better quality, less error-prone JavaScript code using a linter, which points out errors and can also flag up warnings about bad practices, etc., and be customized to be stricter or more relaxed in their error/warning reporting. The JavaScript/ECMAScript linters we'd recommend are JSHint and ESLint; these can be used in a variety of ways, some of which we'll detail below.
#### Online
The JSHint homepage provides an online linter, which allows you to enter your JavaScript code on the left and provides an output on the right, including metrics, warnings, and errors.
![JSHint screenshot. Left panel is a color-coded and line-numbered code editor. Right panel is divided into metrics on the number, size, and makeup of functions and warnings. The warnings include the issue and the line number.](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript/jshint-online.png)
#### Code editor plugins
It is not very convenient to have to copy and paste your code over to a web page to check its validity several times. What you really want is a linter that will fit into your standard workflow with the minimum of hassle. Many code editors have linter plugins. For example, see the "Plugins for text editors and IDEs" section of the JSHint install page.
#### Other uses
There are other ways to use such linters; you can read about them on the JSHint and ESLint install pages.
It is worth mentioning command line uses β you can install these tools as command line utilities (available via the CLI β command line interface) using npm (Node Package Manager β you'll have to install NodeJS first). For example, the following command installs JSHint:
```bash
npm install -g jshint
```
You can then point these tools at JavaScript files you want to lint, for example:
![jshint filename.js was entered at the command line. The response is a list of line numbers and a description of the error found.](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript/js-hint-commandline.png)
You can also use these tools with a task runner/build tool such as Gulp or Webpack to automatically lint your JavaScript during development. (see Using a task runner to automate testing tools in a later article.) See ESLint integrations for ESLint options; JSHint is supported out of the box by Grunt, and also has other integrations available, e.g. JSHint loader for Webpack.
**Note:** ESLint takes a bit more setup and configuration than JSHint, but it is more powerful too.
### Browser developer tools
Browser developer tools have many useful features for helping to debug JavaScript. For a start, the JavaScript console will report errors in your code.
Make a local copy of our fetch-broken example (see the source code also).
If you look at the console, you'll see an error message. The exact wording is browser-dependent, but it will be something like: "Uncaught TypeError: heroes is not iterable", and the referenced line number is 25. If we look at the source code, the relevant code section is this:
```js
function showHeroes(jsonObj) {
const heroes = jsonObj["members"];
for (const hero of heroes) {
// ...
}
}
```
So the code falls over as soon as we try to use `jsonObj` (which as you might expect, is supposed to be a JSON object). This is supposed to be fetched from an external `.json` file using the following `fetch()` call:
```js
const requestURL =
"https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json";
const response = fetch(requestURL);
populateHeader(response);
showHeroes(response);
```
But this fails.
#### The Console API
You may already know what is wrong with this code, but let's explore it some more to show how you could investigate this. For a start, there is a Console API that allows JavaScript code to interact with the browser's JavaScript console. It has a number of features available, but the one you'll use most often is `console.log()`, which prints a custom message to the console.
Try adding a `console.log()` call to log the return value of `fetch()`, like this:
```js
const requestURL =
"https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json";
const response = fetch(requestURL);
console.log(`Response value: ${response}`);
const superHeroes = response;
populateHeader(superHeroes);
showHeroes(superHeroes);
```
Refresh the page in the browser. This time, before the error message, you'll see a new message logged to the console:
```
Response value: [object Promise]
```
The `console.log()` output shows that the return value of `fetch()` is not the JSON data, it's a `Promise`. The `fetch()` function is asynchronous: it returns a `Promise` that is fulfilled only when the actual response has been received from the network. Before we can use the response, we have to wait for the `Promise` to be fulfilled.
We can do this by putting the code that uses the response inside the `then()` method of the returned `Promise`, like this:
```js
const response = fetch(requestURL);
fetch(requestURL).then((response) => {
populateHeader(response);
showHeroes(response);
});
```
To summarize, anytime something is not working and a value does not appear to be what it is meant to be at some point in your code, you can use `console.log()` to print it out and see what is happening.
#### Using the JavaScript debugger
Unfortunately, we still have the same error β the problem has not gone away. Let's investigate this now, using a more sophisticated feature of browser developer tools: the JavaScript debugger as it is called in Firefox.
**Note:** Similar tools are available in other browsers; the Sources tab in Chrome, Debugger in Safari (see Safari Web Development Tools), etc.
In Firefox, the Debugger tab looks like this:
![Firefox debugger](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript/debugger-tab.png)
* On the left, you can select the script you want to debug (in this case we have only one).
* The center panel shows the code in the selected script.
* The right-hand panel shows useful details pertaining to the current environment β *Breakpoints*, *Callstack* and currently active *Scopes*.
The main feature of such tools is the ability to add breakpoints to code β these are points where the execution of the code stops, and at that point you can examine the environment in its current state and see what is going on.
Let's get to work. The error is now being thrown at line 26. Click on line number 26 in the center panel to add a breakpoint to it (you'll see a blue arrow appear over the top of it). Now refresh the page (Cmd/Ctrl + R) β the browser will pause execution of the code at line 51. At this point, the right-hand side will update to show some very useful information.
![Firefox debugger with a breakpoint](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript/breakpoint.png)
* Under *Breakpoints*, you'll see the details of the break-point you have set.
* Under *Call Stack*, you'll see a few entries β this is basically a list of the series of functions that were invoked to cause the current function to be invoked. At the top, we have `showHeroes()` the function we are currently in, and second we have `onload`, which stores the event handler function containing the call to `showHeroes()`.
* Under *Scopes*, you'll see the currently active scope for the function we are looking at. We only have three β `showHeroes`, `block`, and `Window` (the global scope). Each scope can be expanded to show the values of variables inside the scope when execution of the code was stopped.
We can find out some very useful information in here.
1. Expand the `showHeroes` scope β you can see from this that the heroes variable is `undefined`, indicating that accessing the `members` property of `jsonObj` (first line of the function) didn't work.
2. You can also see that the `jsonObj` variable is storing a `Response` object, not a JSON object.
The argument to `showHeroes()` is the value the `fetch()` promise was fulfilled with. So this promise is not in the JSON format: it is a `Response` object. There's an extra step needed to retrieve the content of the response as a JSON object.
We'd like you to try fixing this problem yourself. To get you started, see the documentation for the `Response` object. If you get stuck, you can find the fixed source code at https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/javascript/fetch-fixed.
**Note:** The debugger tab has many other useful features that we've not discussed here, for example conditional breakpoints and watch expressions. For a lot more information, see the Debugger page.
### Performance issues
As your apps get more complex and you start to use more JavaScript, you may start to run into performance problems, especially when viewing apps on slower devices. Performance is a big topic, and we don't have time to cover it in detail here. Some quick tips are as follows:
* To avoid loading more JavaScript than you need, bundle your scripts into a single file using a solution like Browserify. In general, reducing the number of HTTP requests is very good for performance.
* Make your files even smaller by minifying them before you load them onto your production server. Minifying squashes all the code together onto a huge single line, making it take up far less file size. It is ugly, but you don't need to read it when it is finished! This is best done using a minification tool like Uglify (there's also an online version β see JSCompress.com)
* When using APIs, make sure you turn off the API features when they are not being used; some API calls can be really expensive on processing power. For example, when showing a video stream, make sure it is turned off when you can't see it. When tracking a device's location using repeated Geolocation calls, make sure you turn it off when the user stops using it.
* Animations can be really costly for performance. A lot of JavaScript libraries provide animation capabilities programmed by JavaScript, but it is much more cost effective to do the animations via native browser features like CSS Animations (or the nascent Web Animations API) than JavaScript. Read Brian Birtles' Animating like you just don't care with Element.animate for some really useful theory on why animation is expensive, tips on how to improve animation performance, and information on the Web Animations API.
**Note:** Addy Osmani's Writing Fast, Memory-Efficient JavaScript contains a lot of detail and some excellent tips for boosting JavaScript performance.
Cross-browser JavaScript problems
---------------------------------
In this section, we'll look at some of the more common cross-browser JavaScript problems. We'll break this down into:
* Using modern core JavaScript features
* Using modern Web API features
* Using bad browser sniffing code
* Performance problems
### Using modern JavaScript/API features
In the previous article we described some of the ways in which HTML and CSS errors and unrecognized features can be handled due to the nature of the languages. JavaScript is not as permissive as HTML and CSS however β if the JavaScript engine encounters mistakes or unrecognized syntax, such as when new, unsupported features are used, more often than not it will throw errors.
There are a few strategies for handling new feature support; let's explore the most common ones.
**Note:** These strategies do not exist in separate silos β you can, of course combine them as needed. For example, you could use feature detection to determine whether a feature is supported; if it isn't, you could then run code to load a polyfill or a library to handle the lack of support.
#### Feature detection
The idea behind feature detection is that you can run a test to determine whether a JavaScript feature is supported in the current browser, and then conditionally run code to provide an acceptable experience both in browsers that do and don't support the feature. As a quick example, the Geolocation API (which exposes available location data for the device the web browser is running on) has a main entry point for its use β a `geolocation` property available on the global Navigator object. Therefore, you can detect whether the browser supports geolocation or not by using something like the following:
```js
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
// show the location on a map, perhaps using the Google Maps API
});
} else {
// Give the user a choice of static maps instead perhaps
}
```
You could also write such a test for a CSS feature, for example by testing for the existence of *element.style.property* (e.g. `paragraph.style.transform !== undefined`).
If you're looking to apply styles if a CSS feature is supported, you can directly use the @supports at-rule (known as a feature query).
For example, to check whether the browser supports CSS container queries, you could do something like this:
```css
@supports (container-type: inline-size) {
/\* Use container queries if supported \*/
}
```
As a last point, don't confuse feature detection with **browser sniffing** (detecting what specific browser is accessing the site) β this is a terrible practice that should be discouraged at all costs. See Using bad browser sniffing code, later on, for more details.
**Note:** Feature detection will be covered in a lot more detail in its own dedicated article, later in the module.
#### Libraries
JavaScript libraries are essentially third party units of code that you can attach to your page, providing you with a wealth of ready-made functionality that can be used straight away, saving you a lot of time in the process. A lot of JavaScript libraries probably came into existence because their developer was writing a set of common utility functions to save them time when writing future projects, and decided to release them into the wild because other people might find them useful too.
JavaScript libraries tend to come in a few main varieties (some libraries will serve more than one of these purposes):
* Utility libraries: Provide a bunch of functions to make mundane tasks easier and less boring to manage. jQuery for example provides its own fully-featured selectors and DOM manipulation libraries, to allow CSS-selector type selecting of elements in JavaScript and easier DOM building. It is not so important now we have modern features like `Document.querySelector()`/`Document.querySelectorAll()`/`Node` methods available across browsers, but it can still be useful when older browsers need supporting.
* Convenience libraries: Make difficult things easier to do. For example, the WebGL API is really complex and challenging to use when you write it directly, so the Three.js library (and others) is built on top of WebGL and provides a much easier API for creating common 3D objects, lighting, textures, etc.
The Service Worker API is also very complex to use, so code libraries have started appearing to make common Service Worker uses-cases much easier to implement (see the Service Worker Cookbook for several useful code samples).
* Effects libraries: These libraries are designed to allow you to easily add special effects to your websites. This was more useful back when "DHTML" was a popular buzzword, and implementing an effect involved a lot of complex JavaScript, but these days browsers have a lot of built in CSS features and APIs to implementing effects more easily.
* UI libraries: Provide methods for implementing complex UI features that would otherwise be challenging to implement and get working cross browser, for example Foundation, Bootstrap, and Material-UI (the latter is a set of components for use with the React framework). These tend to be used as the basis of an entire site layout; it is often difficult to drop them in just for one UI feature.
* Normalization libraries: Give you a simple syntax that allows you to easily complete a task without having to worry about cross browser differences. The library will manipulate appropriate APIs in the background so the functionality will work whatever the browser (in theory). For example, LocalForage is a library for client-side data storage, which provides a simple syntax for storing and retrieving data. In the background, it uses the best API the browser has available for storing the data, whether that is IndexedDB, Web Storage, or even Web SQL (which is now deprecated, but is still supported in Chromium-based browsers in secure contexts). As another example, jQuery
When choosing a library to use, make sure that it works across the set of browsers you want to support, and test your implementation thoroughly. Also make sure that the library is popular and well-supported, and isn't likely to just become obsolete next week. Talk to other developers to find out what they recommend, see how much activity and how many contributors the library has on GitHub (or wherever else it is stored), etc.
Library usage at a basic level tends to consist of downloading the library's files (JavaScript, possibly some CSS or other dependencies too) and attaching them to your page (e.g. via a `<script>` element), although there are normally many other usage options for such libraries, like installing them as Bower components, or including them as dependencies via the Webpack module bundler. You will have to read the libraries' individual install pages for more information.
**Note:** You will also come across JavaScript frameworks in your travels around the Web, like Ember and Angular. Whereas libraries are often usable for solving individual problems and dropping into existing sites, frameworks tend to be more along the lines of complete solutions for developing complex web applications.
#### Polyfills
Polyfills also consist of 3rd party JavaScript files that you can drop into your project, but they differ from libraries β whereas libraries tend to enhance existing functionality and make things easier, polyfills provide functionality that doesn't exist at all. Polyfills use JavaScript or other technologies entirely to build in support for a feature that a browser doesn't support natively. For example, you might use a polyfill like es6-promise to make promises work in browsers where they are not supported natively.
Let's work through an exercise β in this example used for demonstration purposes only, we use a Fetch polyfill and an es6-promise polyfill. While Fetch and promises are fully supported in modern browsers, if we were targeting a browser that did not support Fetch that browser would likely not support Fetch either, and Fetch makes heavy use of promises:
1. To get started, make a local copy of our fetch-polyfill.html example and our nice image of some flowers in a new directory. We are going to write code to fetch the flowers image and display it in the page.
2. Next, save a copy of the Fetch polyfill in the same directory as the HTML.
3. Apply the polyfill scripts to the page using the following code β place these above the existing `<script>` element so they will be available on the page already when we start trying to use Fetch (we are also loading a Promise polyfill from a CDN, as IE11 does support promises, which fetch requires):
```html
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js"></script>
<script src="fetch.js"></script>
```
4. Inside the original `<script>`, add the following code:
```js
const myImage = document.querySelector(".my-image");
fetch("flowers.jpg").then((response) => {
response.blob().then((myBlob) => {
const objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
});
```
5. If you load it in a browser that doesn't support Fetch, you should still see the flower image appear β cool!
![heading reading fetch basic example with a photo of purple flowers](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript/fetch-image.jpg)
**Note:** You can find our finished version at fetch-polyfill-finished.html (see also the source code).
**Note:** Again, there are many different ways to make use of the different polyfills you will encounter β consult each polyfill's individual documentation.
One thing you might be thinking is "why should we always load the polyfill code, even if we don't need it?" This is a good point β as your sites get more complex and you start to use more libraries, polyfills, etc., you can start to load a lot of extra code, which can start to affect performance, especially on less-powerful devices. It makes sense to only load files as needed.
Doing this requires some extra setup in your JavaScript. You need some kind of a feature detection test that detects whether the browser supports the feature we are trying to use:
```js
if (browserSupportsAllFeatures()) {
main();
} else {
loadScript("polyfills.js", main);
}
function main(err) {
// actual app code goes in here
}
```
So first we run a conditional that checks whether the function `browserSupportsAllFeatures()` returns true. If it does, we run the `main()` function, which will contain all our app's code. `browserSupportsAllFeatures()` looks like this:
```js
function browserSupportsAllFeatures() {
return window.Promise && window.fetch;
}
```
Here we are testing whether the `Promise` object and `fetch()` function exist in the browser. If both do, the function returns true. If the function returns `false`, then we run the code inside the second part of the conditional β this runs a function called loadScript(), which loads the polyfills into the page, then runs `main()` after the loading has finished. `loadScript()` looks like this:
```js
function loadScript(src, done) {
const js = document.createElement("script");
js.src = src;
js.onload = () => {
done();
};
js.onerror = () => {
done(new Error(`Failed to load script ${src}`));
};
document.head.appendChild(js);
}
```
This function creates a new `<script>` element, then sets its `src` attribute to the path we specified as the first argument (`'polyfills.js'` when we called it in the code above). When it has loaded, we run the function we specified as the second argument (`main()`). If an error occurs in the loading of the script, we still call the function, but with a custom error that we can retrieve to help debug a problem if it occurs.
Note that polyfills.js is basically the two polyfills we are using put together into one file. We did this manually, but there are cleverer solutions that will automatically generate bundles for you β see Browserify (see Getting started with Browserify for a basic tutorial). It is a good idea to bundle JS files into one like this β reducing the number of HTTP requests you need to make improves the performance of your site.
You can see this code in action in fetch-polyfill-only-when-needed.html (see the source code also). We'd like to make it clear that we can't take credit for this code β it was originally written by Philip Walton. Check out his article Loading Polyfills Only When Needed for the original code, plus a lot of useful explanation around the wider subject).
**Note:** There are some 3rd party options to consider, for example Polyfill.io β this is a meta-polyfill library that will look at each browser's capabilities and apply polyfills as needed, depending on what APIs and JS features you are using in your code.
#### JavaScript transpiling
Another option that is becoming popular for people who want to use modern JavaScript features now is converting code that uses recent ECMAScript features to a version that will work in older browsers.
**Note:** This is called "transpiling" β you are not compiling code into a lower level to be run on a computer (like you would say with C code); instead, you are changing it into a syntax that exists at a similar level of abstraction so it can be used in the same way, but in slightly different circumstances (in this case, transforming one flavor of JavaScript into another).
A common transpiler is Babel.js but there are others.
### Don't browser sniff
Historically developers used *browser sniffing code* to detect which browser the user was using, and give them appropriate code to work on that browser.
All browsers have a **user-agent** string, which identifies what the browser is (version, name, OS, etc.). Many developers implemented bad browser sniffing code and didn't maintain it. This lead to supporting browsers getting locked out of using websites they could easily render. This became so common that browsers started to lie about what browser they were in their user-agent strings (or claim they were all browsers), to get around sniffing code. Browsers also implemented facilities to allow users to change what user-agent string the browser reported when queried with JavaScript. This all made browser sniffing even more error prone, and ultimately pointless.
History of the browser user-agent string by Aaron Andersen provides a useful and amusing take on the history of browser sniffing.
Use feature detection (and CSS @supports for CSS feature detection) to reliably detect whether a feature is supported. But doing so, you won't need to change your code when new browser versions come out.
### Handling JavaScript prefixes
In the previous article, we included quite a lot of discussion about handling CSS prefixes. Well, new JavaScript implementations used to use prefixes as well, with JavaScript using camel case rather than hyphenation like CSS. For example, if a prefix was being used on a new jshint API object called `Object`:
* Mozilla would use `mozObject`
* Chrome/Opera/Safari would use `webkitObject`
* Microsoft would use `msObject`
Here's an example, taken from our violent-theremin demo (see source code), which uses a combination of the Canvas API and the Web Audio API to create a fun (and noisy) drawing tool:
```js
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioCtx = new AudioContext();
```
In the case of the Web Audio API, the key entry points to using the API were supported in Chrome/Opera via `webkit` prefixed versions (they now support the unprefixed versions). The easy way to get around this situation is to create a new version of the objects that are prefixed in some browsers, and make it equal to the non-prefixed version, OR the prefixed version (OR any other prefixed versions that need consideration) β whichever one is supported by the browser currently viewing the site will be used.
Then we use that object to manipulate the API, rather than the original one. In this case we are creating a modified AudioContext constructor, then creating a new audio context instance to use for our Web Audio coding.
This pattern can be applied to just about any prefixed JavaScript feature. JavaScript libraries/polyfills also make use of this kind of code, to abstract browser differences away from the developer as much as possible.
Again, prefixed features were never supposed to be used in production websites β they are subject to change or removal without warning, and cause cross browser issues. If you insist on using prefixed features, make sure you use the right ones. You can look up what browsers require prefixes for different JavaScript/API features on MDN reference pages, and sites like caniuse.com. If you are unsure, you can also find out by doing some testing directly in browsers.
For example, try going into your browser's developer console and start typing
```js
window.AudioContext;
```
If this feature is supported in your browser, it will autocomplete.
Finding help
------------
There are many other issues you'll encounter with JavaScript; the most important thing to know really is how to find answers online. Consult the HTML and CSS article's Finding help section for our best advice.
Summary
-------
So that's JavaScript. Simple huh? Maybe not so simple, but this article should at least give you a start, and some ideas on how to tackle the JavaScript-related problems you will come across.
* Previous
* Overview: Cross browser testing
* Next |
Introduction to cross-browser testing - Learn web development | Introduction to cross-browser testing
=====================================
* Overview: Cross browser testing
* Next
This article gives an overview of cross-browser testing: what cross-browser testing is, some common problems, and some approaches for debugging/troubleshooting.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages.
|
| Objective: | To gain an understanding of the high-level concepts involved in cross-browser testing. |
What is cross-browser testing?
------------------------------
Cross-browser testing is the practice of ensuring that a website works across various browsers and devices. Web developers should consider:
* Different browsers, including slightly older ones that don't support all the latest JS/CSS features.
* Different devices, from desktops and laptops to tablets and smartphones, to smart TVs, with varying hardware capabilities.
* People with disabilities, who may rely on assistive technologies like screen readers, or use only a keyboard.
Remember that you are not your users β just because your site works on your MacBook Pro or high-end Galaxy Nexus, doesn't mean it will work for all your users!
**Note:** Make the web work for everyone discusses the different browsers, their market share, and related cross-browser compatibility issues.
Websites should be accessible across different browsers and devices, and to people with disabilities (e.g. screen-reader-friendly). A site doesn't need to deliver the exact same experience on all browsers and devices, as long as the core functionality is accessible in some way. For example, a modern browser might have something animated, 3D and shiny, while older browsers might just show a flat graphic with the same information.
Also, it's just about impossible for a website to work on ALL browsers and devices, so a web developer should come to an agreement with the site owner on the range of browsers and devices where the code will work.
Why do cross-browser issues occur?
----------------------------------
There are many different reasons why cross-browser issues occur, and note that here we are talking about issues where things behave differently across different browsers/devices/browsing preferences. Before you even get to cross-browser issues, you should have already fixed bugs in your code (see Debugging HTML, Debugging CSS, and What went wrong? Troubleshooting JavaScript from previous topics to refresh your memory if needed).
Cross-browser issues commonly occur because:
* sometimes browsers have bugs, or implement features differently. This situation is a lot less bad than it used to be; back when IE4 and Netscape 4 were competing to be the dominant browser in the 1990s, browser companies deliberately implemented things differently from each other to try to gain a competitive advantage, which made life hell for developers. Browsers are much better at following standards these days, but differences and bugs still creep through sometimes.
* some browsers may have different levels of support for technology features than others. This is inevitable when you are dealing with bleeding edge features that browsers are just getting around to implementing, or if you have to support very old browsers that are no longer being developed, which may have been frozen (i.e. no more new work done on them) a long time before a new feature was even invented. As an example, if you want to use cutting-edge JavaScript features in your site, they might not work in older browsers. If you need to support older browsers, you might have to not use those, or convert your code to old-fashioned syntax using some kind of cross-compiler where needed.
* some devices may have constraints that cause a website to run slowly, or display badly. For example, if a site has been designed to look nice on a desktop PC, it will probably look tiny and be hard to read on a mobile device. If your site includes a load of big animations, it might be OK on a high-spec tablet but might be sluggish or jerky on a low-end device.
β¦and more reasons besides.
In later articles, we'll explore common cross-browser problems, and look at solutions to those.
Workflows for cross-browser testing
-----------------------------------
All of this cross-browser testing business may sound time-consuming and scary, but it needn't be β you just need to plan carefully for it, and make sure you do enough testing in the right places to make sure you don't run into unexpected problems. If you are working on a large project, you should be testing it regularly, to make sure that new features work for your target audience, and that new additions to the code don't break old features that were previously working.
If you leave all the testing to the end of a project, any bugs you uncover will be a lot more expensive and time-consuming to fix than if you uncover them and fix them as you go along.
The workflow for testing and bug fixes on a project can be broken down into roughly the following four phases (this is only very rough β different people may do things quite differently to this):
**Initial planning** > **Development** > **Testing/discovery** > **Fixes/iteration**
Steps 2β4 will tend to be repeated as many times as necessary to get all of the implementation done. We will look at the different parts of the testing process in much greater detail in subsequent articles, but for now, let's just summarize what may occur in each step.
### Initial planning
In the initial planning phase, you will probably have several planning meetings with the site owner/client (this might be your boss, or someone from an external company you are building a website for), in which you determine exactly what the website should be β what content and functionality should it have, what should it look like, etc. At this point, you'll also want to know how much time you have to develop the site β what is their deadline, and how much are they going to pay you for your work? We won't go into much detail about this, but cross-browser issues can have a serious effect on such planning.
Once you've got an idea of the required feature set, and what technologies you will likely build these features with, you should start exploring the target audience β what browsers, devices, etc. will the target audience for this site be using? The client might already have data about this from previous research they've done, e.g. from other websites they own, or from previous versions of the website you are now working on. If not, you will be able to get a good idea by looking at other sources, such as usage stats for competitors, or countries the site will be serving. You can also use a bit of intuition.
So for example, you might be building an e-commerce site that serves customers in North America. The site should work entirely in the last few versions of the most popular desktop and mobile (iOS, Android, Windows phone) browsers β this should include Chrome (and Opera as it is based on the same rendering engine as Chrome), Firefox, Edge, and Safari.
It should also be accessible with WCAG AA compliance.
Now you know your target testing platforms, you should go back and review the required feature set and what technologies you are going to use.
For example, if the e-commerce site owner wants a WebGL-powered 3D tour of each product built into the product pages, they will need to accept that this just won't work all legacy browser version.
You should compile a list of the potential problem areas.
**Note:** You can find browser support information for technologies by looking up the different features on MDN β the site you're on! You should also consult caniuse.com, for some further useful details.
Once you've agreed on these details, you can go ahead and start developing the site.
### Development
Now on to the development of the site. You should split the different parts of the development into modules, for example you might split the different site areas up β home page, product page, shopping cart, payment workflow, etc. You might then further subdivide these β implement a common site header and footer, implement product page detail view, implement persistent shopping cart widget, etc.
There are multiple general strategies to cross-browser development, for example:
* Get all the functionality working as closely as possible in all target browsers. This may involve writing different code paths that reproduce functionality in different ways aimed at different browsers, or using a Polyfill to mimic any missing support using JavaScript or other technologies, or using a library that allows you to write a single bit of code and then does different things in the background depending on what the browser supports.
* Accept that some things aren't going to work the same on all browsers, and provide different (acceptable) solutions in browsers that don't support the full functionality. Sometimes this is inevitable due to device constraints β a cinema widescreen isn't going to give the same visual experience as a 4" mobile screen, regardless of how you program your site.
* Accept that your site just isn't going to work in some older browsers, and move on. This is OK, provided your client/userbase is OK with it.
Normally your development will involve a combination of the above three approaches. The most important thing is that you test each small part before committing it β don't leave all the testing till the end!
### Testing/discovery
After each implementation phase, you will need to test the new functionality. To start with, you should make sure there are no general issues with your code that are stopping your feature from working:
1. Test it in a couple of stable browsers on your system, like Firefox, Safari, Chrome, or Edge.
2. Do some lo-fi accessibility testing, such as trying to use your site with only the keyboard, or using your site via a screen reader to see if it is navigable.
3. Test on a mobile platform, such as Android or iOS.
At this point, fix any problems you find with your new code.
Next, you should try expanding your list of test browsers to a full list of target audience browsers and start concentrating on weeding out cross-browser issues (see the next article for more information on determining your target browsers). For example:
* Try to test the latest change on all the modern desktop browsers you can β including Firefox, Chrome, Opera, Edge, and Safari on desktop (Mac, Windows, and Linux, ideally).
* Test it in common phone and tablet browsers (e.g. iOS Safari on iPhone/iPad, Chrome and Firefox on iPhone/iPad/Android),
* Also do tests in any other browsers you have included inside your target list.
The most lo-fi option is to just do all the testing you can by yourself (pulling in teammates to help out if you are working in a team). You should try to test it on real physical devices where possible.
If you haven't got the means to test all those different browsers, operating systems, and device combinations on physical hardware, you can also make use of emulators (emulate a device using software on your desktop computer) and virtual machines (software that allows you to emulate multiple operating system/software combinations on your desktop computer). This is a very popular choice, especially in some circumstances β for example, Windows doesn't let you have multiple versions of Windows installed simultaneously on the same machine, so using multiple virtual machines is often the only option here.
Another option is user groups β using a group of people outside your development team to test your site. This could be a group of friends or family, a group of other employees, a class at a local university, or a professional user testing setup, where people are paid to test out your site and provide results.
Finally, you can get smarter with your testing using auditing or automation tools; this is a sensible choice as your projects get bigger, as doing all this testing by hand can start to take a really long time. You can set up your own testing automation system (Selenium being the popular app of choice) that could for example load your site in a number of different browsers, and:
* see if a button click causes something to happen successfully (like for example, a map displaying), displaying the results once the tests are completed
* take a screenshot of each, allowing you to see if a layout is consistent across the different browsers.
If you wish to invest money in testing, there are also commercial tools that can automate much of the setup and testing for you (such as Sauce Labs and Browser Stack). These kinds of tools usually enable a continuous integration workflow, where code changes are automatically tested before they are allowed to be submitted into your code repository.
#### Testing on prerelease browsers
It is often a good idea to test on prerelease versions of browsers; see the following links:
* Firefox Developer Edition
* Microsoft Edge Insider
* Safari Technology Preview
* Chrome Canary
* Opera Developer
This is especially prevalent if you are using very new technologies in your site, and you want to test against the latest implementations, or if you are coming across a bug in the latest release version of a browser, and you want to see if the browser's developers have fixed the bug in a newer version.
### Fixes/iteration
Once you've discovered a bug, you need to try to fix it.
The first thing to do is to narrow down where the bug occurs as much as possible. Get as much information as you can from the person reporting the bug β what platform(s), device(s), browser version(s), etc. Try it on similar configurations (e.g. the same browser version on different desktop platforms, or a few different versions of the same browser on the same platform) to see how widely the bug persists.
It might not be your fault β if a bug exists in a browser, then hopefully the vendor will rapidly fix it. It might have already been fixed β for example if a bug is present in Firefox release 49, but it is no longer there in Firefox Nightly (version 52), then they have fixed it. If it is not fixed, then you may want to file a bug (see Reporting bugs, below).
If it is your fault, you need to fix it! Finding out the cause of the bug involves the same strategy as any web development bug (again, see Debugging HTML, Debugging CSS, and What went wrong? Troubleshooting JavaScript). Once you've discovered what is causing your bug, you need to decide how to work around it in the particular browser it is causing problems in β you can't just change the problem code outright, as this may break the code in other browsers. The general approach is usually to fork the code in some way, for example use JavaScript feature detection code to detect situations in which a problem feature doesn't work, and run some different code in those cases that does work.
Once a fix has been made, you'll want to repeat your testing process to make sure your fix is working OK, and hasn't caused the site to break in other places or other browsers.
Reporting bugs
--------------
Just to reiterate on what was said above, if you discover bugs in browsers, you should report them:
* Firefox Bugzilla
* EdgeHTML issue tracker
* Safari
* Chrome
* Opera
Summary
-------
This article should have given you a high-level understanding of the most important concepts you need to know about cross browser testing. Armed with this knowledge, you are now ready to move on and start learning about Cross-browser testing strategies.
* Overview: Cross browser testing
* Next |
Setting up your own test automation environment - Learn web development | Setting up your own test automation environment
===============================================
* Previous
* Overview: Cross browser testing
In this article, we will teach you how to install your own automation environment and run your own tests using Selenium/WebDriver and a testing library such as selenium-webdriver for Node. We will also look at how to integrate your local testing environment with commercial tools like the ones discussed in the previous article.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages; an idea
of the high-level
principles of cross browser testing, and
automated testing.
|
| Objective: | To show how to set up a Selenium testing environment locally and run tests with it, and how to integrate it with tools like LambdaTest, Sauce Labs, and BrowserStack. |
Selenium
--------
Selenium is the most popular browser automation tool. There are other ways, but the best way to use Selenium is via WebDriver, a powerful API that builds on top of Selenium and makes calls to a browser to automate it, carrying out actions such as "open this web page", "move over this element on the page", "click this link", "see whether the link opens this URL", etc. This is ideal for running automated tests.
How you install and use WebDriver depends on what programming environment you want to use to write and run your tests. Most popular environments have available a package or framework that will install WebDriver and the bindings required to communicate with WebDriver using this language, for example, Java, C#, Ruby, Python, JavaScript (Node), etc. See Setting Up a Selenium-WebDriver Project for more details of Selenium setups for different languages.
Different browsers require different drivers to allow WebDriver to communicate with and control them. See Platforms Supported by Selenium for more information on where to get browser drivers from, etc.
We will cover writing and running Selenium tests using Node.js, as it is quick and easy to get started, and a more familiar environment for front end devs.
**Note:** If you want to find out how to use WebDriver with other server-side environments, also check out Platforms Supported by Selenium for some useful links.
### Setting up Selenium in Node
1. To start with, set up a new npm project, as discussed in Setting up Node and npm in the last chapter. Call it something different, like `selenium-test`.
2. Next, we need to install a framework to allow us to work with Selenium from inside Node. We are going to choose selenium's official selenium-webdriver, as the documentation seems fairly up-to-date and it is well-maintained. If you want different options, webdriver.io and nightwatch.js are also good choices. To install selenium-webdriver, run the following command, making sure you are inside your project folder:
```bash
npm install selenium-webdriver
```
**Note:** It is still a good idea to follow these steps even if you previously installed selenium-webdriver and downloaded the browser drivers. You should make sure that everything is up-to-date.
Next, you need to download the relevant drivers to allow WebDriver to control the browsers you want to test. You can find details of where to get them from on the selenium-webdriver page (see the table in the first section.) Obviously, some of the browsers are OS-specific, but we're going to stick with Firefox and Chrome, as they are available across all the main OSes.
1. Download the latest GeckoDriver (for Firefox) and ChromeDriver drivers.
2. Unpack them into somewhere fairly easy to navigate to, like the root of your home user directory.
3. Add the `chromedriver` and `geckodriver` driver's location to your system `PATH` variable. This should be an absolute path from the root of your hard disk, to the directory containing the drivers. For example, if we were using a macOS machine, our user name was bob, and we put our drivers in the root of our home folder, the path would be `/Users/bob`.
**Note:** Just to reiterate, the path you add to `PATH` needs to be the path to the directory containing the drivers, not the paths to the drivers themselves! This is a common mistake.
To set your `PATH` variable on a macOS system and on most Linux systems:
1. If you're not already using the `bash` shell (for example, on macOS systems, the default is the `zsh` shell, not `bash`), switch to the `bash` shell:
```bash
exec bash
```
2. Open your `.bash_profile` (or `.bashrc`) file (if you can't see hidden files, you'll need to display them, see Show/Hide hidden files in macOS or Show hidden folders in Ubuntu).
3. Paste the following into the bottom of your file (updating the path as it actually is on your machine):
```bash
#Add WebDriver browser drivers to PATH
export PATH=$PATH:/Users/bob
```
4. Save and close this file, then restart your Terminal/command prompt to reapply your Bash configuration.
5. Check that your new paths are in the `PATH` variable by entering the following into your terminal:
```bash
echo $PATH
```
6. You should see it printed out in the terminal.
To set your `PATH` variable on Windows, follow the instructions at How can I add a new folder to my system path?
OK, let's try a quick test to make sure everything is working.
1. Create a new file inside your project directory called `google_test.js`:
2. Give it the following contents, then save it:
```js
const { Builder, Browser, By, Key, until } = require("selenium-webdriver");
(async function example() {
const driver = await new Builder().forBrowser(Browser.FIREFOX).build();
try {
await driver.get("https://www.google.com/ncr");
await driver.findElement(By.name("q")).sendKeys("webdriver", Key.RETURN);
await driver.wait(until.titleIs("webdriver - Google Search"), 1000);
} finally {
await driver.sleep(2000); // Delay long enough to see search page!
await driver.quit();
}
})();
```
**Note:** This function is an IIFE (Immediately Invoked Function Expression).
3. In terminal, make sure you are inside your project folder, then enter the following command:
```bash
node google_test
```
You should see an instance of Firefox automatically open up! Google should automatically be loaded in a tab, "webdriver" should be entered in the search box, and the search button will be clicked. WebDriver will then wait for 1 second; the document title is then accessed, and if it is "webdriver - Google Search", we will return a message to claim the test is passed.
We then wait four seconds, after which WebDriver will then close down the Firefox instance and stop.
Testing in multiple browsers at once
------------------------------------
There is also nothing to stop you running the test on multiple browsers simultaneously. Let's try this!
1. Create another new file inside your project directory called `google_test_multiple.js`. You can feel free to change the references to some of the other browsers we added, remove them, etc., depending on what browsers you have available to test on your operating system. You'll need to make sure you have the right browser drivers set up on your system. In terms of what string to use inside the `.forBrowser()` method for other browsers, see the Browser enum reference page.
2. Give it the following contents, then save it:
```js
const { Builder, Browser, By, Key } = require("selenium-webdriver");
const driver_fx = new Builder().forBrowser(Browser.FIREFOX).build();
const driver_chr = new Builder().forBrowser(Browser.CHROME).build();
async function searchTest(driver) {
try {
await driver.get("http://www.google.com");
await driver.findElement(By.name("q")).sendKeys("webdriver", Key.RETURN);
await driver.sleep(2000).then(async () => {
await driver.getTitle().then(async (title) => {
if (title === "webdriver - Google Search") {
console.log("Test passed");
} else {
console.log("Test failed");
}
});
});
} finally {
driver.quit();
}
}
searchTest(driver_fx);
searchTest(driver_chr);
```
3. In terminal, make sure you are inside your project folder, then enter the following command:
```bash
node google_test_multiple
```
4. If you are using a Mac and do decide to test Safari, you might get an error message along the lines of "Could not create a session: You must enable the 'Allow Remote Automation' option in Safari's Develop menu to control Safari via WebDriver." If you get this, follow the given instruction and try again.
So here we've done the test as before, except that this time we've wrapped it inside a function, `searchTest()`. We've created new browser instances for multiple browsers, then passed each one to the function so the test is performed on all three browsers!
Fun huh? Let's move on, look at the basics of WebDriver syntax, in a bit more detail.
WebDriver syntax crash course
-----------------------------
Let's have a look at a few key features of the webdriver syntax. For more complete details, you should consult the selenium-webdriver JavaScript API reference for a detailed reference and the Selenium main documentation's Selenium WebDriver, which contain multiple examples to learn from written in different languages.
### Starting a new test
To start up a new test, you need to include the `selenium-webdriver` module, importing the `Builder` constructor and `Browser` interface:
```js
const { Builder, Browser } = require("selenium-webdriver");
```
You use the `Builder()` constructor to create a new instance of a driver, chaining the `forBrowser()` method to specify what browser you want to test with this builder.
The `build()` method is chained at the end to actually build the driver instance (see the Builder class reference for detailed information on these features).
```js
let driver = new Builder().forBrowser(Browser.FIREFOX).build();
```
Note that it is possible to set specific configuration options for browsers to be tested, for example you can set a specific version and OS to test in the `forBrowser()` method:
```js
let driver = new Builder().forBrowser(Browser.FIREFOX, "46", "MAC").build();
```
You could also set these options using an environment variable, for example:
```bash
SELENIUM\_BROWSER=firefox:46:MAC
```
Let's create a new test to allow us to explore this code as we talk about it. Inside your selenium test project directory, create a new file called `quick_test.js`, and add the following code to it:
```js
const { Builder, Browser } = require("selenium-webdriver");
(async function example() {
const driver = await new Builder().forBrowser(Browser.FIREFOX).build();
})();
```
### Getting the document you want to test
To load the page you actually want to test, you use the `get()` method of the driver instance you created earlier, for example:
```js
driver.get("http://www.google.com");
```
**Note:** See the WebDriver class reference for details of the features in this section and the ones below it.
You can use any URL to point to your resource, including a `file://` URL to test a local document:
```js
driver.get(
"file:///Users/chrismills/git/learning-area/tools-testing/cross-browser-testing/accessibility/fake-div-buttons.html",
);
```
or
```js
driver.get("http://localhost:8888/fake-div-buttons.html");
```
But it is better to use a remote server location so the code is more flexible β when you start using a remote server to run your tests (see later on), your code will break if you try to use local paths.
Update your `example()` function as follows:
```js
const { Builder, Browser } = require("selenium-webdriver");
(async function example() {
const driver = await new Builder().forBrowser(Browser.FIREFOX).build();
driver.get(
"https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html",
);
})();
```
### Interacting with the document
Now we've got a document to test, we need to interact with it in some way, which usually involves first selecting a specific element to test something about. You can select UI elements in many ways in WebDriver, including by ID, class, element name, etc. The actual selection is done by the `findElement()` method, which accepts as a parameter a selection method. For example, to select an element by ID:
```js
const element = driver.findElement(By.id("myElementId"));
```
One of the most useful ways to find an element by CSS β the `By.css()` method allows you to select an element using a CSS selector.
Update your `example()` function now as follows:
```js
const { Builder, Browser, By } = require("selenium-webdriver");
(async function example() {
const driver = await new Builder().forBrowser(Browser.FIREFOX).build();
driver.get(
"https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html",
);
const button = driver.findElement(By.css("button:nth-of-type(1)"));
})();
```
### Testing your element
There are many ways to interact with your web documents and elements on them. You can see useful common examples starting at Getting text values on the WebDriver docs.
If we wanted to get the text inside our button, we could do this:
```js
button.getText().then((text) => {
console.log(`Button text is '${text}'`);
});
```
Add this to the bottom of the `example()` function now as shown below:
```js
const { Builder, Browser, By } = require("selenium-webdriver");
(async function example() {
const driver = await new Builder().forBrowser(Browser.FIREFOX).build();
driver.get(
"https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html",
);
const button = driver.findElement(By.css("button:nth-of-type(1)"));
button.getText().then((text) => {
console.log(`Button text is '${text}'`);
});
})();
```
Making sure you are inside your project directory, try running the test:
```bash
node quick_test.js
```
You should see the button's text label reported inside the console.
Let's do something a bit more useful. Replace the previous code entry with this line of code, `button.click();` as shown below:
```js
const { Builder, Browser, By } = require("selenium-webdriver");
(async function example() {
const driver = await new Builder().forBrowser(Browser.FIREFOX).build();
driver.get(
"https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html",
);
const button = driver.findElement(By.css("button:nth-of-type(1)"));
button.click();
})();
```
Try running your test again; the button will be clicked, and the `alert()` popup should appear. At least we know the button is working!
You can interact with the popup too. Update the `example()` function as follows, and try testing it again:
```js
const { Builder, Browser, By, until } = require("selenium-webdriver");
(async function example() {
const driver = await new Builder().forBrowser(Browser.FIREFOX).build();
driver.get(
"https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html",
);
const button = driver.findElement(By.css("button:nth-of-type(1)"));
button.click();
await driver.wait(until.alertIsPresent());
const alert = driver.switchTo().alert();
alert.getText().then((text) => {
console.log(`Alert text is '${text}'`);
});
alert.accept();
})();
```
Next, let's try entering some text into one of the form elements. Update the `example()` function as follows and try running your test again:
```js
const { Builder, Browser, By, until } = require("selenium-webdriver");
(async function example() {
const driver = await new Builder().forBrowser(Browser.FIREFOX).build();
driver.get(
"https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html",
);
const input = driver.findElement(By.id("name"));
input.sendKeys("Filling in my form");
const button = driver.findElement(By.css("button:nth-of-type(1)"));
button.click();
await driver.wait(until.alertIsPresent());
const alert = driver.switchTo().alert();
alert.getText().then((text) => {
console.log(`Alert text is '${text}'`);
});
alert.accept();
})();
```
You can submit key presses that can't be represented by normal characters using properties of the `Key` object. For example, above we used this construct to tab out of the form input before submitting it:
```js
driver.sleep(1000).then(() => {
driver.findElement(By.name("q")).sendKeys(Key.TAB);
});
```
### Waiting for something to complete
There are times where you'll want to make WebDriver wait for something to complete before carrying on. For example if you load a new page, you'll want to wait for the page's DOM to finish loading before you try to interact with any of its elements, otherwise the test will likely fail.
In our `google_test.js` test for example, we included this block:
```js
driver.sleep(2000).then(() => {
driver.getTitle().then((title) => {
if (title === "webdriver - Google Search") {
console.log("Test passed");
} else {
console.log("Test failed");
}
});
});
```
The `sleep()` method accepts a value that specifies the time to wait in milliseconds β the method returns a promise that resolves at the end of that time, at which point the code inside the `then()` executes. In this case we get the title of the current page with the `getTitle()` method, then return a pass or fail message depending on what its value is.
We could add a `sleep()` method to our `quick_test.js` test too β try updating your `example()` function like this:
```js
const { Builder, Browser, By, until } = require("selenium-webdriver");
const driver = new Builder().forBrowser("firefox").build();
(async function example() {
try {
driver.get(
"https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html",
);
driver.sleep(2000).then(() => {
const input = driver.findElement(By.id("name"));
input.sendKeys("Filling in my form");
input.getAttribute("value").then((value) => {
if (value !== "") {
console.log("Form input editable");
}
});
});
const button = driver.findElement(By.css("button:nth-of-type(1)"));
button.click();
await driver.wait(until.alertIsPresent());
const alert = driver.switchTo().alert();
alert.getText().then((text) => {
console.log(`Alert text is '${text}'`);
});
alert.accept();
} finally {
await driver.sleep(4000); // Delay long enough to see search page!
driver.quit();
}
})();
```
WebDriver will now wait for 2 seconds before filling in the form field. We then test whether its value got filled in (i.e. is not empty) by using `getAttribute()` to retrieve it's `value` attribute value, and print a message to the console if it is not empty.
**Note:** There is also a method called `wait()`, which repeatedly tests a condition for a certain length of time, and then carries on executing the code. This also makes use of the util library, which defines common conditions to use along with `wait()`.
### Shutting down drivers after use
After you've finished running a test, you should shut down any driver instances you've opened, to make sure that you don't end up with loads of rogue browser instances open on your machine! This is done using the `quit()` method. Call this on your driver instance when you are finished with it. Add this line to the bottom of your `quick_test.js` test now:
```js
driver.quit();
```
When you run it, you should now see the test execute and the browser instance shut down again after the test is complete. This is useful for not cluttering up your computer with loads of browser instances, especially if you have so many that it is causing the computer to slow down.
Test best practices
-------------------
There has been a lot written about best practices for writing tests. You can find some good background information at Test Practices. In general, you should make sure that your tests are:
1. Using good locator strategies: When you are Interacting with the document, make sure that you use locators and page objects that are unlikely to change β if you have a testable element that you want to perform a test on, make sure that it has a stable ID, or position on the page that can be selected using a CSS selector, which isn't going to just change with the next site iteration. You want to make your tests as non-brittle as possible, i.e. they won't just break when something changes.
2. Write atomic tests: Each test should test one thing only, making it easy to keep track of what test file is testing which criterion. As an example, the `google_test.js` test we looked at above is pretty good, as it just tests a single thing β whether the title of a search results page is set correctly. We could work on giving it a better name so it is easier to work out what it does if we add more google tests. Perhaps `results_page_title_set_correctly.js` would be slightly better?
3. Write autonomous tests: Each test should work on it's own, and not depend on other tests to work.
In addition, we should mention test results/reporting β we've been reporting results in our above examples using simple `console.log()` statements, but this is all done in JavaScript, so you can use whatever test running and reporting system you want, be it Mocha, Chai, or some other tool.
1. For example, try making a local copy of our `mocha_test.js` example inside your project directory. Put it inside a subfolder called `test`. This example uses a long chain of promises to run all the steps required in our test β the promise-based methods WebDriver uses need to resolve for it to work properly.
2. Install the mocha test harness by running the following command inside your project directory:
```bash
npm install --save-dev mocha
```
3. You can now run the test (and any others you put inside your `test` directory) using the following command:
```bash
npx mocha --no-timeouts
```
4. You should include the `--no-timeouts` flag to make sure your tests don't end up failing because of Mocha's arbitrary timeout (which is 3 seconds).
**Note:** saucelabs-sample-test-frameworks contains several useful examples showing how to set up different combinations of test/assertion tools.
Running remote tests
--------------------
It turns out that running tests on remote servers isn't that much more difficult than running them locally. You just need to create your driver instance, but with a few more features specified, including the capabilities of the browser you want to test on, the address of the server, and the user credentials you need (if any) to access it.
### LambdaTest
Getting Selenium tests to run remotely on LambdaTest is very simple. The code you need should follow the pattern seen below.
Let's write an example:
1. Inside your project directory, create a new file called `lambdatest_google_test.js`
2. Give it the following contents:
```js
const { Builder, By } = require("selenium-webdriver");
// username: Username can be found at automation dashboard
const USERNAME = "{username}";
// AccessKey: AccessKey can be generated from automation dashboard or profile section
const KEY = "{accessKey}";
// gridUrl: gridUrl can be found at automation dashboard
const GRID\_HOST = "hub.lambdatest.com/wd/hub";
function searchTextOnGoogle() {
// Setup Input capabilities
const capabilities = {
platform: "windows 10",
browserName: "chrome",
version: "67.0",
resolution: "1280x800",
network: true,
visual: true,
console: true,
video: true,
name: "Test 1", // name of the test
build: "NodeJS build", // name of the build
};
// URL: https://{username}:{accessToken}@hub.lambdatest.com/wd/hub
const gridUrl = `https://${USERNAME}:${KEY}@${GRID\_HOST}`;
// setup and build selenium driver object
const driver = new Builder()
.usingServer(gridUrl)
.withCapabilities(capabilities)
.build();
// navigate to a URL, search for a text and get title of page
driver.get("https://www.google.com/ncr").then(function () {
driver
.findElement(By.name("q"))
.sendKeys("LambdaTest\n")
.then(function () {
driver.getTitle().then((title) => {
setTimeout(() => {
console.log(title);
driver.quit();
}, 5000);
});
});
});
}
searchTextOnGoogle();
```
3. Visit your LambdaTest automation dashboard, to fetch your LambdaTest's username and access key by clicking on the **key** icon on the top-right(see *Username and Access Keys*). Replace the `{username}` and `{accessKey}` placeholders in the code with your actual user name and access key values (and make sure you keep them secure).
4. Run the below command in your terminal to execute your test:
```bash
node lambdatest_google_test
```
The test will be sent to LambdaTest, and the output of your test will be reflected on your LambdaTest console.
If you wish to extract these results for reporting purpose from LambdaTest platform then you can do so by using LambdaTest restful API.
5. Now if you go to your LambdaTest Automation dashboard, you'll see your test listed; from here you'll be able to see videos, screenshots, and other such data.
![LambdaTest Automation Dashboard](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Your_own_automation_environment/automation-logs-1.jpg)
You can retrieve network, command, exception, and Selenium logs for every test within your test build. You will also find a video recording of your Selenium script execution.
**Note:** The *HELP* button on LambdaTest Automation Dashboard will provide you with an ample amount of information to help you get started with LambdaTest automation. You can also follow our documentation about running first Selenium script in Node JS.
**Note:** If you don't want to write out the capabilities objects for your tests by hand, you can generate them using the Selenium Desired Capabilities Generator.
#### Filling in test details on LambdaTest programmatically
When executing numerous automation tests, marking their status as passed or failed makes the task a lot easier.
1. Use the below command for marking a status as **passed** on LambdaTest.
```bash
driver.executeScript("lambda-status=passed");
```
2. Use the below command for marking a status as **failed** on LambdaTest.
```bash
driver.executeScript("lambda-status=failed");
```
### BrowserStack
Getting Selenium tests to run remotely on BrowserStack is easy. The code you need should follow the pattern seen below.
Let's write an example:
1. Inside your project directory, create a new file called `bstack_google_test.js`.
2. Give it the following contents:
```js
const { Builder, By, Key } = require("selenium-webdriver");
const request = require("request");
// Input capabilities
const capabilities = {
"bstack:options": {
os: "OS X",
osVersion: "Sonoma",
browserVersion: "17.0",
local: "false",
seleniumVersion: "3.14.0",
userName: "YOUR-USER-NAME",
accessKey: "YOUR-ACCESS-KEY",
},
browserName: "Safari",
};
const driver = new Builder()
.usingServer("http://hub-cloud.browserstack.com/wd/hub")
.withCapabilities(capabilities)
.build();
(async function bStackGoogleTest() {
try {
await driver.get("https://www.google.com/");
await driver.findElement(By.name("q")).sendKeys("webdriver", Key.RETURN);
await driver.sleep(2000);
const title = await driver.getTitle();
if (title === "webdriver - Google Search") {
console.log("Test passed");
} else {
console.log("Test failed");
}
} finally {
await driver.sleep(4000); // Delay long enough to see search page!
await driver.quit();
}
})();
```
3. From your BrowserStack Account - Summary, get your user name and access key (see *Username and Access Keys*). Replace the `YOUR-USER-NAME` and `YOUR-ACCESS-KEY` placeholders in the code with your actual user name and access key values (and make sure you keep them secure).
4. Run your test with the following command:
```bash
node bstack_google_test
```
The test will be sent to BrowserStack, and the test result will be returned to your console. This shows the importance of including some kind of result reporting mechanism!
5. Now if you go back to the BrowserStack automation dashboard page, you'll see your test listed:
![BrowserStack automated results](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Your_own_automation_environment/bstack_automated_results.png)
If you click on the link for your test, you'll get to a new screen where you will be able to see a video recording of the test, and multiple detailed logs of information pertaining to it.
**Note:** The *Resources* menu option on the Browserstack automation dashboard contains a wealth of useful information on using it to run automated tests. See Node JS Documentation for writing automate test scripts in Node JS for the node-specific information. Explore the docs to find out all the useful things BrowserStack can do.
**Note:** If you don't want to write out the capabilities objects for your tests by hand, you can generate them using the generators embedded in the docs. See Run your first test.
#### Filling in BrowserStack test details programmatically
You can use the BrowserStack REST API and some other capabilities to annotate your test with more details, such as whether it passed, why it passed, what project the test is part of, etc. BrowserStack doesn't know these details by default!
Let's update our `bstack_google_test.js` demo, to show how these features work:
1. Install the request module by running the following command inside your project directory:
```js
npm install request
```
2. Then, we'll need to import the node request module, so we can use it to send requests to the REST API. Add the following line at the very top of your code:
```js
const request = require("request");
```
3. Now we'll update our `capabilities` object to include a project name β add the following line before the closing curly brace, remembering to add a comma at the end of the previous line (you can vary the build and project names to organize the tests in different windows in the BrowserStack automation dashboard):
```js
'project' : 'Google test 2'
```
4. Next we need to access the `sessionId` of the current session, so we know where to send the request (the ID is included in the request URL, as you'll see later). Include the following lines just below the block that creates the `driver` object (`let driver β¦`) :
```js
let sessionId;
driver.session_.then((sessionData) => {
sessionId = sessionData.id_;
});
```
5. Finally, update the `driver.sleep(2000)` block near the bottom of the code to add REST API calls (again, replace the `YOUR-USER-NAME` and `YOUR-ACCESS-KEY` placeholders in the code with your actual user name and access key values):
```js
driver.sleep(2000).then(() => {
driver.getTitle().then((title) => {
if (title === "webdriver - Google Search") {
console.log("Test passed");
request({
uri: `https://YOUR-USER-NAME:[email protected]/automate/sessions/${sessionId}.json`,
method: "PUT",
form: {
status: "passed",
reason: "Google results showed correct title",
},
});
} else {
console.log("Test failed");
request({
uri: `https://YOUR-USER-NAME:[email protected]/automate/sessions/${sessionId}.json`,
method: "PUT",
form: {
status: "failed",
reason: "Google results showed wrong title",
},
});
}
});
});
```
These are fairly intuitive β once the test completes, we send an API call to BrowserStack to update the test with a passed or failed status, and a reason for the result.
If you now go back to your BrowserStack automation dashboard page, you should see your test session available, as before, but with the updated data attached to it:
![BrowserStack Custom Results](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Your_own_automation_environment/bstack_custom_results.png)
### Sauce Labs
Getting Selenium tests to run remotely on Sauce Labs is also very simple, and very similar to BrowserStack albeit with a few syntactic differences. The code you need should follow the pattern seen below.
Let's write an example:
1. Inside your project directory, create a new file called `sauce_google_test.js`.
2. Give it the following contents:
```js
const { Builder, By, Key } = require("selenium-webdriver");
const username = "YOUR-USER-NAME";
const accessKey = "YOUR-ACCESS-KEY";
const driver = new Builder()
.withCapabilities({
browserName: "chrome",
platform: "Windows XP",
version: "43.0",
username,
accessKey,
})
.usingServer(
`https://${username}:${accessKey}@ondemand.saucelabs.com:443/wd/hub`,
)
.build();
driver.get("http://www.google.com");
driver.findElement(By.name("q")).sendKeys("webdriver");
driver.sleep(1000).then(() => {
driver.findElement(By.name("q")).sendKeys(Key.TAB);
});
driver.findElement(By.name("btnK")).click();
driver.sleep(2000).then(() => {
driver.getTitle().then((title) => {
if (title === "webdriver - Google Search") {
console.log("Test passed");
} else {
console.log("Test failed");
}
});
});
driver.quit();
```
3. From your Sauce Labs user settings, get your user name and access key. Replace the `YOUR-USER-NAME` and `YOUR-ACCESS-KEY` placeholders in the code with your actual user name and access key values (and make sure you keep them secure).
4. Run your test with the following command:
```bash
node sauce_google_test
```
The test will be sent to Sauce Labs, and the test result will be returned to your console. This shows the importance of including some kind of result reporting mechanism!
5. Now if you go to your Sauce Labs Automated Test dashboard page, you'll see your test listed; from here you'll be able to see videos, screenshots, and other such data.
![Sauce Labs automated test](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Your_own_automation_environment/sauce_labs_automated_test.png)
**Note:** Sauce Labs' Platform Configurator is a useful tool for generating capability objects to feed to your driver instances, based on what browser/OS you want to test on.
**Note:** for more useful details on testing with Sauce Labs and Selenium, check out Getting Started with Selenium for Automated Website Testing, and Instant Selenium Node.js Tests.
#### Filling in Sauce Labs test details programmatically
You can use the Sauce Labs API to annotate your test with more details, such as whether it passed, the name of the test, etc. Sauce Labs doesn't know these details by default!
To do this, you need to:
1. Install the Node Sauce Labs wrapper using the following command (if you've not already done it for this project):
```bash
npm install saucelabs --save-dev
```
2. Require saucelabs β put this at the top of your `sauce_google_test.js` file, just below the previous variable declarations:
```js
const SauceLabs = require("saucelabs");
```
3. Create a new instance of SauceLabs, by adding the following just below that:
```js
const saucelabs = new SauceLabs({
username: "YOUR-USER-NAME",
password: "YOUR-ACCESS-KEY",
});
```
Again, replace the `YOUR-USER-NAME` and `YOUR-ACCESS-KEY` placeholders in the code with your actual user name and access key values (note that the saucelabs npm package rather confusingly uses `password`, not `accessKey`). Since you are using these twice now, you may want to create a couple of helper variables to store them in.
4. Below the block where you define the `driver` variable (just below the `build()` line), add the following block β this gets the correct driver `sessionID` that we need to write data to the job (you can see it action in the next code block):
```js
driver.getSession().then((sessionid) => {
driver.sessionID = sessionid.id_;
});
```
5. Finally, replace the `driver.sleep(2000)` block near the bottom of the code with the following:
```js
driver.sleep(2000).then(() => {
driver.getTitle().then((title) => {
let testPassed = false;
if (title === "webdriver - Google Search") {
console.log("Test passed");
testPassed = true;
} else {
console.error("Test failed");
}
saucelabs.updateJob(driver.sessionID, {
name: "Google search results page title test",
passed: testPassed,
});
});
});
```
Here we've set a `testPassed` variable to `true` or `false` depending on whether the test passed or fails, then we've used the `saucelabs.updateJob()` method to update the details.
If you now go back to your Sauce Labs Automated Test dashboard page, you should see your new job now has the updated data attached to it:
![Sauce Labs Updated Job info](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Your_own_automation_environment/sauce_labs_updated_job_info.png)
### Your own remote server
If you don't want to use a service like Sauce Labs or BrowserStack, you can always set up your own remote testing server. Let's look at how to do this.
1. The Selenium remote server requires Java to run. Download the latest JDK for your platform from the Java SE downloads page. Install it when it is downloaded.
2. Next, download the latest Selenium standalone server β this acts as a proxy between your script and the browser drivers. Choose the latest stable version number (i.e. not a beta), and from the list choose a file starting with "selenium-server-standalone". When this has downloaded, put it in a sensible place, like in your home directory. If you've not already added the location to your `PATH`, do so now (see the Setting up Selenium in Node section).
3. Run the standalone server by entering the following into a terminal on your server computer
```bash
java -jar selenium-server-standalone-3.0.0.jar
```
(update the `.jar` filename) so it matches exactly what file you've got.
4. The server will run on `http://localhost:4444/wd/hub` β try going there now to see what you get.
Now we've got the server running, let's create a demo test that will run on the remote selenium server.
1. Create a copy of your `google_test.js` file, and call it `google_test_remote.js`; put it in your project directory.
2. Update the second code block (which starts with `let driver = β¦`) like so
```js
let driver = new Builder()
.forBrowser(Browser.FIREFOX)
.usingServer("http://localhost:4444/wd/hub")
.build();
```
3. Run your test, and you should see it run as expected; this time however you will be running it on the standalone server:
```bash
node google_test_remote.js
```
So this is pretty cool. We have tested this locally, but you could set this up on just about any server along with the relevant browser drivers, and then connect your scripts to it using the URL you choose to expose it at.
Integrating Selenium with CI tools
----------------------------------
As another point, it is also possible to integrate Selenium and related tools like LambdaTest, and Sauce Labs with continuous integration (CI) tools β this is useful, as it means you can run your tests via a CI tool, and only commit new changes to your code repository if the tests pass.
It is out of scope to look at this area in detail in this article, but we'd suggest getting started with Travis CI β this is probably the easiest CI tool to get started with and has good integration with web tools like GitHub and Node.
To get started, see for example:
* Travis CI for complete beginners
* Building a Node.js project (with Travis)
* Using LambdaTest with Travis CI
* Using LambdaTest with CircleCI
* Using LambdaTest with Jenkins
* Using Sauce Labs with Travis CI
**Note:** If you wish to perform continuous testing with **codeless automation** then you can use Endtest or TestingBot.
Summary
-------
This module should have proven fun, and should have given you enough of an insight into writing and running automated tests for you to get going with writing your own automated tests.
* Previous
* Overview: Cross browser testing |
Handling common HTML and CSS problems - Learn web development | Handling common HTML and CSS problems
=====================================
* Previous
* Overview: Cross browser testing
* Next
With the scene set, we'll now look specifically at the common cross-browser problems you will come across in HTML and CSS code, and what tools can be used to prevent problems from happening, or fix problems that occur. This includes linting code, handling CSS prefixes, using browser dev tools to track down problems, using polyfills to add support into browsers, tackling responsive design problems, and more.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages; an idea
of the high level
principles of cross browser testing.
|
| Objective: |
To be able to diagnose common HTML and CSS cross browser problems, and
use appropriate tools and techniques to fix them.
|
The trouble with HTML and CSS
-----------------------------
Some of the trouble with HTML and CSS lies with the fact that both languages are fairly simple, and often developers don't take them seriously, in terms of making sure the code is well-crafted, efficient, and semantically describes the purpose of the features on the page. In the worst cases, JavaScript is used to generate the entire web page content and style, which makes your pages inaccessible, and less performant (generating DOM elements is expensive). In other cases, nascent features are not supported consistently across browsers, which can make some features and styles not work for some users. Responsive design problems are also common β a site that looks good in a desktop browser might provide a terrible experience on a mobile device, because the content is too small to read, or perhaps the site is slow because of expensive animations.
Let's go forth and look at how we can reduce cross browser errors that result from HTML/CSS.
First things first: fixing general problems
-------------------------------------------
We said in the first article of this series that a good strategy to begin with is to test in a couple of modern browsers on desktop/mobile, to make sure your code is working generally, before going on to concentrate on the cross browser issues.
In our Debugging HTML and Debugging CSS articles, we provided some really basic guidance on debugging HTML/CSS β if you are not familiar with the basics, you should definitely study these articles before carrying on.
Basically, it is a matter of checking whether your HTML and CSS code is well formed and doesn't contain any syntax errors.
**Note:** One common problem with CSS and HTML arises when different CSS rules begin to conflict with one another. This can be especially problematic when you are using third party code. For example, you might use a CSS framework and find that one of the class names it uses clashes with one you've already used for a different purpose. Or you might find that HTML generated by some kind of third party API (generating ad banners, for example) includes a class name or ID that you are already using for a different purpose. To ensure this doesn't happen, you need to research the tools you are using first and design your code around them. It is also worth "namespacing" CSS, e.g. if you have a widget, make sure it has a distinct class, and then start the selectors that select elements inside the widget with this class, so conflicts are less likely. For example `.audio-player ul a`.
### Validation
For HTML, validation involves making sure all your tags are properly closed and nested, you are using a DOCTYPE, and you are using tags for their correct purpose. A good strategy is to validate your code regularly. One service that can do this is the W3C Markup Validation Service, which allows you to point to your code, and returns a list of errors:
![The HTML validator homepage](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS/validator.png)
CSS has a similar story β you need to check that your property names are spelled correctly, property values are spelled correctly and are valid for the properties they are used on, you are not missing any curly braces, and so on. The W3C has a CSS Validator available too, for this purpose.
### Linters
Another good option to choose is a so-called Linter application, which not only points out errors, but can also flag up warnings about bad practices in your CSS, and other points besides. Linters can generally be customized to be stricter or more relaxed in their error/warning reporting.
There are many online linter applications, the best of which are probably Dirty Markup (HTML, CSS, JavaScript), and CSS Lint (CSS only). These allows you to paste your code into a window, and it will flag up any errors with crosses, which can then be hovered to get an error message informing you what the problem is. Dirty Markup also allows you to make fixes to your markup using the *Clean* button.
![Dirty Markup application displaying the message "Unexpected character in unquoted attribute" over the following incorrect HTML markup: <div id=combinators">](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS/dirty-markup.png)
However, it is not very convenient to have to copy and paste your code over to a web page to check its validity several times. What you really want is a linter that will fit into your standard workflow with the minimum of hassle.
Many code editors have linter plugins. For example, see:
* SublimeLinter for Sublime Text
* Notepad++ linter
* VSCode linters
### Browser developer tools
The developer tools built into most browsers also feature useful tools for hunting down errors, mainly for CSS.
**Note:** HTML errors don't tend to show up so easily in dev tools, as the browser will try to correct badly-formed markup automatically; the W3C validator is the best way to find HTML errors β see Validation above.
As an example, in Firefox the CSS inspector will show CSS declarations that aren't applied crossed out, with a warning triangle. Hovering the warning triangle will provide a descriptive error message:
![The developer tools cross out invalid CSS and add a hoverable warning icon](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS/css-message-devtools.png)
Other browser devtools have similar features.
Common cross browser problems
-----------------------------
Now let's move on to look at some of the most common cross browser HTML and CSS problems. The main areas we'll look at are lack of support for modern features, and layout issues.
### Browsers not supporting modern features
This is a common problem, especially when you need to support old browsers or you are using features that are implemented in some browsers but not yet in all. In general, most core HTML and CSS functionality (such as basic HTML elements, CSS basic colors and text styling) works across all the browsers you'll want to support; more problems are uncovered when you start wanting to use newer HTML, CSS, and APIs. MDN displays browser compatibility data for each feature documented; for example, see the browser support table for the `:has()` pseudo-class.
Once you've identified a list of technologies you will be using that are not universally supported, it is a good idea to research what browsers they are supported in, and what related techniques are useful. See Finding help below.
#### HTML fallback behavior
Some problems can be solved by just taking advantage of the natural way in which HTML/CSS work.
Unrecognized HTML elements are treated by the browser as anonymous inline elements (effectively inline elements with no semantic value, similar to `<span>` elements). You can still refer to them by their names, and style them with CSS, for example β you just need to make sure they are behaving as you want them to. Style them just as you would any other element, including setting the `display` property to something other than `inline` if needed.
More complex elements like HTML `<video>`, `<audio>`, `<picture>`, `<object>`, and `<canvas>` (and other features besides) have natural mechanisms for fallbacks to be added in case the resources linked to are not supported. You can add fallback content in between the opening and closing tags, and non-supporting browsers will effectively ignore the outer element and run the nested content.
For example:
```html
<video id="video" controls preload="metadata" poster="img/poster.jpg">
<source
src="video/tears-of-steel-battle-clip-medium.webm"
type="video/webm" />
<!-- Offer download -->
<p>
Your browser does not support WebM video; here is a link to
<a href="video/tears-of-steel-battle-clip-medium.mp4"
>view the video directly</a
>
</p>
</video>
```
This example includes a simple link allowing you to download the video if even the HTML video player doesn't work, so at least the user can still access the video.
Another example is form elements. When new `<input>` types were introduced for inputting specific information into forms, such as times, dates, colors, numbers, etc., if a browser didn't support the new feature, the browser used the default of `type="text"`. Input types were added, which are very useful, particularly on mobile platforms, where providing a pain-free way of entering data is very important for the user experience. Platforms provide different UI widgets depending on the input type, such as a calendar widget for entering dates. Should a browser not support an input type, the user can still enter the required data.
The following example shows date and time inputs:
```html
<form>
<div>
<label for="date">Enter a date:</label>
<input id="date" type="date" />
</div>
<div>
<label for="time">Enter a time:</label>
<input id="time" type="time" />
</div>
</form>
```
The output of this code is as follows:
**Note:** You can also see this running live as forms-test.html on GitHub (see the source code also).
If you view the example, you'll see the UI features in action as you try to input data. On devices with dynamic keyboards, type-specific keypads will be displayed. On a non-supporting browser, the inputs will just default to normal text inputs, meaning the user can still enter the correct information.
#### CSS fallback behavior
CSS is arguably better at fallbacks than HTML. If a browser encounters a declaration or rule it doesn't understand, it just skips it completely without applying it or throwing an error. This might be frustrating for you and your users if such a mistake slips through to production code, but at least it means the whole site doesn't come crashing down because of one error, and if used cleverly you can use it to your advantage.
Let's look at an example β a simple box styled with CSS, which has some styling provided by various CSS features:
![A red pill button with rounded corners, inset shadow, and drop shadow](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS/blingy-button.png)
**Note:** You can also see this example running live on GitHub as button-with-fallback.html (also see the source code).
The button has a number of declarations that style, but the two we are most interested in are as follows:
```css
button {
/\* β¦ \*/
background-color: #ff0000;
background-color: rgb(255 0 0 / 100%);
box-shadow:
inset 1px 1px 3px rgb(255 255 255 / 40%),
inset -1px -1px 3px rgb(0 0 0 / 40%);
}
button:hover {
background-color: rgb(255 0 0 / 50%);
}
button:active {
box-shadow:
inset 1px 1px 3px rgb(0 0 0 / 40%),
inset -1px -1px 3px rgb(255 255 255 / 40%);
}
```
Here we are providing an RGB `background-color` that changes opacity on hover to give the user a hint that the button is interactive, and some semi-transparent inset `box-shadow` shades to give the button a bit of texture and depth. While now fully supported, RGB colors and box shadows haven't been around forever; starting in IE9. Browsers that didn't support RGB colors would ignore the declaration meaning in old browsers the background just wouldn't show up at all so the text would be unreadable, no good at all!
![Hard to see pill button with white text on an almost white background](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS/unreadable-button.png)
To sort this out, we have added a second `background-color` declaration, which just specifies a hex color β this is supported way back in really old browsers, and acts as a fallback if the modern shiny features don't work. What happens is a browser visiting this page first applies the first `background-color` value; when it gets to the second `background-color` declaration, it will override the initial value with this value if it supports RGB colors. If not, it will just ignore the entire declaration and move on.
**Note:** The same is true for other CSS features like media queries, `@font-face` and `@supports` blocks β if they are not supported, the browser just ignores them.
#### Selector support
Of course, no CSS features will apply at all if you don't use the right selectors to select the element you want to style!
In a comma-separated list of selectors, if you just write a selector incorrectly, it may not match any element. If, however, a selector is invalid, the **entire** list of selectors is ignored, along with the entire style block. For this reason, only include a `:-moz-` prefixed pseudo class or pseudo-element in a forgiving selector list, such as `:where(::-moz-thumb)`. Don't include a `:-moz-` prefixed pseudo class or pseudo-element within a comma-separated group of selectors outside of a `:is()` or `:where()` forgiving selector list as all browsers other than Firefox will ignore the entire block. Note that both `:is()` and `:where()` can be passed as parameters in other selector lists, including `:has()` and `:not()`.
We find that it is helpful to inspect the element you are trying to style using your browser's dev tools, then look at the DOM tree breadcrumb trail that DOM inspectors tend to provide to see if your selector makes sense compared to it.
For example, in the Firefox dev tools, you get this kind of output at the bottom of the DOM inspector:
![The breadcrumb of elements is html > body > form > div.form > input#date](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS/dom-breadcrumb-trail.png)
If for example you were trying to use this selector, you'd be able to see that it wouldn't select the input element as desired:
```css
form > #date
```
(The `date` form input isn't a direct child of the `<form>`; you'd be better off using a general descendant selector instead of a child selector).
#### Handling CSS prefixes
Another set of problems comes with CSS prefixes β these are a mechanism originally used to allow browser vendors to implement their own version of a CSS (or JavaScript) feature while the technology is in an experimental state, so they can play with it and get it right without conflicting with other browser's implementations, or the final unprefixed implementations.
For example, Firefox uses `-moz-` and Chrome/Edge/Opera/Safari use `-webkit-`. Other prefixes you may encounter in old code include `-ms-`, used by Internet Explorer and early versions of Edge, and `-o`, used in the original versions of Opera.
Prefixed features were never supposed to be used in production websites β they are subject to change or removal without warning, may cause performance issues in old browser versions that require them, and have been the cause of cross-browser issues. This is particularly a problem, for example, when developers decide to use only the `-webkit-` version of a property, which implied that the site won't work in other browsers. This actually happened so much that other browser vendors implemented `-webkit-` prefixed versions of several CSS properties. While browsers still support some prefixed property names, property values, and pseudo classes, now experimental features are put behind flags so that web developers can test them during development.
If using a prefix, make sure it is needed; that the property is one of the few remaining prefixed features. You can look up what browsers require prefixes on MDN reference pages, and sites like caniuse.com. If you are unsure, you can also find out by doing some testing directly in browsers. Include the standard non-prefixed version after the prefixed style declaration; it will be ignored if not supported and used when supported.
```css
.masked {
-webkit-mask-image: url(MDN.svg);
mask-image: url(MDN.svg);
-webkit-mask-size: 50%;
mask-size: 50%;
}
```
Try this simple example:
1. Use this page, or another site that has a prominent heading or other block-level element.
2. Right/Cmd + click on the element in question and choose Inspect/Inspect element (or whatever the option is in your browser) β this should open up the dev tools in your browser, with the element highlighted in the DOM inspector.
3. Look for a feature you can use to select that element. For example, at the time of writing, this page on MDN has a logo with an ID of `mdn-docs-logo`.
4. Store a reference to this element in a variable, for example:
```js
const test = document.getElementById("mdn-docs-logo");
```
5. Now try to set a new value for the CSS property you are interested in on that element; you can do this using the style property of the element, for example try typing these into the JavaScript console:
```js
test.style.transform = "rotate(90deg)";
```
As you start to type the property name representation after the second dot (note that in JavaScript, CSS property names are written in lower camel case, not kebab-case), the JavaScript console should begin to autocomplete the names of the properties that exist in the browser and match what you've written so far. This is useful for finding out what properties are implemented in that browser.
If you do need to include modern features, test for feature support using `@supports`, which allows you to implement native feature detection tests, and nest the prefixed or new feature within the `@supports` block.
#### Responsive design problems
Responsive design is the practice of creating web layouts that change to suit different device form factors β for example, different screen widths, orientations (portrait or landscape), or resolutions. A desktop layout for example will look terrible when viewed on a mobile device, so you need to provide a suitable mobile layout using media queries, and make sure it is applied correctly using viewport. You can find a detailed account of such practices in our guide to responsive design.
Resolution is a big issue too β for example, mobile devices are less likely to need big heavy images than desktop computers, and are more likely to have slower internet connections and possibly even expensive data plans that make wasted bandwidth more of a problem. In addition, different devices can have a range of different resolutions, meaning that smaller images could appear pixelated. There are a number of techniques that allow you to work around such problems, from media queries to more complex responsive image techniques, including `<picture>` and the `<image>` element's `srcset` and `sizes` attributes.
Finding help
------------
There are many other issues you'll encounter with HTML and CSS, making knowledge of how to find answers online invaluable.
Among the best sources of support information are the Mozilla Developer Network (that's where you are now!), stackoverflow.com, and caniuse.com.
To use the Mozilla Developer Network (MDN), most people do a search engine search of the technology they are trying to find information on, plus the term "mdn", for example, "mdn HTML video". MDN contains several useful types of content:
* Reference material with browser support information for client-side web technologies, e.g. the <video> reference page.
* Other supporting reference material, e.g. the Guide to media types and formats on the web,
* Useful tutorials that solve specific problems, for example, Creating a cross-browser video player.
caniuse.com provides support information, along with a few useful external resource links. For example, see https://caniuse.com/#search=video (you just have to enter the feature you are searching for into the text box).
stackoverflow.com (SO) is a forum site where you can ask questions and have fellow developers share their solutions, look up previous posts, and help other developers. You are advised to look and see if there is an answer to your question already, before posting a new question. For example, we searched for "disabling autofocus on HTML dialog" on SO, and very quickly came up with Disable showModal auto-focusing using HTML attributes.
Aside from that, try searching your favorite search engine for an answer to your problem. It is often useful to search for specific error messages if you have them β other developers will be likely to have had the same problems as you.
Summary
-------
Now you should be familiar with the main types of cross browser HTML and CSS problems that you'll meet in web development, and how to go about fixing them.
* Previous
* Overview: Cross browser testing
* Next |
Strategies for carrying out testing - Learn web development | Strategies for carrying out testing
===================================
* Previous
* Overview: Cross browser testing
* Next
This article explains how to do cross-browser testing: how to choose which browsers and devices to test, how to actually test those browsers and devices, and how to test with user groups.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages; an idea
of the high-level
principles of cross-browser testing.
|
| Objective: |
To gain an understanding of the high-level concepts involved in
cross-browser testing.
|
Choosing which browsers and devices to test
-------------------------------------------
Since you can't test every combination of browser and device, it's enough that you ensure your site works on the most important ones. In practical applications, "important" often means "commonly used among the target audience."
You can classify browsers and devices by the amount of support you intend to give. For example:
1. A-grade: Common/modern browsers β Known to be capable. Test thoroughly and provide full support.
2. B-grade: Older/less capable browsers β known not to be capable. Test, and provide a more basic experience that gives full access to core information and services.
3. C-grade: Rare/unknown browsers β don't test, but assume they are capable. Serve the full site, which should work, at least with the fallbacks provided by our defensive coding.
In the following sections, we'll build up a support chart in this format.
**Note:** Yahoo first made this approach popular, with their Graded browser Support approach.
### Predict your audience's most commonly used browsers
This typically involves making educated guesses based on user demographics. For example, suppose your users are in North America and Western Europe:
A quick online search tells you that most people in North America and Western Europe use Windows or Mac desktops/laptops, where the main browsers are Chrome, Firefox, Safari, and Edge. You'd probably want to just test the latest versions of these browsers, as these browsers get regular updates. These should all go in the A-grade tier.
Most people in this demographic also use either iOS or Android phones, so you'd probably want to test the latest versions of iOS Safari, the last couple of versions of the old Android stock browser, and Chrome and Firefox for iOS and Android. You should ideally test these on both a phone and a tablet, to ensure responsive designs work.
Opera Mini isn't very capable of running complex JavaScript, so we should put this into grade B as well.
Thus, we've based our choice of which browsers to test on the browsers that we expect our users to use.
This gives us the following support chart so far:
1. A-grade: Chrome and Firefox for Windows/Mac, Safari for Mac, Edge for Windows, iOS Safari for iPhone/iPad, Android stock browser (last two versions) on phone/tablet, Chrome, and Firefox for Android (last two versions) on phone/tablet
2. B-grade: Opera Mini
3. C-grade: n/a
If your target audience is mostly located somewhere else, then the most common browsers and OSs may differ from the above.
**Note:** "The CEO of my company uses a Blackberry, so we'd better make sure it looks good on that" can also be something to consider.
### Browser statistics
Some websites show which browsers are popular in a given region. For example, Statcounter gives an idea of trends in North America.
### Using analytics
A much more accurate source of data, if you can get it, is an analytics app like Google Analytics, which tells you exactly what browsers people are using to browse your site. Of course, this relies on you already having a site to use it on, so it isn't good for completely new sites.
You may also consider using open-source and privacy-focused analytics platforms like Open Web Analytics and Matomo. They expect you to self-host the analytics platform.
#### Setting up Google analytics
1. First of all, you'll need a Google account. Use this account to sign into Google Analytics.
2. Choose the Google Analytics (web) option, and click the *Sign Up* button.
3. Enter your website/app details into the signup page. This is fairly intuitive to set up; the most important field to get right is the website URL. This needs to be your site/app's root URL.
4. Once you've finished filling in everything, press the *Get Tracking ID* button, then accept the terms of service that appear.
5. The next page provides you with some code snippets and other instructions. For a basic website, what you need to do is copy the *Website tracking* code block and paste it into all the different pages you want to track using Google Analytics on your site. You could place the snippets below your closing `</body>` tag, or somewhere else appropriate that keeps it from getting muddled up with your application code.
6. Upload the changes to the development server, or wherever else you need your code.
That's it! Your site should now be ready to start reporting analytics data.
#### Studying analytics data
Now you should be able to go back to the Analytics Web homepage, and start looking at the data you've collected about your site (you need to leave a little bit of time for some data to actually be collected, of course.)
By default, you should see the reporting tab, like so:
![How google analytics collects data in its main reporting dashboard](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Testing_strategies/analytics-reporting.png)
There is a huge amount of data you could look at using Google Analytics β customized reports in different categories, etc. β and we haven't got time to discuss it all.
Getting started with Analytics provides some useful guidance on reporting (and more) for beginners.
You can see what browsers and operating systems your users are using by selecting *Audience > Technology > Browser & OS* from the left-hand menu.
**Note:** When using Google analytics, you need to beware of misleading bias, e.g. "We have no Firefox Mobile users" might lead you to not bother supporting Firefox mobile. But you are not going to have any Firefox Mobile users if the site was broken on Firefox mobile in the first place.
### Other considerations
You should include accessibility as a grade A testing requirement (we'll cover exactly what you should test in our Handling common accessibility problems article).
Also, you should be aware of situation-specific needs. For example, if you are creating some kind of company intranet for delivering sales figures to managers, and all the managers have been provided with Windows phones, you will probably want to make mobile IE support a priority.
### Final support chart
So, our final support chart will end up looking like so:
1. A-grade: Chrome and Firefox for Windows/Mac, Safari for Mac, and Edge (last two versions of each), iOS Safari for iPhone/iPad, Android stock browser (last two versions) on phone/tablet, Chrome, and Firefox for Android (last two versions) on phone tablet. Accessibility passing common tests.
2. B-grade: Opera Mini.
3. C-grade: Opera, other niche modern browsers.
What are you going to test?
---------------------------
When you've got a new addition to your codebase that needs testing, before you start testing you should write out a list of testing requirements that need to pass to be accepted. These requirements can be visual or functional β both combine to make a usable website feature.
Consider the following example (see the source code, and also the example running live):
![How to prepare a testing scenario featuring the design and user requirements](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Testing_strategies/sliding-box-demo.png)
Test criteria for this feature could be written like so:
A and B grade:
* Button should be activatable by the user's primary control mechanism, whatever it is β this should include mouse, keyboard, and touch.
* Toggling the button should make the information box appear/disappear.
* The text should be readable.
* Visually impaired users using screen readers should be able to access the text.
A-grade:
* The information box should animate smoothly as it appears/disappears.
* The gradient and text shadow should appear to enhance the look of the box.
You may notice from the text in the example that it won't work in IE8 β this is a problem according to our support chart, which you'll have to work on, perhaps by using a feature detection library to implement the functionality in a different way if the browser doesn't support CSS transitions (see Implementing feature detection, later on in the course).
You might also notice that the button isn't usable using only the keyboard β this also needs to be remedied. Maybe we could use some JavaScript to implement a keyboard control for the toggle, or use some other method entirely?
These test criteria are useful, because:
* They give you a set of steps to follow when you are performing tests.
* They can be easily turned into sets of instructions for user groups to follow when carrying out tests (e.g. "try to activate the button using your mouse, and then the keyboardβ¦") β see User testing, below.
* They can also provide a basis for writing automated tests. It is easier to write such tests if you know exactly what you want to test, and what the success conditions are (see Selenium, later in the series).
Putting together a testing lab
------------------------------
One option for carrying out browser tests is to do the testing yourself. To do this, you will probably use a combination of actual physical devices, and emulated environments (using either an emulator or a virtual machine).
### Physical devices
It is generally better to have a real device running the browser you want to test β this provides the greatest accuracy in terms of behavior and overall user experience. You'll probably want something like the following, for a reasonable low-level device lab:
* A Mac, with the browsers installed that you need to test β this can include Firefox, Chrome, Opera, and Safari.
* A Windows PC, with the browsers installed that you need to test β this can include Edge (or IE), Chrome, Firefox, and Opera.
* A higher-spec Android phone and tablet with the browser installed that you need to test β this can include Chrome, Firefox, and Opera Mini for Android, as well as the original Android stock browser.
* A higher-spec iOS phone and tablet with the browsers installed that you need to test β this can include iOS Safari and Chrome, Firefox, and Opera Mini for iOS.
The following are also good options, if you can get them:
* A Linux PC available, in case you need to test bugs specific to Linux versions of browsers. Linux users commonly use Firefox, Opera, and Chrome. If you only have one machine available, you could consider creating a dual boot machine running Linux and Windows on separate partitions. Ubuntu's installer makes this quite easy to set up; see WindowsDualBoot for help with this.
* A couple of lower-spec mobile devices, so you can test the performance of features like animations on less powerful processors.
Your main work machine can also be a place to install other tools for specific purposes, such as accessibility auditing tools, screen readers, and emulators/virtual machines.
Some larger companies have device labs that stock a very large selection of different devices, enabling developers to hunt down bugs on very specific browser/device combinations. Smaller companies and individuals are generally not able to afford such a sophisticated lab, so tend to make do with smaller labs, emulators, virtual machines, and commercial testing apps.
We will cover each of the other options below.
**Note:** Some efforts have been made to create publicly accessible device labs β see Open Device Labs.
**Note:** We also need to consider accessibility β there are a number of useful tools you can install on your machine to facilitate accessibility testing, but we'll cover those in the Handling common accessibility problems article, later in the course.
### Emulators
Emulators are basically programs that run inside your computer and emulate a device or particular device conditions of some kind, allowing you to do some of your testing more conveniently than having to find a particular combination of hardware/software to test.
An emulator might be as simple as testing a device condition. For example, if you want to do some quick and dirty testing of your width/height media queries for responsive design, you could use Firefox's Responsive Design Mode. Safari has a similar mode too, which can be enabled by going to *Safari > Preferences*, and checking *Show Develop menu*, then choosing *Develop > Enter Responsive Design Mode*. Chrome also has something similar: Device mode (see Simulate Mobile Devices with Device Mode).
More often than not though, you'll have to install some kind of emulator. The most common devices/browsers you'll want to test are as follows:
* The official Android Studio IDE for developing Android apps is a bit heavy weight for just testing websites on Google Chrome or the old Stock Android browser, but it does come with a Robust emulator. If you want something a bit more lightweight, Andy is a reasonable option that runs on both Windows and Mac.
* Apple provides an app called Simulator that runs on top of the XCode development environment, and emulates iPad/iPhone/Apple Watch/Apple TV. This includes the native iOS Safari browser. This unfortunately only runs on a Mac.
You can often find simulators for other mobile device environments too, for example:
* You can emulate Opera Mini on its own if you want to test it.
* There are emulators available for Windows Mobile OSes: see Windows Phone Emulator for Windows Phone 8 and Test with the Microsoft Emulator for Windows 10 Mobile (these only run on Windows).
**Note:** Many emulators actually require the use of a virtual machine (see below); when this is the case, instructions are often provided, and/or use of the virtual machine is incorporated into the installer of the emulator.
### Virtual machines
Virtual machines are applications that run on your desktop computer and allow you to run emulations of entire operating systems, each compartmentalized in its own virtual hard drive (often represented by a single large file existing on the host machine's hard drive). There are a number of popular virtual machine apps available, such as Parallels, VMWare, and Virtual Box; we personally like the latter, because it is free.
**Note:** You need a lot of hard disk space available to run virtual machine emulations; each operating system you emulate can take up a lot of memory. You tend to choose the hard drive space you want for each install; you could get away with probably 10GB, but some sources recommend up to 50GB or more, so the operating system will run reliably. A good option provided by most virtual machine apps is to create a **dynamically allocated** hard drive that grows and shrinks as the need arises.
To use a Virtual Box, you need to:
1. Get hold of an installer disk or image (e.g. ISO file) for the operating system you want to emulate. Virtual Box is unable to provide these; most, like Windows OSes, are commercial products that can't be freely distributed.
2. Download the appropriate installer for your operating system and install it.
3. Open the app; you'll be presented with a view like the following:
![Application window left panel lists Windows operating system and Opera TV emulators. Right panel include several subpanels including general, system, display, settings, audio, network and a preview.](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Testing_strategies/virtualbox.png)
4. To create a new virtual machine, press the *New* button in the top left-hand corner.
5. Follow the instructions and fill in the following dialog boxes as appropriate. You'll:
1. Provide a name for the new virtual machine
2. Choose which operating system and version you are installing on it
3. Set how much RAM should be allocated (we'd recommend something like 2048MB, or 2GB)
4. Create a virtual hard disk (choose the default options across the three dialog boxes containing *Create a virtual hard disk now*, *VDI (virtual disk image)*, and *Dynamically allocated*).
5. Choose the file location and size for the virtual hard disk (choose a sensible name and location to keep it, and for the size specify around 50GB, or as much as you are comfortable with specifying).
Now the new virtual box should appear in the left-hand menu of the main Virtual Box UI window. At this point, you can double-click to open it β it will start to boot up the virtual machine, but it won't yet have the operating system (OS) installed. At this point you need to point the dialog box at the installer image/disk, and it will run through the steps to install the OS just like on a physical machine.
![How to install the virtual Box for a specific operating system](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Testing_strategies/virtualbox-installer.png)
**Warning:** You need to make sure you have the operating system image you want to install on the virtual machine available at this point, and install it right away. If you cancel the process at this point, it can render the virtual machine unusable, and make it so you need to delete it and create it again. This is not fatal, but it is annoying.
After the process has completed, you should have a virtual machine running an operating system inside a window on your host computer.
![Virtual box machine running on an windows operating system](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Testing_strategies/virtualbox-running.png)
You need to treat this virtual operating system installation just like you would any real installation β for example, as well as installing the browsers you want to test, install an anti-virus program to protect it from viruses.
Having multiple virtual machines is very useful, particularly for Windows IE/Edge testing β on Windows, you are not able to have multiple versions of the default browser installed side by side, so you might want to build up a library of virtual machines to handle different tests as required, e.g.:
* Windows 10 with Edge 14
* Windows 10 with Edge 13
**Note:** Another good thing about virtual machines is that the virtual disk images are fairly self-contained. If you are working on a team, you can create one virtual disk image, then copy it and pass it around. Just make sure you have the required licenses to run all those copies of Windows or whatever else you are running if it is a licensed product.
### Automation and commercial apps
As mentioned in the last chapter, you can take a lot of the pain out of browser testing by using some kind of automation system. You can set up your own testing automation system (Selenium being the popular app of choice), which does take some setup, but can be very rewarding when you get it worked out.
There are also commercial tools available such as Sauce Labs, Browser Stack and LambdaTest that do this kind of thing for you, without you having to worry about the setup, if you wish to invest some money in your testing.
Another alternative is to use no-code test automation tools such as Endtest.
We will look at how to use such tools later on in the module.
User testing
------------
Before we move on, we'll finish this article off by talking a bit about user testing β this can be a good option if you have a willing user group to test your new functionality on. Bear in mind that this can be as lo-fi or as sophisticated as you like β your user group could be a group of friends, a group of colleagues, or a group of unpaid or paid volunteers, depending on whether you have any money to spend on testing.
Generally, you'll get your users to look at the page or view containing the new functionality on some kind of a development server, so you are not putting the final site or change live until it is finished. You should get them to follow some steps and report the results they get. It is useful to provide a set of steps (sometimes called a script) so that you get more reliable results pertaining to what you were trying to test. We mentioned this in the What are you going to test section above β it is easy to turn the test criteria detailed there into steps to follow. For example, the following would work for a sighted user:
* Click the question mark button using the mouse on your desktop computer a few times. Refresh the browser window.
* Select and activate the question mark button using the keyboard on your desktop computer a few times.
* Tap the question mark button a few times on your touch screen device.
* Toggling the button should make the information box appear/disappear. Does it do this, in each of the above three cases?
* Is the text readable?
* Does the information box animate smoothly as it appears/disappears?
When running tests, it can also be a good idea to:
* Set up a separate browser profile where possible, with browser extensions and other such things disabled, and run your tests in that profile (see Use the Profile Manager to create and remove Firefox profiles and Share Chrome with others or add personas, for example).
* Use browser's private mode functionality when running tests, where available (e.g. Private Browsing in Firefox, Incognito Mode in Chrome) so things like cookies and temp files are not saved.
These steps are designed to make sure that the browser you are testing in is as "pure" as possible, i.e. there is nothing installed that could affect the results of the tests.
**Note:** Another useful lo-fi option, if you have the hardware available, is to test your sites on low-end phones/other devices β as sites get larger and feature more effects, there is a higher chance of the site slowing down, so you need to start giving performance more consideration. Trying to get your functionality working on a low end device will make it more likely that the experience will be good on higher-end devices.
**Note:** Some server-side development environments provide useful mechanisms for rolling out site changes to only a subset of users, providing a useful mechanism for getting a feature tested by a subset of users without the need for a separate development server. An example is Django Waffle Flags.
Summary
-------
After reading this article you should now have a good idea of what you can do to identify your target audience/target browser list, and then effectively carry out cross-browser testing on that list.
Next, we'll turn our attention to the actual code issues your testing might uncover, starting with HTML and CSS.
* Previous
* Overview: Cross browser testing
* Next |
Introduction to automated testing - Learn web development | Introduction to automated testing
=================================
* Previous
* Overview: Cross browser testing
* Next
Manually running tests on several browsers and devices, several times per day, can get tedious, and time-consuming. To handle this efficiently, you should become familiar with automation tools. In this article, we look at what is available, how to use task runners, and how to use the basics of commercial browser test automation apps such as LambdaTest, Sauce Labs, BrowserStack, and TestingBot.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML, CSS, and JavaScript languages;
an idea of the high level principles of cross-browser testing.
|
| Objective: | To provide an understanding of what automated testing entails, how it can make your life easier, and how to make use of some of the commercial products that make things easier. |
Automation makes things easy
----------------------------
Throughout this module we have detailed loads of different ways in which you can test your websites and apps, and explained the sort of scope your cross-browser testing efforts should have in terms of what browsers to test, accessibility considerations, and more. Sounds like a lot of work, doesn't it?
We agree β testing all the things we've looked at in previous articles manually can be a real pain. Fortunately, there are tools to help us automate some of this pain away. There are two main ways in which we can automate the tests we've been talking about in this module:
1. Use a task runner such as Grunt or Gulp, or npm scripts to run tests and clean up code during your build process. This is a great way to perform tasks like linting and minifying code, adding in CSS prefixes or transpiling nascent JavaScript features for maximum cross-browser reach, and so on.
2. Use a browser automation system like Selenium to run specific tests on installed browsers and return results, alerting you to failures in browsers as they crop up. Commercial cross-browser testing apps like Sauce Labs and BrowserStack are based on Selenium, but allow you to access their set up remotely using a simple interface, saving you the hassle of setting up your own testing system.
We will look at how to set up your own Selenium-based testing system in the next article. In this article, we'll look at how to set up a task runner, and use the basic functionality of commercial systems like the ones mentioned above.
**Note:** the above two categories are not mutually exclusive. It is possible to set up a task runner to access a service like Sauce Labs, or LambdaTest via an API, run cross browser tests, and return results. We will look at this below as well.
Using a task runner to automate testing tools
---------------------------------------------
As we said above, you can drastically speed up common tasks such as linting and minifying code by using a task runner to run everything you need to run automatically at a certain point in your build process. For example, this could be every time you save a file, or at some other point. Inside this section we'll look at how to automate task running with Node and Gulp, a beginner-friendly option.
### Setting up Node and npm
Most tools these days are based on Node.js, so you'll need to install it from nodejs.org:
1. Download the installer for your system from the above site. (If you already have Node and npm installed, jump to point 4)
2. Install it like you would any other program. Note that Node comes with Node Package Manager (npm), which allows you to easily install packages, share your own packages with others, and run useful scripts on your projects.
3. Once the install completes, test that node is installed by typing the following into the terminal, which returns the installed versions of Node and npm:
```bash
node -v
npm -v
```
4. If you've got Node/npm already installed, you should update them to their latest versions. To update Node, the most reliable way is to download and install an updated installer package from their website (see link above). To update npm, use the following command in your terminal:
```bash
npm install npm@latest -g
```
**Note:** If the above command fails with permissions errors, Fixing npm permissions should sort you out.
To start using Node/npm-based packages on your projects, you need to set up your project directories as npm projects. This is easy to do.
For example, let's first create a test directory to allow us to play without fear of breaking anything.
1. Create a new directory somewhere sensible using your file manager UI, or, on a command line, by navigating to the location you want and running the following command:
```bash
mkdir node-test
```
2. To make this directory an npm project, you just need to go inside your test directory and initialize it, with the following:
```bash
cd node-test
npm init
```
3. This second command will ask you many questions to find out the information required to set up the project; you can just select the defaults for now.
4. Once all the questions have been asked, it will ask you if the information entered is OK. Type `yes` and press Enter/Return and npm will generate a `package.json` file in your directory.
This file is basically a config file for the project. You can customize it later, but for now it'll look something like this:
```json
{
"name": "node-test",
"version": "1.0.0",
"description": "Test for npm projects",
"main": "index.js",
"scripts": {
"test": "test"
},
"author": "Chris Mills",
"license": "MIT"
}
```
With this, you are ready to move on.
### Setting up Gulp automation
Let's look at setting up Gulp and using it to automate some testing tools.
1. To begin with, create a test npm project using the procedure detailed at the bottom of the previous section.
Also, update the `package.json` file with the line: `"type": "module"` so that it'll look something like this:
```json
{
"name": "node-test",
"version": "1.0.0",
"description": "Test for npm projects",
"main": "index.js",
"scripts": {
"test": "test"
},
"author": "Chris Mills",
"license": "MIT",
"type": "module"
}
```
2. Next, you'll need some sample HTML, CSS and JavaScript content to test your system on β make copies of our sample index.html, main.js, and style.css files in a subfolder with the name `src` inside your project folder.
You can try your own test content if you like, but bear in mind that such tools won't work on internal JS/CSS β you need external files.
3. First, install gulp globally (meaning, it will be available across all projects) using the following command:
```bash
npm install --global gulp-cli
```
4. Next, run the following command inside your npm project directory root to set up gulp as a dependency of your project:
```bash
npm install --save-dev gulp
```
5. Now create a new file inside your project directory called `gulpfile.mjs`. This is the file that will run all our tasks. Inside this file, put the following:
```js
import gulp from "gulp";
export default function (cb) {
console.log("Gulp running");
cb();
}
```
This requires the `gulp` module we installed earlier, and then exports a default task that does nothing except for printing a message to the terminal β this is useful for letting us know that Gulp is working. Each gulp task is exported in the same basic format β `exports.taskName = taskFunction`. Each function takes one parameter β a callback to run when the task is completed.
6. You can run your gulp's default task with the following command β try this now:
```bash
gulp
```
### Adding some real tasks to Gulp
To add some real tasks to Gulp, we need to think about what we want to do. A reasonable set of basic functionalities to run on our project is as follows:
* html-tidy, css-lint, and js-hint to lint and report/fix common HTML/CSS/JS errors (see gulp-htmltidy, gulp-csslint, gulp-jshint).
* Autoprefixer to scan our CSS and add vendor prefixes only where needed (see gulp-autoprefixer).
* babel to transpile any new JavaScript syntax features to traditional syntax that works in older browsers (see gulp-babel).
See the links above for full instructions on the different gulp packages we are using.
To use each plugin, you need to first install it via npm, then require any dependencies at the top of the `gulpfile.js` file, then add your test(s) to the bottom of it, and finally export the name of your task to be available via gulp's command.
#### html-tidy
1. Install using the following line:
```bash
npm install --save-dev gulp-htmltidy
```
**Note:** `--save-dev` adds the package as a dependency to your project. If you look in your project's `package.json` file, you'll see an entry for it in the `devDependencies` property.
2. Add the following dependency to `gulpfile.js`:
```js
import htmltidy from "gulp-htmltidy";
```
3. Add the following test to the bottom of `gulpfile.js`:
```js
export function html() {
return gulp
.src("src/index.html")
.pipe(htmltidy())
.pipe(gulp.dest("build"));
}
```
4. Change the default export to:
```js
export default html;
```
Here we are grabbing our development `index.html` file with `gulp.src()`, which allows us to grab a source file to do something with.
We next use the `pipe()` function to pass that source to another command to do something else with. We can chain as many of these together as we want. We first run `htmltidy()` on the source, which goes through and fixes errors in our file. The second `pipe()` function writes the output HTML file to the `build` directory.
In the input version of the file, you may have noticed that we put an empty `<p>` element; htmltidy has removed this by the time the output file has been created.
#### Autoprefixer and css-lint
1. Install using the following lines:
```bash
npm install --save-dev gulp-autoprefixer
npm install --save-dev gulp-csslint
```
2. Add the following dependencies to `gulpfile.js`:
```js
import autoprefixer from "gulp-autoprefixer";
import csslint from "gulp-csslint";
```
3. Add the following test to the bottom of `gulpfile.js`:
```js
export function css() {
return gulp
.src("src/style.css")
.pipe(csslint())
.pipe(csslint.formatter("compact"))
.pipe(
autoprefixer({
cascade: false,
}),
)
.pipe(gulp.dest("build"));
}
```
4. Add the following property to `package.json`:
```json
"browserslist": [
"last 5 versions"
]
```
5. Change the default task to:
```js
export default gulp.series(html, css);
```
Here we grab our `style.css` file, run csslint on it (which outputs a list of any errors in your CSS to the terminal), then runs it through autoprefixer to add any prefixes needed to make nascent CSS features run in older browsers. At the end of the pipe chain, we output our modified prefixed CSS to the `build` directory. Note that this only works if csslint doesn't find any errors β try removing a curly brace from your CSS file and re-running gulp to see what output you get!
#### js-hint and babel
1. Install using the following lines:
```bash
npm install --save-dev gulp-babel @babel/preset-env
npm install --save-dev @babel/core
npm install jshint gulp-jshint --save-dev
```
2. Add the following dependencies to `gulpfile.js`:
```js
import babel from "gulp-babel";
import jshint from "gulp-jshint";
```
3. Add the following test to the bottom of `gulpfile.js`:
```js
export function js() {
return gulp
.src("src/main.js")
.pipe(jshint())
.pipe(jshint.reporter("default"))
.pipe(
babel({
presets: ["@babel/env"],
}),
)
.pipe(gulp.dest("build"));
}
```
4. Change the default task to:
```js
export default gulp.series(html, css, js);
```
Here we grab our `main.js` file, run `jshint` on it and output the results to the terminal using `jshint.reporter`; we then pass the file to babel, which converts it to old style syntax and outputs the result into the `build` directory. Our original code included a fat arrow function, which babel has modified into an old style function.
#### Further ideas
Once this is all set up, you can run the `gulp` command inside your project directory, and you should get an output like this:
![Output in a code editor where lines show the time tasks start or finish, the task name, and the duration of 'Finished' tasks.](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Automated_testing/gulp-output.png)
You can then try out the files output by your automated tasks by looking at them inside the `build` directory, and loading `build/index.html` in your web browser.
If you get errors, check that you've added all the dependencies and the tests as shown above; also try commenting out the HTML/CSS/JavaScript code sections and then rerunning gulp to see if you can isolate what the problem is.
Gulp comes with a `watch()` function that you can use to watch your files and run tests whenever you save a file. For example, try adding the following to the bottom of your `gulpfile.js`:
```js
export function watch() {
gulp.watch("src/\*.html", html);
gulp.watch("src/\*.css", css);
gulp.watch("src/\*.js", js);
}
```
Now try entering the `gulp watch` command into your terminal. Gulp will now watch your directory, and run the appropriate tasks whenever you save a change to an HTML, CSS, or JavaScript file.
**Note:** The `*` character is a wildcard character β here we're saying "run these tasks when any files of these types are saved. You could also use wildcards in your main tasks, for example `gulp.src('src/*.css')` would grab all your CSS files and then run piped tasks on them.
There's a lot more you can do with Gulp. The Gulp plugin directory has literally thousands of plugins to search through.
### Other task runners
There are many other task runners available. We certainly aren't trying to say that Gulp is the best solution out there, but it works for us and it is fairly accessible to beginners. You could also try using other solutions:
* Grunt works in a very similar way to Gulp, except that it relies on tasks specified in a config file, rather than using written JavaScript. See Getting started with Grunt for more details.
* You can also run tasks directly using npm scripts located inside your `package.json` file, without needing to install any kind of extra task runner system. This works on the premise that things like Gulp plugins are basically wrappers around command line tools. So, if you can work out how to run the tools using the command line, you can then run them using npm scripts. It is a bit trickier to work with, but can be rewarding for those who are strong with their command line skills. Why npm scripts? provides a good introduction with a good deal of further information.
Using commercial testing services to speed up browser testing
-------------------------------------------------------------
Now let's look at commercial third-party browser testing services and what they can do for us.
The basic premise with such applications is that the company that runs each one has a huge server farm that can run many different tests. When you use this service, you provide a URL of the page you want to test along with information, such as what browsers you want it tested in. The app then configures a new VM with the OS and browser you specified, and returns the test results in the form of screenshots, videos, log files, text, etc.
You can then step up a gear, using an API to access functionality programmatically, which means that such apps can be combined with task runners, such as your own local Selenium environments and others, to create automated tests.
**Note:** There are other commercial browser testing systems available but in this article, we'll focus on LambdaTest, Sauce Labs, and BrowserStack. We're not saying that these are necessarily the best tools available, but they are good ones that are simple for beginners to get up and running with.
### LambdaTest
#### Getting started with LambdaTest
1. Let's get started by signing up on LambdaTest for free.
2. Sign in. This should happen automatically after you verify your email address.
**Note:** Unlike other cloud-based cross browser testing service providers, LambdaTest offers a freemium account where you get lifetime access to their platform. The only difference between their premium and their freemium plan is on the amount of consumption. For automation testing through their Selenium Grid, LambdaTest offers 60 minutes per month of free testing.
#### The basics: Manual tests
Once you sign in to LambdaTest, you will be routed to the LambdaTest Dashboard. The dashboard will provide you details related to how many minutes you have consumed, how many concurrent sessions are running, your total number of tests to date, and more.
1. To start off with manual testing you need to select the **"Real Time Testing"** tab from the left navigation menu.
![LambdaTest Dashboard](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Automated_testing/lambdatest-dashboard.png)
2. As you click on the **Real Time Testing** you will be directed to a screen where you can choose the browser configuration, browser version, OS, and screen resolution with which you want to test your website.
![Real Time Testing](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Automated_testing/mark-as-bug-1.png)
3. As you click on the Start button, a loading screen will appear, providing you with a VM (Virtual Machine) based on your configurations. Once loaded, you can perform live, interactive cross-browser testing with a website.
![Mark as bug](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Automated_testing/mark-as-bug-2.png)
If you notice an issue with the UI, then you can share it with your colleagues by capturing a screenshot of your VM with the screenshot button. You can also record a video of your test session by hitting the recorder button in your test session.
4. With the in-built image editor, highlight your screenshot before you push it to your colleagues.
![Highlight a bug](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Automated_testing/mark-as-bug-3.png)
5. Using the mark as bug button you can push bugs to numerous third-party tools such as Jira, Asana, Trello, and more. That way you can log a bug directly from your test session on LambdaTest to your project management instance. Check out all the third-party LambdaTest integrations.
**Note:** All the videos and images captured inside a test session are captured inside the gallery, test logs, and issue tracker at LambdaTest.
### Sauce Labs
#### Getting started with Sauce Labs
Let's get started with a Sauce Labs Trial.
1. Create a Sauce Labs trial account.
2. Sign in. This should happen automatically after you verify your email address.
#### The basics: Manual tests
The Sauce Labs dashboard has a lot of options available on it. For now, make sure you are on the *Manual Tests* tab.
1. Click *Start a new manual session*.
2. In the next screen, type in the URL of a page you want to test (use https://mdn.github.io/learning-area/javascript/building-blocks/events/show-video-box-fixed.html, for example), then choose a browser/OS combination you want to test by using the different buttons and lists. There is a lot of choice, as you'll see!
![select sauce manual session](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Automated_testing/sauce-manual-session.png)
3. When you click Start session, a loading screen will then appear, which spins up a virtual machine running the combination you chose.
4. When loading has finished, you can then start to remotely test the website running in the chosen browser.
![Sauce test running](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Automated_testing/sauce-test-running.png)
5. From here you can see the layout as it would look in the browser you are testing, move the mouse around and try clicking buttons, etc. The top menu allows you to:
* Stop the session
* Give someone else a URL so they can observe the test remotely.
* Copy text/notes to a remote clipboard.
* Take a screenshot.
* Test in full screen mode.
Once you stop the session, you'll return to the Manual Tests tab, where you'll see an entry for each of the previous manual sessions you started. Clicking on one of these entries shows more data for the session. In here you can download any screenshots you took, watch a video of the session, view data logs, and more.
**Note:** This is already very useful, and way more convenient than having to set up all these emulators and virtual machines by yourself.
#### Advanced: The Sauce Labs API
Sauce Labs has a restful API that allows you to programmatically retrieve details of your account and existing tests, and annotate tests with further details, such as their pass/fail state which isn't recordable by manual testing alone. For example, you might want to run one of your own Selenium tests remotely using Sauce Labs to test a certain browser/OS combination, and then pass the test results back to Sauce Labs.
It has several clients available to allow you to make calls to the API using your favorite environment, be it PHP, Java, Node.js, etc.
Let's have a brief look at how we'd access the API using Node.js and node-saucelabs.
1. First, set up a new npm project to test this out, as detailed in Setting up Node and npm. Use a different directory name than before, like `sauce-test` for example.
2. Install the Node Sauce Labs wrapper using the following command:
```bash
npm install saucelabs
```
3. Create a new file inside your project root called `call_sauce.js`. give it the following contents:
```js
const SauceLabs = require("saucelabs").default;
(async () => {
const myAccount = new SauceLabs({
username: "your-sauce-username",
password: "your-sauce-api-key",
});
// Get full WebDriver URL from the client depending on region:
console.log(myAccount.webdriverEndpoint);
// Get job details of last run job
const jobs = await myAccount.listJobs("your-sauce-username", {
limit: 1,
full: true,
});
console.log(jobs);
})();
```
4. You'll need to fill in your Sauce Labs username and API key in the indicated places. These can be retrieved from your User Settings page. Fill these in now.
5. Make sure everything is saved, and run your file like so:
```bash
node call_sauce
```
#### Advanced: Automated tests
We'll cover actually running automated Sauce Lab tests in the next article.
### BrowserStack
#### Getting started with BrowserStack
Let's get started with a BrowserStack Trial.
1. Create a BrowserStack trial account.
2. Sign in. This should happen automatically after you verify your email address.
3. When you first sign in, you should be on the Live testing page; if not, click the *Live* link in the top nav menu.
4. If you are on Firefox or Chrome, you'll be prompted to Install a browser extension in a dialog titled "Enable Local Testing" β click the *Install* button to proceed. On other browsers you'll still be able to use some of the features (generally via Flash), but you might not get the full experience.
#### The basics: Manual tests
The BrowserStack Live dashboard allows you to choose what device and browser you want to test on β Platforms in the left column, devices on the right. When you mouse over or click on each device, you get a choice of browsers available on that device.
![Test Choices](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Automated_testing/browserstack-test-choices-sized.png)
Clicking on one of those browser icons will load up your choice of platform/device/browser β choose one now, and give it a try.
![Test Devices](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Automated_testing/browserstack-test-device-sized.png)
**Note:** The blue device icon next to some of the mobile device choices signals that you will be testing on a real device; choices without that icon will be run on an emulator.
You'll find that you can enter URLs into the address bar, and use the other controls like you'd expect on a real device. You can even do things like copy and paste from the device to your clipboard, scroll up and down by dragging with the mouse, or use appropriate gestures (e.g. pinch/zoom, two fingers to scroll) on the touchpads of supporting devices (e.g. MacBook). Note that not all features are available on all devices.
You'll also see a menu that allows you to control the session.
![Test Menu](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Automated_testing/browserstack-test-menu-sized.png)
The features here are as follows:
* *Switch* β Change to another platform/device/browser combination.
* Orientation (looks like a Reload icon) β Switch orientation between portrait and landscape.
* Fit to screen (looks like a full screen icon) β Fill the testing areas as much as possible with the device.
* Capture a bug (looks like a camera) β Takes a screenshot, then allows you to annotate and save it.
* Issue tracker (looks like a deck of cards) β View previously captured bugs/screenshots.
* Settings (cog icon) β Allows you to alter general settings for the session.
* Help (question mark) β Accesses help/support functions.
* *Devtools* β Allows you to use your browser's devtools to directly debug or manipulate the page being shown in the test browser. This currently only works when testing the Safari browser on iOS devices.
* *Device info* β Displays information about the testing device.
* *Features* β Shows you what features the current configuration supports, e.g. copy to clipboard, gesture support, etc.
* *Stop* β Ends the session.
**Note:** This is already very useful, and way more convenient than having to set up all these emulators and virtual machines by yourself.
#### Other basic features
If you go back to the main BrowserStack page, you'll find a couple of other useful basic features under the *More* menu option:
* *Responsive*: Enter a URL and press *Generate*, and BrowserStack will load that URL on multiple devices with different viewport sizes. Within each device you can further adjust settings like monitor size, to get a good idea of how your site's layout works across different form factors.
* *Screenshots*: Enter a URL, choose the browsers/devices/platforms you are interested in, then press *Generate screenshots* β BrowserStack will take screenshots of your site in all those different browsers then make them available to you to view and download.
#### Advanced: The BrowserStack API
BrowserStack also has a restful API that allows you to programmatically retrieve details of your account plan, sessions, builds, etc.
It has several clients available to allow you to make calls to the API using your favorite environment, be it PHP, Java, Node.js, etc.
Let's have a brief look at how we'd access the API using Node.js.
1. First, set up a new npm project to test this out, as detailed in Setting up Node and npm. Use a different directory name than before, like `bstack-test` for example.
2. Create a new file inside your project root called `call_bstack.js`. give it the following contents:
```js
const request = require("request");
const bsUser = "BROWSERSTACK\_USERNAME";
const bsKey = "BROWSERSTACK\_ACCESS\_KEY";
const baseUrl = `https://${bsUser}:${bsKey}@www.browserstack.com/automate/`;
function getPlanDetails() {
request({ uri: `${baseUrl}plan.json` }, (err, res, body) => {
console.log(JSON.parse(body));
});
/\* Response:
{
automate\_plan: <string>,
parallel\_sessions\_running: <int>,
team\_parallel\_sessions\_max\_allowed: <int>,
parallel\_sessions\_max\_allowed: <int>,
queued\_sessions: <int>,
queued\_sessions\_max\_allowed: <int>
}
\*/
}
getPlanDetails();
```
3. You'll need to fill in your BrowserStack username and API key in the indicated places. These can be retrieved from your BrowserStack Account & Profile Details, under the Authentication & Security section. Fill these in now.
4. Make sure everything is saved, and run your file like so:
```bash
node call_bstack
```
Below we've also provided some other ready-made functions you might find useful when working with the BrowserStack restful API.
```js
function getBuilds() {
request({ uri: `${baseUrl}builds.json` }, (err, res, body) => {
console.log(JSON.parse(body));
});
/\* Response:
[
{
automation\_build: {
name: <string>,
duration: <int>,
status: <string>,
hashed\_id: <string>
}
},
{
automation\_build: {
name: <string>,
duration: <int>,
status: <string>,
hashed\_id: <string>
}
},
// β¦
]
\*/
}
function getSessionsInBuild(build) {
const buildId = build.automation_build.hashed_id;
request(
{ uri: `${baseUrl}builds/${buildId}/sessions.json` },
(err, res, body) => {
console.log(JSON.parse(body));
},
);
/\* Response:
[
{
automation\_session: {
name: <string>,
duration: <int>,
os: <string>,
os\_version: <string>,
browser\_version: <string>,
browser: <string>,
device: <string>,
status: <string>,
hashed\_id: <string>,
reason: <string>,
build\_name: <string>,
project\_name: <string>,
logs: <string>,
browser\_url: <string>,
public\_url: <string>,
video\_url: <string>,
browser\_console\_logs\_url: <string>,
har\_logs\_url: <string>
}
},
{
automation\_session: {
name: <string>,
duration: <int>,
os: <string>,
os\_version: <string>,
browser\_version: <string>,
browser: <string>,
device: <string>,
status: <string>,
hashed\_id: <string>,
reason: <string>,
build\_name: <string>,
project\_name: <string>,
logs: <string>,
browser\_url: <string>,
public\_url: <string>,
video\_url: <string>,
browser\_console\_logs\_url: <string>,
har\_logs\_url: <string>
}
},
// β¦
]
\*/
}
function getSessionDetails(session) {
const sessionId = session.automation_session.hashed_id;
request({ uri: `${baseUrl}sessions/${sessionId}.json` }, (err, res, body) => {
console.log(JSON.parse(body));
});
/\* Response:
{
automation\_session: {
name: <string>,
duration: <int>,
os: <string>,
os\_version: <string>,
browser\_version: <string>,
browser: <string>,
device: <string>,
status: <string>,
hashed\_id: <string>,
reason: <string>,
build\_name: <string>,
project\_name: <string>,
logs: <string>,
browser\_url: <string>,
public\_url: <string>,
video\_url: <string>,
browser\_console\_logs\_url: <string>,
har\_logs\_url: <string>
}
}
\*/
}
```
#### Advanced: Automated tests
We'll cover actually running automated BrowserStack tests in the next article.
### TestingBot
#### Getting started with TestingBot
Let's get started with a TestingBot Trial.
1. Create a TestingBot trial account.
2. Sign in. This should happen automatically after you verify your email address.
#### The basics: Manual tests
The TestingBot dashboard lists the various options you can choose from. For now, make sure you are on the *Live Web Testing* tab.
1. Enter the URL of the page you want to test.
2. Choose the browser/OS combination you want to test by selecting the combination in the grid.
![Test Choices](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Automated_testing/screen_shot_2019-04-19_at_14.55.33.png)
3. When you click *Start Browser*, a loading screen will then appear, which spins up a virtual machine running the combination you chose.
4. When loading has finished, you can then start to remotely test the website running in the chosen browser.
5. From here you can see the layout as it would look in the browser you are testing, move the mouse around and try clicking buttons, etc. The side menu allows you to:
* Stop the session
* Change the screen resolution
* Copy text/notes to a remote clipboard
* Take, edit, and download screenshots
* Test in full screen mode.
Once you stop the session, you'll return to the *Live Web Testing* page, where you'll see an entry for each of the previous manual sessions you started. Clicking on one of these entries shows more data for the session. Here you can download any screenshots you took, watch a video of the test, and view logs for the session.
#### Advanced: The TestingBot API
TestingBot has a restful API that allows you to programmatically retrieve details of your account and existing tests, and annotate tests with further details, such as their pass/fail state which isn't recordable by manual testing alone.
TestingBot has several API clients you can use to interact with the API, including clients for NodeJS, Python, Ruby, Java and PHP.
Below is an example on how to interact with the TestingBot API with the NodeJS client testingbot-api.
1. First, set up a new npm project to test this out, as detailed in Setting up Node and npm. Use a different directory name than before, like `tb-test` for example.
2. Install the Node TestingBot wrapper using the following command:
```bash
npm install testingbot-api
```
3. Create a new file inside your project root called `tb.js`. give it the following contents:
```js
const TestingBot = require("testingbot-api");
let tb = new TestingBot({
api\_key: "your-tb-key",
api\_secret: "your-tb-secret",
});
tb.getTests(function (err, tests) {
console.log(tests);
});
```
4. You'll need to fill in your TestingBot Key and Secret in the indicated places. You can find these in the TestingBot dashboard.
5. Make sure everything is saved, and run the file:
```bash
node tb.js
```
#### Advanced: Automated tests
We'll cover actually running automated TestingBot tests in the next article.
Summary
-------
This was quite a ride, but I'm sure you can start to see the benefits of using automation tools to do some of the heavy lifting in terms of testing.
In the next article, we'll look at setting up our own local automation system using Selenium, and how to combine that with services such as Sauce Labs, BrowserStack and TestingBot.
* Previous
* Overview: Cross browser testing
* Next |
Introducing a complete toolchain - Learn web development | Introducing a complete toolchain
================================
* Previous
* Overview: Understanding client-side tools
* Next
In the final couple of articles in the series, we will solidify your tooling knowledge by walking you through the process of building up a sample case study toolchain. We'll go all the way from setting up a sensible development environment and putting transformation tools in place to actually deploying your app on Netlify. In this article, we'll introduce the case study, set up our development environment, and set up our code transformation tools.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages.
|
| Objective: |
To solidify what we've learnt so far by working through a complete
toolchain case study.
|
There really are unlimited combinations of tools and ways to use them, what you see in this article and the next is only *one* way that the featured tools can be used for a project.
**Note:** It's also worth repeating that not all of these tools need to be run on the command line. Many of today's code editors (such as VS Code) have integration support for a *lot* of tools via plugins.
Introducing our case study
--------------------------
The toolchain that we are creating in this article will be used to build and deploy a mini-site that lists data (taken from one of NASA's open APIs) concerning potentially hazardous space objects that threaten our existence on Earth! It looks like this:
![screenshot of the sample will it miss website](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Introducing_complete_toolchain/will-it-miss-screenshot.png)
You can see a live version of the site at near-misses.netlify.com.
Tools used in our toolchain
---------------------------
In this article we're going to use the following tools and features:
* JSX, a React-related set of syntax extensions that allow you to do things like defining component structures inside JavaScript. You won't need to know React to follow this tutorial, but we've included this to give you an idea of how a non-native web language could be integrated into a toolchain.
* The latest built-in JavaScript features (at the time of writing), such as `import`.
* Useful development tools such as Prettier for formatting and ESLint for linting.
* PostCSS to provide CSS nesting capabilities.
* Parcel to build and minify our code, and to write a bunch of configuration file content automatically for us.
* GitHub to manage our source code control.
* Netlify to automate our deployment process.
You may not be familiar with all the above features and tools or what they are doing, but don't panic β we'll explain each part as we move through this article.
Toolchains and their inherent complexity
----------------------------------------
As with any chain, the more links you have in your toolchain, the more complex and potentially brittle it is β for example it might be more complex to configure, and easier to break. Conversely, the fewer links, the more resilient the toolchain is likely to be.
All web projects will be different, and you need to consider what parts of your toolchain are necessary and consider each part carefully.
The smallest toolchain is one that has no links at all. You would hand code the HTML, use "vanilla JavaScript" (meaning no frameworks or intermediary languages), and manually upload it all to a server for hosting.
However, more complicated software requirements will likely benefit from the usage of tools to help simplify the development process. In addition, you should include tests before you deploy to your production server to ensure your software works as intended β this already sounds like a necessary toolchain.
For our sample project, we'll be using a toolchain specifically designed to aid our software development and support the technical choices made during the software design phase. We will however be avoiding any superfluous tooling, with the aim of keeping complexity to a minimum.
For example, we *could* have included a tool to minimize our SVG file sizes during the build. However, this project has only 4 SVG images, which were manually minified using SVGO before adding them to the project.
A couple of prerequisites
-------------------------
Besides the tools we're going to install that contribute to our toolchain, we mentioned two web services in the above list of tools. Let's take this opportunity to make sure we are set up with them before we continue. You will need to create accounts with each of GitHub and Netlify if you wish to complete the tutorial.
* As mentioned previously, GitHub is a source code repository service that adds community features such as issue tracking, following project releases, and much more. In the next chapter, we will push to a GitHub code repository, which will cause a cascade effect that (should) deploy all the software to a home on the web.
* Netlify is a hosting service for static websites (that is, websites that entirely consist of files that do not change in real-time), which lets us deploy multiple times a day and freely hosts static sites of all kinds. Netlify is what provides the "home on the web" mentioned above β free hosting for us to deploy our test app to.
Once you've signed up for GitHub (click the *Sign Up* link on the homepage if you don't already have an account, and follow the instructions), you can use your GitHub account for authentication on Netlify (click *Sign Up*, then choose *GitHub* from the "Sign up with one of the following" list), so technically you only need to create one new account.
Later on, you'll need to connect your Netlify account to your GitHub repository to deploy this project; we'll see how to do that in the next chapter.
Three stages of tools
---------------------
As we talked about in Chapter 1, the toolchain will be structured into the following phases:
* **Safety net**: Making the software development experience stable and more efficient. We might also refer to this as our development environment.
* **Transformation**: Tooling that allows us to use the latest features of a language (e.g. JavaScript) or another language entirely (e.g. JSX or TypeScript) in our development process, and then transforms our code so that the production version still runs on a wide variety of browsers, modern and older.
* **Post development**: Tooling that comes into play after you are done with the body of development to ensure that your software makes it to the web and continues to run. In this case study we'll look at adding tests to your code, and deploying your app using Netlify so it is available for all the web to see.
Let's start working on these, beginning with our development environment.
Creating a development environment
----------------------------------
This part of the toolchain is sometimes seen to be delaying the actual work, and it can be very easy to fall into a "rabbit hole" of tooling where you spend a lot of time trying to get the environment "just right".
But you can look at this in the same way as setting up your physical work environment. The chair needs to be comfortable, and set up in a good position to help with your posture. You need power, Wi-Fi, and USB ports! There might be important decorations or music that help with your mental state β these are all important to do your best work possible, and they should also only need to be set up once, if done properly.
In the same way, setting up your development environment, if done well, needs to be done only once and should be reusable in many future projects. You will probably want to review this part of the toolchain semi-regularly and consider if there are any upgrades or changes you should introduce, but this shouldn't be required too often.
Your toolchain will depend on your own needs, but for this example of a (possible) complete toolchain, the tools that will be installed up front will be:
* Library installation tools β for adding dependencies.
* Code revision control.
* Code tidying tools β for tidying JavaScript, CSS, and HTML.
* Code linting tools β for linting our code.
### Library installation tools
We'll use npm to install our tools, which you first met in Chapter 2. You should have Node.js and npm installed already, but if not, refer back to that section.
**Note:** Though it's not clear from the installation process, installing npm also installs a complementary tool called npx. We will use npx later in this chapter to help run tools that are installed as local dependencies to the project.
npm will be used to install subsequent parts of our toolchain. First of all, however, we'll install git to help with revision control.
### Code revision control
It's possible you've heard of "git" before. Git is currently the most popular source code revision control tool available to developers β revision control provides many advantages, such as a way to backup your work in a remote place, and a mechanism to work in a team on the same project without fear of overwriting each other's code.
It might be obvious to some, but it bears repeating: Git is not the same thing as GitHub. Git is the revision control tool, whereas GitHub is an online store for git repositories (plus a number of useful tools for working with them). Note that, although we're using GitHub in this chapter, there are several alternatives including GitLab and Bitbucket, and you could even host your own git repositories.
Using revision control in your projects and including it as part of the toolchain will help manage the evolution of your code. It offers a way to "commit" blocks of work as you progress, along with comments such as "X new feature implemented", or "Bug Z now fixed due to Y changes".
Revision control can also allow you to *branch* out your project code, creating a separate version, and trying out new functionality on, without those changes affecting your original code.
Finally, it can help you undo changes or revert your code back to a time "when it was working" if a mistake has been introduced somewhere and you are having trouble fixing it β something all developers need to do once in a while!
Git can be downloaded and installed via the git-scm website β download the relevant installer for your system, run it, and follow the on-screen prompts. This is all you need to do for now.
You can interact with git in a number of different ways, from using the command line to issue commands, to using a git GUI app to issue the same commands by pushing buttons, or even from directly inside your code editor, as seen in the Visual Studio Code example below:
![GitHub integration shown in VS Code](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Introducing_complete_toolchain/vscode-git.png)
Anyway, installing git is all we need to do for now. Let's move on.
### Code tidying tools
We'll be using Prettier, which we first met in Chapter 2, to tidy our code in this project. If you followed the directions in the Installing Prettier section then you might already have Prettier installed. If not, we'll get you to install Prettier as a global utility using the terminal right now.
You can check whether you've already got it installed globally using the following command:
```bash
prettier -v
```
If installed, you'll get a version number returned like 2.0.2; if not, it'll return something along the lines of "command not found". If this is the case, install it using the following command:
```bash
npm install prettier -g
```
Now that Prettier is installed, running and tidying your code can be done on the command line on an individual file basis from anywhere on your computer, for example:
```bash
prettier --write ./src/index.html
```
**Note:** In the command above, I use Prettier with the `--write` flag. Prettier understands this to mean "if there's any problem in my code format, go ahead and fix them, then save my file". This is fine for our development process, but we can also use `prettier` without the flag and it will only check the file. Checking the file (and not saving it) is useful for purposes like checks that run before a release - i.e. "don't release any code that's not been properly formatted."
It can be arduous to run the initial command against each file, and it would be useful to have a single command to do this for us (and the same will go for our linting tools).
There are many ways to solve this problem; here's just a few:
* Using npm scripts to run multiple commands from the command line in one go, such as `npm run tidy-code`.
* Using special "git hooks" to test if the code is formatted before a commit.
* Using code editor plugins to run Prettier commands each time a file is saved.
**Note:** What is a git hook? Git (not GitHub) provides a system that lets us attach pre- and post- actions to the tasks we perform with git (such as committing your code). Although git hooks can be a bit overly complicated (in this author's opinion), once they're in place they can be very powerful. If you're interested in using hooks, Husky is a greatly simplified route into using hooks.
For VS Code, one useful extension is the Prettier Code Formatter by Esben Petersen, which lets VSCode automatically format code upon saving. This means that any file in the project we are working on gets formatted nicely, including HTML, CSS, JavaScript, JSON, markdown, and more. All the editor needs is "Format On Save" enabled.
Like many tools made more recently Prettier comes with "sensible defaults". That means that you'll be able to use Prettier without having to configure anything (if you are happy with the defaults). This lets you get on with what's important: the creative work.
### Code linting tools
Linting helps with code quality but also is a way to catch potential errors earlier during development. It's a key ingredient of a good toolchain and one that many development projects will include by default.
Web development linting tools mostly exist for JavaScript (though there are a few available for HTML and CSS). This makes sense: if an unknown HTML element or invalid CSS property is used, due to the resilient nature of these two languages nothing is likely to break. JavaScript is a lot more fragile β mistakenly calling a function that doesn't exist for example causes your JavaScript to break; linting JavaScript is therefore very important, especially for larger projects.
The go-to tool for JavaScript linting is ESLint. It's an extremely powerful and versatile tool but can be tricky to configure correctly and you could easily consume many hours trying to get a configuration *just right*!
Out of the box, ESLint is going to complain that it can't find the configuration file if you run it. The configuration file supports multiple formats but for this project, we'll use `.eslintrc.json` (the leading period means the file is hidden by default).
ESLint is installed via npm, so as per discussions in Chapter 2, you have the choice to install this tool locally or globally. Using both is recommended:
* For projects you intend to share, you should always include ESLint as a local dependency so that anyone making their own copy can follow the rules you've applied to the project.
* You should also consider having ESLint installed globally so that you can quickly use it to check any file you want.
For the sake of simplicity, in this chapter, we're not going to explore all the features of ESLint, but we will put a configuration in place that works for our particular project and its requirements. However, bear in mind that if you want to refine and enforce a rule about how your code looks (or validates), it's very likely that it can be done with the right ESLint configuration.
A little later in this chapter, we'll provide the ESLint config. Once a working configuration is in place, running the command can generate some useful information. Here is an example ESLint output:
```bash
./my-project/src/index.js
2:8 error 'React' is defined but never used no-unused-vars
22:20 error 'body' is defined but never used no-unused-vars
96:19 error 'b' is defined but never used no-unused-vars
β 3 problems (3 errors, 0 warnings)
```
**Note:** We'll install ESLint in the next section; don't worry about this for now.
As with other tools, code editor integration support is typically good for ESLint, and potentially more useful as it can give us real-time feedback when issues crop up:
![ESLint error integration shown in VS Code](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Introducing_complete_toolchain/eslint-error.png)
Configuring the initial project
-------------------------------
Using these tools, a new project can be set up safely in the knowledge that many "basic" issues will be caught early on.
Using the command line, we can create the project, install the initial tooling, and create rudimentary configuration files. Again, once you've repeated this process a few times, you'll get a feel for what your default setup should be. Of course, this is *just one* possible configuration.
### Initial setup
OK, let's get the initial project setup out of the way.
1. Start off by opening your terminal, and navigating to a place that you'll be able to find and get to easily. The Desktop perhaps, or your home or documents folder?
2. Next, run the following commands to create a folder to keep your project in, and go inside the folder:
```bash
mkdir will-it-miss
cd will-it-miss
```
3. Now we will create a new directory for all of our website's development code to live in. Run the following now:
```bash
mkdir src
```
Code organization tends to be quite subjective from team to team. For this project, the source code will live in `src`.
4. Making sure you are inside the root of the `will-it-miss` directory, enter the following command to start git's source control functionality working on the directory:
```bash
git init
```
This means that you'll now be able to start storing revisions to the folder's contents, saving it to a remote repository, etc. More on this later!
5. Next, enter the following command to turn your directory into an npm package, with the advantages that we discussed in the previous article:
```bash
npm init --force
```
This will create a default `package.json` file that we can configure later on if desired. The `--force` flag causes the command to instantly create a default `package.json` file without asking you all the usual questions about what contents you want it to have (as we saw previously). We only need the defaults for now, so this saves us a bit of time.
#### Getting the project code files
At this point, we'll get hold of the project's code files (HTML, CSS, JavaScript, etc.), and put them in our `src` directory. We won't teach you how they work, as that is not the point of this chapter. They are merely here to run the tools on, to teach you about how *they* work.
1. To get hold of the code files, visit https://github.com/remy/mdn-will-it-miss and download and unzip the contents of this repo onto your local drive somewhere. You can download the entire project as a zip file by selecting *Clone or download* > *Download ZIP*.
![The GitHub will it miss repo](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Introducing_complete_toolchain/github-will-it-miss.png)
2. Now copy the contents of the project's `src` directory to your currently empty `src` directory.
We have our project files in place. That's all we need to do for now!
**Note:** To set up the project on your local machine, go to the root directory of the unzipped folder, open a terminal in that location, and execute the `npm install` command in the terminal. This will install all project dependencies that are mentioned in the `package.json` file.
#### Installing our tools
Now it's time to install the initial set of tools we'll be using in our dev environment. Run the following from inside your project's root directory:
```bash
npm install --save-dev eslint prettier babel-eslint
```
There are two important things to note about the command you just ran. The first is that we're installing the dependencies locally to the project β installing tools locally is better for a specific project. Installing locally (not including the `--global` option) allows us to easily recreate this setup on other machines.
The second important part of this install command is the `--save-dev` option. This tells the npm tool that these particular dependencies are only needed for development (npm therefore lists them in the `package.json` file under `devDependencies`, not `dependencies`). This means that if this project is installed in production mode these dependencies will not be installed. A "typical" project can have many development dependencies which are not needed to actually run the code in production. Keeping them as separate dependencies reduces any unnecessary work when deploying to production (which we will look at in the next chapter).
Before starting on the development of the actual application code, a little configuration is required for our tools to work properly. It's not a prerequisite of developing for the web, but it's useful to have the tools configured correctly if they're going to help catch errors during development β which ESLint is particularly useful for.
### Configuring our tools
In the root of the project (not in the `src` directory), we will add configuration files to configure some of our tools, namely Prettier and ESLint. This is general practice for tool configuration β you tend to find the config files in the project root, which more often than not contain configuration options expressed in a JSON structure (though our tools and many others also support YAML, which you can switch to if that's your preferred flavor of the configuration file).
1. First of all, create a file in the root of your `will-it-miss` directory called `.prettierrc.json`.
2. To configure Prettier, give `.prettierrc.json` the following contents:
```json
{
"singleQuote": true,
"trailingComma": "es5"
}
```
With these settings, when Prettier formats JavaScript for you it will use single quotes for all your quoted values, and it won't use trailing commas (a newer feature of ECMAScript that will cause errors in older browsers). You can find more about configuring Prettier in its documentation.
3. Next up, we'll configure ESLint β create another file in the root of your `will-it-miss` directory called `.eslintrc.json`, and give it the following contents:
```json
{
"env": {
"es6": true,
"browser": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"rules": {
"no-console": 0
}
}
```
The above ESLint configuration says that we want to use the "recommended" ESLint settings, that we're going to allow usage of ES6 features (such as `map()` or `Set()`), that we can use module `import` statements, and that using `console.log()` is allowed.
4. However, in the project's source files we are using React JSX syntax (for your real projects you might use React or Vue or any other framework, or no framework at all!).
Putting JSX syntax in the middle of our JavaScript is going to cause ESLint to complain pretty quickly with the current configuration, so we'll need to add a little more configuration to the ESLint settings to get it to accept JSX features.
The final config file should look like this β add in the bolded parts and save it:
```json
{
"env": {
"es6": true,
"browser": true
},
"extends": ["eslint:recommended", "plugin:react/recommended"],
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"plugins": ["react"],
"rules": {
"semi": "error",
"no-console": 0,
"react/jsx-uses-vars": "error"
}
}
```
As the configuration now uses a plugin called "React", this development dependency also needs to be installed, so that the code is there to actually run that part of the linting process.
5. Run the following terminal command in the root of your project folder:
```bash
npm install --save-dev eslint-plugin-react
```
There's a complete list of ESLint rules that you can tweak and configure to your heart's content and many companies and teams have published their own ESLint configurations, which can sometimes be useful either to get inspiration or to select one that you feel suits your own standards. A forewarning though: ESLint configuration is a very deep rabbit hole!
That's our dev environment setup complete at this point. Now, finally we're (very nearly) ready to code.
Build and transformation tools
------------------------------
For this project, as mentioned above, React is going to be used, which also means that JSX will be used in the source code. The project will also use the latest JavaScript features.
An immediate issue is that no browser has native support for JSX; it is an intermediate language that is meant to be compiled into languages the browser understands in the production code.
If the browser tries to run the source JavaScript it will immediately complain; the project needs a build tool to transform the source code to something the browser can consume without issue.
There's a number of choices for transform tools and though WebPack is a particularly popular one, this project is going to use Parcel β specifically because it requires a lot less configuration.
Parcel works on the basis that it will try to configure your development requirements on the fly. Parcel will watch the code and run a live-reloading web server during development. This also means that Parcel will install our software dependencies automatically as they are referenced in the source code, as we saw in Chapter 3.
Parcel will take care of installing any transformation tooling and configuration required without us needing to intervene (in most cases).
Then as a final bonus, Parcel can bundle and prepare the code for production deployment, taking care of minification and browser compatibility requirements.
We therefore need to install the parcel dependency in our project too β run the following command in your terminal:
```bash
npm install --save-dev parcel-bundler
```
### Using future features
The code for our project is using some new web features including features that are so new they aren't fully standardized yet. For example, instead of reaching for a tool like Sass, this particular project uses the W3C proposal for CSS nesting. CSS nesting allows us to nest CSS selectors and properties inside one another thus creating more specific selector scope. Sass was one of the first preprocessors to support nesting (if not the first) but now after many years, nesting looks like it will soon be standardized, which means that we will have it available in our browsers without needing build tools.
Until then, Parcel will do the transformation between nested CSS and natively supported CSS with the help of PostCSS, which Parcel works with out of the box. Since we've specifically decided this project should use CSS nesting (instead of Sass), the project will need to include a PostCSS plugin.
Let's use the postcss-preset-env, which lets us "use tomorrow's CSS today". To do so, follow these steps:
1. Add a single file called `.postcssrc` to the root of your project directory.
2. Add the following contents to the new file, which will automagically give us full access to the latest CSS features:
```json
{
"plugins": {
"postcss-preset-env": {
"stage": 0
}
}
}
```
That's all we need to do β remember that Parcel installs the dependencies for us by default!
Although this stage of our toolchain can be quite painful, because we've chosen a tool that purposely tries to reduce configuration and complexity, there's really nothing more we need to do during the development phase. Modules are correctly imported, nested CSS is correctly transformed to "regular CSS", and our development is unimpeded by the build process.
Now our software is ready to be written!
Running the transformation
--------------------------
To start working with our project, we'll run the Parcel server on the command line. In its default mode it will watch for changes in your code and automatically install your dependencies. This is nice because we don't have to flit back and forth between the code and the command line.
1. To start Parcel off in the background, go to your terminal and run the following command:
```bash
npx parcel src/index.html
```
You should see an output like this (once the dependencies have been installed):
```bash
Server running at http://localhost:1234
β¨ Built in 129ms.
```
Parcel also installs the dependencies that we will use in our code, including react, react-dom, react-async-hook, date-fns, and format-number. This first run will therefore be longer than a typical run of Parcel.
**Note:** if you run Parcel on this project and are faced with an error that reads `Error: ENOENT: no such file or directory`, stop the process using `Ctrl` + `C` and then try re-running it.
The server is now running on the URL that was printed (in this case localhost:1234).
2. Go to this URL in your browser and you will see the example app running!
Another clever trick Parcel has up its sleeve is that any changes to your source code will now trigger an update in the browser. To try this out:
1. Load up the file `src/components/App.js` in your favorite text editor.
2. Search for the text "near misses", and replace it with something silly like "flying pigs".
3. Save the file, then go straight back to the app running in your browser. You'll notice that the browser has automatically refreshed, and the line "<date> there will be <number> near misses" at the top of the page has been changed!
You could also try using ESLint and Prettier too β try deliberately removing a load of the whitespace from one of your files and running Prettier on it to clean it up, or introduce a syntax error into one of your JavaScript files and see what errors ESLint gives you when you try to use Parcel to build it again.
Summary
-------
We've come a long way in this chapter, building up a rather nice local development environment to create an application in.
At this point during web software development you would usually be crafting your code for the software you intend to build. Since this module is all about learning the tools around web development, not web development code itself, we won't be teaching you any actual coding β you'll find that information in the rest of MDN!
Instead, we've written an example project for you to use your tools on. We'd suggest that you work through the rest of the chapter using our example code, and then you can try changing the contents of the src directory to your own project and publishing that on Netlify instead! And indeed, deploying to Netlify will be the end goal of the next chapter!
* Previous
* Overview: Understanding client-side tools
* Next |
Package management basics - Learn web development | Package management basics
=========================
* Previous
* Overview: Understanding client-side tools
* Next
In this article, we'll look at package managers in some detail to understand how we can use them in our own projects β to install project tool dependencies, keep them up-to-date, and more.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages.
|
| Objective: |
To understand what package managers and package repositories are, why
they are needed, and the basics of how to use them.
|
A dependency in your project
----------------------------
A **dependency** is a third-party bit of software that was probably written by someone else and ideally solves a single problem for you. A web project can have any number of dependencies, ranging from none to many, and your dependencies might include sub-dependencies that you didn't explicitly install β your dependencies may have their own dependencies.
A simple example of a useful dependency that your project might need is some code to calculate relative dates as human-readable text. You could certainly code this yourself, but there's a strong chance that someone else has already solved this problem β why waste time reinventing the wheel? Moreover, a reliable third-party dependency will likely have been tested in a lot of different situations, making it more robust and cross-browser compatible than your own solution.
A project dependency can be an entire JavaScript library or framework β such as React or Vue β or a very small utility like our human-readable date library, or it can be a command line tool such as Prettier or ESLint, which we talked about in previous articles.
Without modern build tools, dependencies like this might be included in your project using a simple `<script>` element, but this might not work right out of the box and you will likely need some modern tooling to bundle your code and dependencies together when they are released on the web. A bundle is a term that's generally used to refer to a single file on your web server that contains all the JavaScript for your software β typically compressed as much as possible to help reduce the time it takes to get your software downloaded and displayed in your visitors' browser.
In addition, what happens if you find a better tool that you want to use instead of the current one, or a new version of your dependency is released that you want to update to? This is not too painful for a couple of dependencies, but in larger projects with many dependencies, this kind of thing can become really challenging to keep track of. It makes more sense to use a **package manager** such as npm, as this will guarantee that the code is added and removed cleanly, as well as a host of other advantages.
What exactly is a package manager?
----------------------------------
We've met npm already, but stepping back from npm itself, a package manager is a system that will manage your project dependencies.
The package manager will provide a method to install new dependencies (also referred to as "packages"), manage where packages are stored on your file system, and offer capabilities for you to publish your own packages.
In theory, you may not need a package manager and you could manually download and store your project dependencies, but a package manager will seamlessly handle installing and uninstalling packages. If you didn't use one, you'd have to manually handle:
* Finding all the correct package JavaScript files.
* Checking them to make sure they don't have any known vulnerabilities.
* Downloading them and putting them in the correct locations in your project.
* Writing the code to include the package(s) in your application (this tends to be done using JavaScript modules, another subject that is worth reading up on and understanding).
* Doing the same thing for all of the packages' sub-dependencies, of which there could be tens, or hundreds.
* Removing all the files again if you want to remove the packages.
In addition, package managers handle duplicate dependencies (something that becomes important and common in front-end development).
In the case of npm (and JavaScript- and Node-based package managers) you have two options for where you install your dependencies. As we touched on in the previous article, dependencies can be installed globally or locally to your project. Although there tend to be more pros for installing globally, the pros for installing locally are more important β such as code portability and version locking.
For example, if your project relied on Webpack with a certain configuration, you'd want to ensure that if you installed that project on another machine or returned to it much later on, the configuration would still work. If a different version of Webpack was installed, it may not be compatible. To mitigate this, dependencies are installed locally to a project.
To see local dependencies really shine, all you need to do is try to download and run an existing project β if it works and all the dependencies work right out of the box, then you have local dependencies to thank for the fact that the code is portable.
**Note:** npm is not the only package manager available. A successful and popular alternative package manager is Yarn. Yarn resolves the dependencies using a different algorithm that can mean a faster user experience. There are also a number of other emerging clients, such as pnpm.
Package registries
------------------
For a package manager to work, it needs to know where to install packages from, and this comes in the form of a package registry. The registry is a central place where a package is published and thus can be installed from. npm, as well as being a package manager, is also the name of the most commonly-used package registry for JavaScript packages. The npm registry exists at npmjs.com.
npm is not the only option. You could manage your own package registry β products like Microsoft Azure allow you to create proxies to the npm registry (so you can override or lock certain packages), GitHub also offers a package registry service, and there will be likely more options appearing as time goes on.
What is important is that you ensure you've chosen the best registry for you. Many projects will use npm, and we'll stick to this in our examples throughout the rest of the module.
Using the package ecosystem
---------------------------
Let's run through an example to get you started with using a package manager and registry to install a command line utility.
Parcel is another tool that developers commonly use in their development process. Parcel is clever in that it can watch the contents of our code for calls to dependencies and automatically installs any dependencies it sees that our code needs. It can also automatically build our code.
### Setting up the app as an npm package
First of all, create a new directory to store our experimental app in, somewhere sensible that you'll find again. We'll call it parcel-experiment, but you can call it whatever you like:
```bash
mkdir parcel-experiment
cd parcel-experiment
```
Next, let's initialise our app as an npm package, which creates a config file β `package.json` β that allows us to save our configuration details in case we want to recreate this environment later on, or even publish the package to the npm registry (although this is somewhat beyond the scope of this article).
Type the following command, making sure you are inside the `parcel-experiment` directory:
```bash
npm init
```
You will now be asked some questions; npm will then create a default `package.json` file based on the answers:
* `name`: A name to identify the app. Just press
`Return`
to accept the default `parcel-experiment`.
* `version`: The starting version number for the app. Again, just press
`Return`
to accept the default `1.0.0`.
* `description`: A quick description of the app's purpose. Type in something really simple, like "A simple npm package to learn about using npm", then press
`Return`
.
* `entry point`: This will be the top-level JavaScript file of the app. The default `index.js` is fine for now β press
`Return`
.
* `test command`, `git repository`, and `keywords`: press
`Return`
to leave each of these blank for now.
* `author`: The author of the project. Type your own name, and press
`Return`
.
* `license`: The license to publish the package under. Press
`Return`
to accept the default for now.
Press `Return` one more time to accept these settings.
Go into your `parcel-experiment` directory and you should now find you've got a package.json file. Open it up and it should look something like this:
```json
{
"name": "parcel-experiment",
"version": "1.0.0",
"description": "A simple npm package to learn about using npm",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Chris Mills",
"license": "ISC"
}
```
So this is the config file that defines your package. This is good for now, so let's move on.
### Installing parcel
Run the following command to install Parcel locally:
```bash
npm install parcel-bundler
```
Once that's done *All The Things*, we're now ready for some "modern client-side development" (which really means using build tools to make the developer experience a little easier). First of all however, take another look at your package.json file. You'll see that npm has added a new field, dependencies:
```json
"dependencies": {
"parcel-bundler": "^1.12.4"
}
```
This is part of the npm magic β if in the future you move your codebase to another location, on another machine, you can recreate the same setup by running the command `npm install`, and npm will look at the dependencies and install them for you.
One disadvantage is that Parcel is only available inside our `parcel-experiment` app; you won't be able to run it in a different directory. But the advantages outweigh the disadvantages.
### Setting up our example app
Anyway, on with the setup.
Parcel expects an `index.html` and an `index.js` file to work with, but otherwise, it is very unopinionated about how you structure your project. Other tools can be very different, but at least Parcel makes it easy for our initial experiment.
So now we need to add an `index.html` file to our working directory. Create `index.html` in your test directory, and give it the following contents:
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>My test page</title>
</head>
<body>
<script src="./index.js"></script>
</body>
</html>
```
Next, we need to add an `index.js` file in the same directory as `index.html`. For now, `index.js` can be empty; it just needs to exist. Create this now.
### Having fun with Parcel
Now we'll run our newly installed Parcel tool. In your terminal, run the following command:
```bash
npx parcel index.html
```
You should see something like this printed in your terminal:
```bash
Server running at http://localhost:1234
β¨ Built in 193ms.
```
**Note:** If you have trouble with the terminal returning a "command not found" type error, try running the above command with the `npx` utility, i.e. `npx parcel index.html`.
Now we're ready to benefit from the full JavaScript package ecosystem. For a start, there is now a local web server running at `http://localhost:1234`. Go there now and you'll not see anything for now, but what is cool is that when you do make changes to your app, Parcel will rebuild it and refresh the server automatically so you can instantly see the effect your update had.
Now for some page content. Let's say we want to show human-readable relative dates, such as "2 hours ago", "4 days ago" and so on. The `date-fns` package's `formatDistanceToNow()` method is useful for this (there's other packages that do the same thing too).
In the `index.js` file, add the following code and save it:
```js
import { formatDistanceToNow } from "date-fns";
const date = "1996-09-13 10:00:00";
document.body.textContent = `${formatDistanceToNow(new Date(date))} ago`;
```
Go back to `http://localhost:1234` and you'll see how long ago it is since the author turned 18.
What's particularly special about the code above is that it is using the `formatDistanceToNow()` function from the `date-fns` package, which we didn't install! Parcel has spotted that you need the module, searched for it in the `npmjs.com` package registry, and installed it locally for us, automatically. You can prove this by looking in our `package.json` file again β you'll see that the `dependencies` field has been updated for us:
```json
"dependencies": {
"date-fns": "^2.12.0",
"parcel-bundler": "^1.12.4"
}
```
Parcel has also added the files required for someone else to pick up this project and install any dependencies that we've used. If you take a look in the directory you ran the `parcel` command in, you'll find a number of new files; the most interesting of which are:
* `node_modules`: The dependency files of Parcel and date-fns.
* `dist`: The distribution directory β these are the automatically packaged, minified files Parcel has built for us, and the files it is serving at `localhost:1234`. These are the files you would upload to your web server when releasing the site online for public consumption.
So long as we know the package name, we can use it in our code and Parcel will go off, fetch, and install (actually "copy") the package into our local directory (under `node_modules`).
### Building our code for production
However, this code is not ready for production. Most build tooling systems will have a "development mode" and a "production mode". The important difference is that a lot of the helpful features you will use in development are not needed in the final site, so will be stripped out for production, e.g. "hot module replacement", "live reloading", and "uncompressed and commented source code". Though far from exhaustive, these are some of the common web development features that are very helpful at the development stage but are not very useful in production. In production, they will just bloat your site.
Now stop the previous Parcel command using `Ctrl` + `C`.
We can now prepare our bare bones example site for an imaginary deployment. Parcel provides an additional command to generate files that are suited to publication, making bundles (mentioned earlier) with the build option.
Run the following command:
```bash
npx parcel build index.html
```
You should see an output like so:
```bash
β¨ Built in 9.35s.
dist/my-project.fb76efcf.js.map 648.58 KB 64ms
dist/my-project.fb76efcf.js 195.74 KB 8.43s
dist/index.html 288 B 806ms
```
Again, the destination for our production files is the `dist` directory.
### Reducing your app's file size
However, as with all tools that "help" developers there's often a tradeoff. In this particular case, it's the file size. The JavaScript bundle my-project.fb76efcf.js is a whopping 195K β very large, given that all it does is print a line of text. Sure, there's some calculation, but we definitely don't need 195K worth of JavaScript to do this!
When you use development tooling it's worth questioning whether they're doing the right thing for you. In this case, the bundle is nearly 200K because it has in fact included the entire `date-fns` library, not just the function we're using.
If we had avoided any development tools and pointed a `<script src="">` element to a hosted version of `date-fns`, roughly the same thing would have happened β all of the library would be downloaded when our example page is loaded in a browser.
However, this is where development tooling has a chance to shine. Whilst the tooling is on our machine, we can ask the software to inspect our use of the code and only include the functions that we're actually using in production β a process known as "Tree Shaking".
This makes a lot of sense as we want to reduce file size and thus make our app load as quickly as possible. Different tooling will let you tree shake in different ways.
Although the list grows by the month, there are three main offerings for tools that generate bundles from our source code: Webpack, Rollup, and Parcel. There will be more available than this, but these are popular ones:
* The RollUp tool offers tree shaking and code splitting as its core features.
* Webpack requires some configuration (though "some" might be understating the complexity of some developers' Webpack configurations).
* In the case of Parcel (prior to Parcel version 2), there's a special flag required β `--experimental-scope-hoisting` β which will tree shake while building.
Let's stick with Parcel for now, given that we've already got it installed. Try running the following command:
```bash
npx parcel build index.html --experimental-scope-hoisting
```
You'll see that this makes a huge difference:
```bash
β¨ Built in 7.87s.
dist/my-project.86f8a5fc.js 10.34 KB 7.17s
dist/index.html 288 B 753ms
```
Now the bundle is approximately 10K. Much better.
If we were to release this project to a server, we would only release the files in the `dist` folder. Parcel has automatically handled all the filename changes for us. We recommend having a look at the source code in `dist/index.html` just so you can see what changes Parcel has performed automatically.
**Note:** At the time of writing, Parcel 2 had not been released. However when it does, these commands will all still work because the authors of Parcel have had the good sense to name the tool slightly differently. To install Parcel 1.x you have to install `parcel-bundler`, but parcel 2.x is called `parcel`.
There's a lot of tools available and the JavaScript package ecosystem is growing at an unprecedented rate, which has pros and cons. There's improvements being made all the time and the choice, for better or worse, is constantly increasing. Faced with the overwhelming choice of tooling, probably the most important lesson is to learn what the tool you select is capable of.
A rough guide to package manager clients
----------------------------------------
This tutorial installed the Parcel package using npm, but as mentioned earlier on there are some alternatives. It's worth at least knowing they exist and having some vague idea of the common commands across the tools. You've already seen some in action, but let's look at the others.
The list will grow over time, but at the time of writing, the following main package managers are available:
* npm at npmjs.org
* pnpm at pnpm.js.org
* Yarn at yarnpkg.com
npm and pnpm are similar from a command line point of view β in fact, pnpm aims to have full parity over the argument options that npm offers. It differs in that it uses a different method for downloading and storing the packages on your computer, aiming to reduce the overall disk space required.
Where npm is shown in the examples below, pnpm can be swapped in and the command will work.
Yarn is often thought to be quicker than npm in terms of the installation process (though your mileage may vary). This is important to developers because there can be a significant amount of time wasted on waiting for dependencies to install (and copy to the computer).
**Note:** The npm package manager is **not** required to install packages from the npm registry, even though they share the same name. pnpm and Yarn can consume the same `package.json` format as npm, and can install any package from the npm and other package registries.
Let's review the common actions you'll want to perform with package managers.
### Initialise a new project
```bash
npm init
yarn init
```
As shown above, this will prompt and walk you through a series of questions to describe your project (name, license, description, and so on) then generate a `package.json` for you that contains meta-information about your project and its dependencies.
### Installing dependencies
```bash
npm install date-fns
yarn add date-fns
```
We also saw `install` in action above. This would directly add the `date-fns` package to the working directory in a subdirectory called `node_modules`, along with `date-fns`'s own dependencies.
By default, this command will install the latest version of `date-fns`, but you can control this too. You can ask for `date-fns@1`, which gives you the latest 1.x version (which is 1.30.1). Or you could try `date-fns@^2.3.0`, which means the latest version after or including 2.3.0 (2.8.1 at the time of writing).
### Updating dependencies
```bash
npm update
yarn upgrade
```
This will look at the currently installed dependencies and update them, if there is an update available, within the range that's specified in the package.
The range is specified in the version of the dependency in your `package.json`, such as `date-fns@^2.0.1` β in this case, the caret character `^` means all minor and patch releases after and including 2.0.1, up to but excluding 3.0.0.
This is determined using a system called semver, which might look a bit complicated from the documentation but can be simplified by considering only the summary information and that a version is represented by `MAJOR.MINOR.PATCH`, such as 2.0.1 being major version 2 with patch version 1. An excellent way to try out semver values is to use the semver calculator.
It's important to remember that `npm update` will not upgrade the dependencies to beyond the range defined in the `package.json` β to do this you will need to install that version specifically.
### Audit for vulnerabilities
```bash
npm audit
yarn audit
```
This will check all of the dependency tree for your project and run the specific versions you're using against a vulnerability database and notify you if there are potential vulnerable packages in your project.
A good starting point for learning about vulnerabilities is the Snyk project, which covers both JavaScript packages and other programming languages.
### Checking on a dependency
```bash
npm ls date-fns
yarn why date-fns
```
This command will show what version of a dependency is installed and how it came to be included in your project. It's possible that another, top-level, package could have pulled in `date-fns`. It's equally possible (and not ideal) that you have multiple versions of a package in your project (this has been seen many times over with the lodash package, as it's so useful).
Although the package manager will do its best to deduplicate packages you may want to investigate exactly which version is installed.
### More commands
You can find out more about the individual commands for npm and yarn online. Again, pnpm commands will have parity with npm, with a handful of additions.
Making your own commands
------------------------
The package managers also support creating your own commands and executing them from the command line. For instance, we could create the following command:
```bash
npm run dev
# or yarn run dev
```
This would run a custom script for starting our project in "development mode". In fact, we regularly include this in all projects as the local development setup tends to run slightly differently to how it would run in production.
If you tried running this in your Parcel test project from earlier it would (likely) claim the "dev script is missing". This is because npm, Yarn (and the like) are looking for a property called dev in the `scripts` property of your `package.json` file.
Parcel can run a development server using the command `parcel serve filename.html`, and we'd like to use that often during our development.
So, let's create a custom shorthand command β "dev" β in our `package.json`.
If you followed the tutorial from earlier, you should have a `package.json` file inside your parcel-experiment directory. Open it up, and its `scripts` member should look like this:
```json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
},
```
Update it so that it looks like this, and save the file:
```json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "parcel serve index.html"
},
```
We've added a custom `dev` command as an npm script.
Now try running the following in your terminal, making sure you are inside the `parcel-experiment` directory:
```bash
npm run dev
```
This should start Parcel and serve up your `index.html` at the local development server, as we saw before:
```bash
Server running at http://localhost:1234
β¨ Built in 5.48s.
```
In addition, the npm (and yarn) commands are clever in that they will search for command line tools that are locally installed to the project before trying to find them through conventional methods (where your computer will normally store and allow software to be found). You can learn more about the technical intricacies of the `run` command, although in most cases your own scripts will run just fine.
You can add all kinds of things to the `scripts` property that help you do your job. We certainly have, and others have too.
Summary
-------
This brings us to the end of our tour of package managers. Our next move is to build up a sample toolchain, putting all that we've learnt so far into practice.
* Previous
* Overview: Understanding client-side tools
* Next
See also
--------
* npm scripts reference
* package.json reference |
Client-side tooling overview - Learn web development | Client-side tooling overview
============================
* Overview: Understanding client-side tools
* Next
In this article, we provide an overview of modern web tooling, what kinds of tools are available and where you'll meet them in the lifecycle of web app development, and how to find help with individual tools.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages.
|
| Objective: |
To understand what types of client-side tooling there are, and how to
find tools and get help with them.
|
Overview of modern tooling
--------------------------
Writing software for the web has become more sophisticated through the ages. Although it is still entirely reasonable to write HTML, CSS, and JavaScript "by hand" there is now a wealth of tools that developers can use to speed up the process of building a website, or app.
There are some extremely well-established tools that have become common "household names" amongst the development community, and new tools are being written and released every day to solve specific problems. You might even find yourself writing a piece of software to aid your own development process, to solve a specific problem that existing tools don't already seem to handle.
It is easy to become overwhelmed by the sheer number of tools that can be included in a single project. Equally, a single configuration file for a tool like Webpack can be hundreds of lines long, most of which are magical incantations that seem to do the job but which only a master engineer will fully understand!
From time to time, even the most experienced of web developers get stuck on a tooling problem; it is possible to waste hours attempting to get a tooling pipeline working before even touching a single line of application code. If you have found yourself struggling in the past, then don't worry β you are not alone.
In these articles, we won't answer every question about web tooling, but we will provide you with a useful starting point of understanding the fundamentals, which you can then build from. As with any complex topic, it is good to start small, and gradually work your way up to more advanced uses.
The modern tooling ecosystem
----------------------------
Today's modern developer tooling ecosystem is huge, so it's useful to have a broad idea of what main problems the tools are solving. If you jump on your favorite search engine and look for "front-end developer tools" you're going to hit a huge spectrum of results ranging from text editors, to browsers, to the type of pens you can use to take notes.
Though your choice of code editor is certainly a tooling choice, this series of articles will go beyond that, focusing on developer tools that help you produce web code more efficiently.
From a high-level perspective, you can put client-side tools into the following three broad categories of problems to solve:
* **Safety net** β Tools that are useful during your code development.
* **Transformation** β Tools that transform code in some way, e.g. turning an intermediate language into JavaScript that a browser can understand.
* **Post-development** β Tools that are useful after you have written your code, such as testing and deployment tools.
Let's look at each one of these in more detail.
### Safety net
These are tools that make the code you write a little better.
This part of the tooling should be specific to your own development environment, though it's not uncommon for companies to have some kind of policy or pre-baked configuration available to install so that all their developers are using the same processes.
This includes anything that makes your development process easier for generating stable and reliable code. Safety net tooling should also help you either prevent mistakes or correct mistakes automatically without having to build your code from scratch each time.
A few very common safety net tool types you will find being used by developers are as follows.
#### Linters
**Linters** are tools that check through your code and tell you about any errors that are present, what error types they are, and what code lines they are present on. Often linters can be configured to not only report errors, but also report any violations of a specified style guide that your team might be using (for example code that is using the wrong number of spaces for indentation, or using template literals rather than regular string literals).
ESLint is the industry standard JavaScript linter β a highly configurable tool for catching potential syntax errors and encouraging "best practices" throughout your code. Some companies and projects have also shared their ESLint configs.
You can also find linting tools for other languages, such as csslint.
Also well-worth looking at is webhint, a configurable, open-source linter for the web that surfaces best practices including approaches to accessibility, performance, cross-browser compatibility via MDN's browser compatibility data, security, testing for PWAs, and more. It is available as a Node.js command-line tool and a VS Code extension.
#### Source code control
Also known as **version control systems** (VCS), **source code control** is essential for backing work up and working in teams. A typical VCS involves having a local version of the code that you make changes to. You then "push" changes to a "master" version of the code inside a remote repository stored on a server somewhere. There is usually a way of controlling and coordinating what changes are made to the "master" copy of the code, and when, so a team of developers doesn't end up overwriting each other's work all the time.
Git is the source code control system that most people use these days. It is primarily accessed via the command line but can be accessed via friendly user interfaces. With your code in a git repository, you can push it to your own server instance, or use a hosted source control website such as GitHub, GitLab, or BitBucket.
We'll be using GitHub in this module. You can find more information about it at Git and GitHub.
#### Code formatters
Code formatters are somewhat related to linters, except that rather than point out errors in your code, they usually tend to make sure your code is formatted correctly, according to your style rules, ideally automatically fixing errors that they find.
Prettier is a very popular example of a code formatter, which we'll make use of later on in the module.
#### Bundlers/packagers
These are tools that get your code ready for production, for example by "tree-shaking" to make sure only the parts of your code libraries that you are actually using are put into your final production code, or "minifying" to remove all the whitespace in your production code, making it as small as possible before it is uploaded to a server.
Parcel is a particularly clever tool that fits into this category β it can do the above tasks, but also helps to package assets like HTML, CSS, and image files into convenient bundles that you can then go on to deploy, and also adds dependencies for you automatically whenever you try to use them. It can even handle some code transformation duties for you.
Webpack is another very popular packaging tool that does similar things.
### Transformation
This stage of your web app lifecycle typically allows you to code in either "future code" (such as the latest CSS or JavaScript features that might not have native support in browsers yet) or code using another language entirely, such as TypeScript. Transformation tools will then generate browser-compatible code for you, to be used in production.
Generally, web development is thought of as three languages: HTML, CSS, and JavaScript, and there are transformation tools for all of these languages. Transformation offers two main benefits (amongst others):
1. The ability to write code using the latest language features and have that transformed into code that works on everyday devices. For example, you might want to write JavaScript using cutting-edge new language features, but still have your final production code work on older browsers that don't support those features. Good examples here include:
* Babel: A JavaScript compiler that allows developers to write their code using cutting-edge JavaScript, which Babel then takes and converts into old-fashioned JavaScript that more browsers can understand. Developers can also write and publish plugins for Babel.
* PostCSS: Does the same kind of thing as Babel, but for cutting-edge CSS features. If there isn't an equivalent way to do something using older CSS features, PostCSS will install a JavaScript polyfill to emulate the CSS effect you want.
2. The option to write your code in an entirely different language and have it transformed into a web-compatible language. For example:
* Sass/SCSS: This CSS extension allows you to use variables, nested rules, mixins, functions, and many other features, some of which are available in native CSS (such as variables), and some of which aren't.
* TypeScript: TypeScript is a superset of JavaScript that offers a bunch of additional features. The TypeScript compiler converts TypeScript code to JavaScript when building for production.
* Frameworks such as React, Ember, and Vue: Frameworks provide a lot of functionality for free and allow you to use it via custom syntax built on top of vanilla JavaScript. In the background, the framework's JavaScript code works hard to interpret this custom syntax and render it as a final web app.
### Post development
Post-development tooling ensures that your software makes it to the web and continues to run. This includes the deployment processes, testing frameworks, auditing tools, and more.
This stage of the development process is one that you want the least amount of active interaction with so that once it is configured, it runs mostly automatically, only popping up to say hello if something has gone wrong.
#### Testing tools
These generally take the form of a tool that will automatically run tests against your code to make sure it is correct before you go any further (for example, when you attempt to push changes to a GitHub repo). This can include linting, but also more sophisticated procedures like unit tests, where you run part of your code, making sure they behave as they should.
* Frameworks for writing tests include Jest, Mocha, and Jasmine.
* Automated test running and notification systems include Travis CI, Jenkins, Circle CI, and others.
#### Deployment tools
Deployment systems allow you to get your website published, are available for both static and dynamic sites, and commonly tend to work alongside testing systems. For example, a typical toolchain will wait for you to push changes to a remote repo, run some tests to see if the changes are OK, and then if the tests pass, automatically deploy your app to a production site.
Netlify is one of the most popular deployment tools right now, but others include Vercel and GitHub Pages.
#### Others
There are several other tool types available to use in the post-development stage, including Code Climate for gathering code quality metrics, the webhint browser extension for performing runtime analysis of cross-browser compatibility and other checks, GitHub bots for providing more powerful GitHub functionality, Updown for providing app uptime monitoring, and so many more!
### Some thoughts about tooling types
There's certainly an order in which the different tooling types apply in the development lifecycle, but rest assured that you don't *have* to have all of these in place to release a website. In fact, you don't need any of these. However, including some of these tools in your process will improve your own development experience and likely improve the overall quality of your code.
It often takes some time for new developer tools to settle down in their complexity. One of the best-known tools, Webpack, has a reputation for being overly complicated to work with, but in the latest major release, there was a huge push to simplify common usage so the configuration required is reduced down to an absolute minimum.
There's definitely no silver bullet that will guarantee success with tools, but as your experience increases you'll find workflows that work *for you* or for your team and their projects. Once all the kinks in the process are flattened out, your toolchain should be something you can forget about and it *should* just work.
How to choose and get help with a particular tool
-------------------------------------------------
Most tools tend to get written and released in isolation, so although there's almost certainly help available it's never in the same place or format. It can therefore be hard to find help with using a tool, or even to choose what tool to use. The knowledge about which are the best tools to use is a bit tribal, meaning that if you aren't already in the web community, it is hard to find out exactly which ones to go for! This is one reason we wrote this series of articles, to hopefully provide that first step that is hard to find otherwise.
You'll probably need a combination of the following things:
* Experienced teachers, mentors, fellow students, or colleagues that have some experience, have solved such problems before, and can give advice.
* A useful specific place to search. General web searches for front-end developer tools are generally useless unless you already know the name of the tool you are searching for.
+ If you are using the npm package manager to manage your dependencies for example, it is a good idea to go to the npm homepage and search for the type of tool you are looking for, for example try searching for "date" if you want a date formatting utility, or "formatter" if you are searching for a general code formatter. Pay attention to the popularity, quality, and maintenance scores, and how recently the package was last updated. Also click through to the tool pages to find out how many monthly downloads a package has, and whether it has good documentation that you can use to figure out whether it does what you need it to do. Based on these criteria, the date-fns library looks like a good date formatting tool to use. You'll see this tool in action and learn more about package managers in general in Chapter 3 of this module.
+ If you are looking for a plugin to integrate tool functionality into your code editor, look at the code editor's plugins/extensions page β see VSCode extensions, for example. Have a look at the featured extensions on the front page, and again, try searching for the kind of extension you want (or the tool name, for example search for "ESLint" on the VSCode extensions page). When you get results, have a look at information such as how many stars or downloads the extension has, as an indicator of its quality.
* Development-related forums to ask questions on about what tools to use, for example MDN Learn Discourse, or Stack Overflow.
When you've chosen a tool to use, the first port of call should be the tool project homepage. This could be a full-blown website or it might be a single readme document in a code repository. The date-fns docs for example are pretty good, complete, and easy to follow. Some documentation however can be rather technical and academic and not a good fit for your learning needs.
Instead, you might want to find some dedicated tutorials on getting started with particular types of tools. A great starting place is to search websites like CSS Tricks, Dev, freeCodeCamp, and Smashing Magazine, as they're tailored to the web development industry.
Again, you'll probably go through several different tools as you search for the right ones for you, trying them out to see if they make sense, are well-supported, and do what you want them to do. This is fine β it is all good for learning, and the road will get smoother as you get more experience.
Summary
-------
That rounds off our gentle introduction to the topic of client-side web tooling, from a high level. Next up we provide you with a crash course on the command line, which is where a lot of tooling is invoked from. We'll take a look at what the command line can do and then try installing and using our first tool.
* Overview: Understanding client-side tools
* Next |
Deploying our app - Learn web development | Deploying our app
=================
* Previous
* Overview: Understanding client-side tools
In the final article in our series, we take the example toolchain we built up in the previous article and add to it so that we can deploy our sample app. We push the code to GitHub, deploy it using Netlify, and even show you how to add a simple test into the process.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and
JavaScript languages.
|
| Objective: |
To finish working through our complete toolchain case study, focusing on
deploying the app.
|
Post development
----------------
There's potentially a large range of problems to be solved in this section of the project's lifecycle. As such, it's important to create a toolchain that handles these problems in a way that requires as little manual intervention as possible.
Here's just a few things to consider for this particular project:
* Generating a production build: Ensuring files are minimized, chunked, have tree-shaking applied, and that versions are "cache busted".
* Running tests: These can range from "is this code formatted properly?" to "does this thing do what I expect?", and ensuring failing tests prevent deployment.
* Actually deploying the updated code to a live URL: Or potentially a staging URL so it can be reviewed first.
**Note:** Cache busting is a new term that we haven't met before in the module. This is the strategy of breaking a browser's own caching mechanism, which forces the browser to download a new copy of your code. Parcel (and indeed many other tools) will generate filenames that are unique to each new build. This unique filename "busts" your browser's cache, thereby making sure the browser downloads the fresh code each time an update is made to the deployed code.
The above tasks also break down into further tasks; note that most web development teams will have their own terms and processes for at least some part of the post-development phase.
For this project, we're going to use Netlify's wonderful static hosting offering to host our project. Netlify gives us hosting or more specifically, a URL to view your project online and to share it with your friends, family, and colleagues.
Deploying to hosting tends to be at the tail-end of the project life cycle, but with services such as Netlify bringing down the cost of deployments (both in financial terms and also the time required to actually deploy) it's possible to deploy during development to either share work in progress or to have a pre-release for some other purpose.
Netlify, amongst other things, also allows you to run pre-deployment tasks, which in our case means that all the production code build processes can be performed inside of Netlify and if the build is successful, the website changes will be deployed.
Although Netlify offers a drag and drop deployment service, we are intending to trigger a new deployment to Netlify each time we push to a GitHub repo.
It's exactly these kinds of connected services that we would encourage you to look for when deciding on your own build toolchain. We can commit our code and push to GitHub and the updated code will automatically trigger the entire build routine. If all is well, we get a live change deployed automatically. The *only* action we need to perform is that initial "push".
However, we do have to set these steps up, and we'll look at that now.
The build process
-----------------
Again, because we're using Parcel for development, the build option is extremely simple to add. Instead of running the server with `npx parcel src/index.html`, we can run it with `npx parcel build src/index.html` and Parcel will build everything ready for production instead of just running it for development and testing purposes. This includes doing minification and tree-shaking of code, and cache-busting on filenames.
The newly-created production code is placed in a new directory called `dist`, which contains *all* the files required to run the website, ready for you to upload to a server.
However, doing this step manually isn't our final aim β what we want is for the build to happen automatically and the result of the `dist` directory to be deployed live on our website.
This is where our code, GitHub, and Netlify need to be set up to talk to one another, so that each time we update our GitHub code repository, Netlify will automatically pick up the changes, run the build tasks, and finally release a new update.
We're going to add the build command to our `package.json` file as an npm script, so that the command `npm run build` will trigger the build process. This step isn't necessary, but it is a good best practice to get into the habit of setting up β across all our projects, we can then rely on `npm run build` to always do the complete build step, without needing to remember the specific build command arguments for each project.
1. Open the `package.json` file in your project's root directory, and find the `scripts` property.
2. We'll add a `build` command that we can run to build our code. Add the following line to your project now:
```json
"scripts": {
// β¦
"build": "parcel build src/index.html"
}
```
**Note:** If the `scripts` property already has a command inside it, put a comma at the end of it. Keep the JSON valid.
3. You should now be able to run the following command in the root of your project directory to run the production build step (first quit the running process with `Ctrl` + `C` if you need to):
```bash
npm run build
```
This should give you an output like the following, showing you the production files that were created, how big they are, and how long they took to build:
```bash
dist/src.99d8a31a.js.map 446.15 KB 63ms
dist/src.99d8a31a.js 172.51 KB 5.55s
dist/stars.7f1dd035.svg 6.31 KB 145ms
dist/asteroid2.3ead4904.svg 3.51 KB 155ms
dist/asteroid1.698d75e9.svg 2.9 KB 153ms
dist/src.84f2edd1.css.map 2.57 KB 3ms
dist/src.84f2edd1.css 1.25 KB 1.53s
dist/bg.084d3fd3.svg 795 B 147ms
dist/index.html 354 B 944ms
```
Try it now!
For you to create your own instance of this project you will need to host this project's code in your own git repository. Our next step is to push the project to GitHub.
Committing changes to GitHub
----------------------------
This section will get you over the line to storing your code in a git repository, but it is a far cry from a git tutorial. There are many great tutorials and books available, and our Git and GitHub page is a good place to start.
We initialized our working directory as a git working directory earlier on. A quick way to verify this is to run the following command:
```bash
git status
```
You should get a status report of what files are being tracked, what files are staged, and so on β all terms that are part of the git grammar. If you get the error `fatal: not a git repository` returned, then the working directory is not a git working directory and you'll need to initialise git using `git init`.
Now we have three tasks ahead of us:
* Add any changes we've made to the stage (a special name for the place that git will commit files from).
* Commit the changes to the repository.
* Push the changes to GitHub.
1. To add changes, run the following command:
```bash
git add .
```
Note the period at the end, it means "everything in this directory". The `git add .` command is a bit of a sledgehammer approach β it will add all local changes you've worked on in one go. If you want finer control over what you add, then use `git add -p` for an interactive process, or add individual files using `git add path/to/file`.
2. Now all the code is staged, we can commit; run the following command:
```bash
git commit -m 'committing initial code'
```
**Note:** Although you're free to write whatever you wish in the commit message, there's some useful tips around the web on good commit messages. Keep them short, concise, and descriptive, so they clearly describe what the change does.
3. Finally, the code needs to be pushed to your GitHub-hosted repository. Let's do that now.
Over at GitHub, visit https://github.com/new and create your own repository to host this code.
4. Give your repository a short, memorable name, without spaces in it (use hyphens to separate words), and a description, then click *Create repository* at the bottom of the page.
You should now have a "remote" URL that points to your new GitHub repo.
![GitHub screenshot showing remote URLs you can use to deploy code to a GitHub repo](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Deployment/github-quick-setup.png)
5. This remote location needs to be added to our local git repository before we can push it up there, otherwise it won't be able to find it. You'll need to run a command with the following structure (use the provided HTTPS option for now β especially if you are new to GitHub β not the SSH option):
```bash
git remote add github https://github.com/yourname/repo-name.git
```
So if your remote URL was `https://github.com/remy/super-website.git`, as in the screenshot above, your command would be
```bash
git remote add github https://github.com/remy/super-website.git
```
Change the URL to your own repository, and run it now.
6. Now we're ready to push our code to GitHub; run the following command now:
```bash
git push github main
```
At this point, you'll be prompted to enter a username and password before Git will allow the push to be sent. This is because we used the HTTPS option rather than the SSH option, as seen in the screenshot earlier. For this, you need your GitHub username and then β if you do not have two-factor authentication (2FA) turned on β your GitHub password. We would always encourage you to use 2FA if possible, but bear in mind that if you do, you'll also need to use a "personal access token". GitHub help pages has an excellent and simple walkthrough covering how to get one.
**Note:** If you are interested in using the SSH option, thereby avoiding the need to enter your username and password every time you push to GitHub, this tutorial walks you through how.
This final command instructs git to push the code (aka publish) to the "remote" location that we called `github` (that's the repository hosted on github.com β we could have called it anything we like) using the branch `main`. We've not encountered branches at all, but the "main" branch is the default place for our work and it's what git starts on. It's also the default branch that Netlify will look for, which is convenient.
**Note:** Until October 2020 the default branch on GitHub was `master`, which for various social reasons was switched to `main`. You should be aware that this older default branch may appear in various projects you encounter, but we'd suggest using `main` for your own projects.
So with our project committed in git and pushed to our GitHub repository, the next step in the toolchain is to connect GitHub to Netlify so our project can be deployed live on the web!
Using Netlify for deployment
----------------------------
Deploying from GitHub to Netlify is surprisingly simple once you know the steps, particularly with "static websites" such as this project.
**Note:** There are also a lot of guides and tutorials on Netlify to help you improve your development workflow.
Let's get this done:
1. Go to https://app.netlify.com/start.
2. Press the GitHub button underneath the *Continuous Deployment* heading. "Continuous Deployment" means that whenever the code repository changes, Netlify will (try) to deploy the code, thus it being "continuous".
![netlify deployment options, as described in the surrounding text](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Deployment/netlify-deploy.png)
3. Depending on whether you authorized Netlify before, you might need to authorize Netlify with GitHub, and choose what account you want to authorize it for (if you have multiple GitHub accounts or orgs). Choose the one you pushed your project to.
4. Netlify will prompt you with a list of the GitHub repositories it can find. Select your project repository and proceed to the next step.
5. Since we've connected Netlify to our GitHub account and given it access to deploy the project repository, Netlify will ask *how* to prepare the project for deployment and *what* to deploy.
You should enter the command `npm run build` for the *Build command*, and specify the `dist` directory for the *Publish directory* β this contains the code that we want to make public.
6. To finish up, click *Deploy site*.
![netlify distribution options, as described in the surrounding text](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Deployment/netlify-dist.png)
7. After a short wait for the deployment to occur, you should get a URL that you can go to, to see your published site β try it out!
8. And even better, whenever we make a change and *push* the change to our remote git repository (on GitHub), this will trigger a notification to Netlify which will then run our specified build task and then deploy the resulting `dist` directory to our published site.
Try it now β make a small change to your app, and then push it to GitHub using these commands:
```bash
git add .
git commit -m 'simple netlify test'
git push github main
```
You should see your published site update with the change β this might take a few minutes to publish, so have a little patience.
That's it for Netlify. We can optionally change the name of the Netlify project or specify to use our own domain name, which Netlify offers some excellent documentation on.
Now for one final link in our toolchain: a test to ensure our code works.
Testing
-------
Testing itself is a vast subject, even within the realm of front-end development. I'll show you how to add an initial test to your project and how to use the test to prevent or to allow the project deployment to happen.
When approaching tests there are a good deal of ways to approach the problem:
* End-to-end testing, which involves your visitor clicking a thing and some other thing happening.
* Integration testing, which basically says "does one block of code still work when connected to another block?"
* Unit testing, where small and specific bits of functionality are tested to see if they do what they are supposed to do.
* And many more types. Also, see our cross browser testing module for a bunch of useful testing information
Remember also that tests are not limited to JavaScript; tests can be run against the rendered DOM, user interactions, CSS, and even how a page looks.
However, for this project we're going to create a small test that will check the third-party NASA data feed and ensure it's in the correct format. If not, the test will fail and will prevent the project from going live. To do anything else would be beyond the scope of this module β testing is a huge subject that really requires its own separate module. We are hoping that this section will at least make you aware of the need for testing, and will plant the seed that inspires you to go and learn more.
Although the test for this project does not include a test framework, as with all things in the front-end development world, there are a slew of framework options.
The test itself isn't what is important. What is important is how the failure or success is handled. Some deployment platforms will include a specific method for testing as part of their pipeline. Products like GitHub, GitLab, etc., all support running tests against individual commits.
As this project is deploying to Netlify, and Netlify only asks about the build command, we will have to make the tests part of the build. If the test fails, the build fails, and Netlify won't deploy.
Let's get started.
1. Go to your `package.json` file and open it up.
2. Find your `scripts` member, and update it so that it contains the following test and build commands:
```json
"scripts": {
β¦
"test": "node tests/\*.js",
"build": "npm run test && parcel build src/index.html"
}
```
3. Now of course we need to add the test to our codebase; create a new directory in your root directory called tests:
```bash
mkdir tests
```
4. Inside the new directory, create a test file:
```bash
cd tests
touch nasa-feed.test.js
```
5. Open this file, and add the contents of nasa-feed.test.js to it:
6. This test uses the axios package to fetch the data feed we want to test; to install this dependency, run the following command:
```bash
npm install --save-dev axios
```
We need to manually install axios because Parcel won't help us with this dependency. Our tests are outside of Parcel's view of our system β since Parcel never sees nor runs any of the test code, we're left to install the dependency ourselves.
7. Now to manually run the test, from the command line we can run:
```bash
npm run test
```
The result, if successful, is β¦ nothing. This is considered a success. In general, we only want tests to be noisy if there's something wrong. The test also exited with a special signal that tells the command line that it was successful β an exit signal of 0. If there's a failure the test fails with an exit code of 1 β this is a system-level value that says "something failed".
The `npm run test` command will use node to run all the files that are in the tests directory that end with `.js`.
In our build script, `npm run test` is called, then you see the string `&&` β this means "if the thing on the left succeeded (exited with zero), then do this thing on the right". So this translates into: if the tests pass, then build the code.
8. You'll have to upload your new code to GitHub, using similar commands to what you used before:
```bash
git add .
git commit -m 'adding test'
git push github main
```
In some cases you might want to test the result of the built code (since this isn't quite the original code we wrote), so the test might need to be run after the build command. You'll need to consider all these individual aspects whilst you're working on your own projects.
Now, finally, a minute or so after pushing, Netlify will deploy the project update. But only if it passes the test that was introduced.
Summary
-------
That's it for our sample case study, and for the module! We hope you found it useful. While there is a long way to go before you can consider yourself a client-side tooling wizard, we are hoping that this module has given you that first important step towards understanding client-side tooling, and the confidence to learn more and try out new things.
Let's summarize all the parts of the toolchain:
* Code quality and maintenance are performed by ESLint and Prettier. These tools are added as `devDependencies` to the project via `npm install --dev eslint prettier eslint-plugin-react` (the ESLint plugin is needed because this particular project uses React).
* There are two configuration files that the code quality tools read: `.eslintrc` and `.prettierrc`.
* During development, we use Parcel to handle our dependencies. `parcel src/index.html` is running in the background to watch for changes and to automatically build our source.
* Deployment is handled by pushing our changes to GitHub (on the "main" branch), which triggers a build and deployment on Netlify to publish the project. For our instance this URL is near-misses.netlify.com; you will have your own unique URL.
* We also have a simple test that blocks the building and deployment of the site if the NASA API feed isn't giving us the correct data format.
For those of you wanting a challenge, consider whether you can optimize some part of this toolchain. Some questions to ask yourself:
* Can images be compressed during the build step?
* Could React be swapped out for something smaller?
* Could you add more tests to prevent a bad build from deploying, such as performance audits?
* Could you set up a notification to let you know when a new deploy succeeded or failed?
* Previous
* Overview: Understanding client-side tools |
Command line crash course - Learn web development | Command line crash course
=========================
* Previous
* Overview: Understanding client-side tools
* Next
In your development process, you'll undoubtedly be required to run some commands in the terminal (or on the "command line" β these are effectively the same thing). This article provides an introduction to the terminal, the essential commands you'll need to enter into it, how to chain commands together, and how to add your own command line interface (CLI) tools.
| | |
| --- | --- |
| Prerequisites: |
Familiarity with the core HTML,
CSS, and JavaScript languages.
|
| Objective: | To understand what the terminal/command line is, what basic commands you should learn, and how to install new command line tools. |
Welcome to the terminal
-----------------------
The terminal is a text interface for executing text-based programs. If you're running any tooling for web development there's a near-guaranteed chance that you'll have to pop open the command line and run some commands to use your chosen tools (you'll often see such tools referred to as **CLI tools** β command line interface tools).
A large number of tools can be used by typing commands into the command line; many come pre-installed on your system, and a huge number of others are installable from package registries.
Package registries are like app stores, but (mostly) for command line based tools and software.
We'll see how to install some tools later on in this chapter, and we'll learn more about package registries in the next chapter.
One of the biggest criticisms of the command line is that it lacks hugely in user experience.
Viewing the command line for the first time can be a daunting experience: a blank screen and a blinking cursor, with very little obvious help available on what to do.
On the surface, they're far from welcoming but there's a lot you can do with them, and we promise that, with a bit of guidance and practice, using them will get easier!
This is why we are providing this chapter β to help you get started in this seemingly unfriendly environment.
### Where did the terminal come from?
The terminal originates from around the 1950s-60s and its original form really doesn't resemble what we use today (for that we should be thankful). You can read a bit of the history on Wikipedia's entry for Computer Terminal.
Since then, the terminal has remained a constant feature of all operating systems β from desktop machines to servers tucked away in the cloud, to microcomputers like the Raspberry PI Zero, and even to mobile phones. It provides direct access to the computer's underlying file system and low-level features, and is therefore incredibly useful for performing complex tasks rapidly, if you know what you are doing.
It is also useful for automation β for example, to write a command to update the titles of hundreds of files instantly, say from "ch01-xxxx.png" to "ch02-xxxx.png". If you updated the file names using your finder or explorer GUI app, it would take you a long time.
Anyway, the terminal is not going away anytime soon.
### What does the terminal look like?
Below you can see some of the different flavors of programs that are available that can get you to a terminal.
The next images show the command prompts available in Windows β there's a good range of options from the "cmd" program to "powershell" β which can be run from the start menu by typing the program name.
![A vanilla windows cmd line window, and a windows powershell window](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line/win-terminals.png)
And below, you can see the macOS terminal application.
![A basic vanilla macOS terminal](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line/mac-terminal.png)
### How do you access the terminal?
Many developers today are using Unix-based tools (e.g. the terminal, and the tools you can access through it). Many tutorials and tools that exist on the web today support (and sadly assume) Unix-based systems, but not to worry β they are available on most systems. In this section, we'll look at how to get access to the terminal on your chosen system.
#### Linux/Unix
As hinted at above, Linux/Unix systems have a terminal available by default, listed among your Applications.
#### macOS
macOS has a system called Darwin that sits underneath the graphical user interface. Darwin is a Unix-like system, which provides the terminal, and access to the low-level tools. macOS Darwin mostly has parity with Unix, certainly good enough to not cause us any worries as we work through this article.
The terminal is available on macOS at Applications/Utilities/Terminal.
#### Windows
As with some other programming tools, using the terminal (or command line) on Windows has traditionally not been as simple or easy as on other operating systems. But things are getting better.
Windows has traditionally had its own terminal-like program called cmd ("the command prompt") for a long time, but this definitely doesn't have parity with Unix commands, and is equivalent to the old-style Windows DOS prompt.
Better programs exist for providing a terminal experience on Windows, such as Powershell (see here to find installers), and Gitbash (which comes as part of the git for Windows toolset).
However, the best option for Windows in the modern day is the Windows Subsystem for Linux (WSL) β a compatibility layer for running Linux operating systems directly from inside Windows 10, allowing you to run a "true terminal" directly on Windows, without needing a virtual machine.
This can be installed directly from the Windows store for free. You can find all the documentation you need in the Windows Subsystem for Linux Documentation.
![a screenshot of the Windows subsystem for Linux documentation](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line/wsl.png)
In terms of what option to choose on Windows, we'd strongly recommend trying to install the WSL. You could stick with the default command prompt (`cmd`), and many tools will work OK, but you'll find everything easier if you have better parity with Unix tools.
#### Side note: what's the difference between a command line and a terminal?
Generally, you'll find these two terms used interchangeably. Technically, a terminal is a software that starts and connects to a shell. A shell is your session and session environment (where things like the prompt and shortcuts might be customized). The command line is the literal line where you enter commands and the cursor blinks.
### Do you have to use the terminal?
Although there's a great wealth of tools available from the command line, if you're using tools like Visual Studio Code there's also a mass of extensions that can be used as a proxy to use terminal commands without needing to use the terminal directly. However, you won't find a code editor extension for everything you want to do β you'll have to get some experience with the terminal eventually.
Basic built-in terminal commands
--------------------------------
Enough talk β let's start looking at some terminal commands! Out of the box, here are just a few of the things the command line can do, along with the names of relevant tools in each case:
* Navigate your computer's file system along with base-level tasks such as create, copy, rename, and delete:
+ Move around your directory structure: `cd`
+ Create directories: `mkdir`
+ Create files (and modify their metadata): `touch`
+ Copy files or directories: `cp`
+ Move files or directories: `mv`
+ Delete files or directories: `rm`
* Download files found at specific URLs: `curl`
* Search for fragments of text inside larger bodies of text: `grep`
* View a file's contents page by page: `less`, `cat`
* Manipulate and transform streams of text (for example changing all the instances of `<div>`s in an HTML file to `<article>`): `awk`, `tr`, `sed`
**Note:** There are a number of good tutorials on the web that go much deeper into the command line β this is only a brief introduction!
Let's move forward and look at using a few of these tools on the command line. Before you go any further, open your terminal program!
### Navigation on the command line
When you visit the command line you will inevitably need to navigate to a particular directory to "do something". All the operating systems (assuming a default setup) will launch their terminal program in your "home" directory, and from there you're likely to want to move to a different place.
The `cd` command lets you Change Directory. Technically, cd isn't a program but a built-in. This means your operating system provides it out of the box, and also that you can't accidentally delete it β thank goodness! You don't need to worry too much about whether a command is built-in or not, but bear in mind that built-ins appear on all unix-based systems.
To change the directory, you type `cd` into your terminal, followed by the directory you want to move to. Assuming the directory is inside your home directory, you can use `cd Desktop` (see the screenshots below).
![results of the cd Desktop command being run in a variety of windows terminals - the terminal location moves into the desktop](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line/win-terminals-cd.png)
Try typing this into your system's terminal:
```bash
cd Desktop
```
If you want to move back up to the previous directory, you can use two dots:
```bash
cd ..
```
**Note:** A very useful terminal shortcut is using the `tab` key to autocomplete names that you know are present, rather than having to type out the whole thing. For example, after typing the above two commands, try typing `cd D` and pressing `tab` β it should autocomplete the directory name `Desktop` for you, provided it is present in the current directory. Bear this in mind as you move forward.
If the directory you want to go to is nested deep, you need to know the path to get to it. This usually becomes easier as you get more familiar with the structure of your file system, but if you are not sure of the path you can usually figure it out with a combination of the `ls` command (see below), and by clicking around in your Explorer/Finder window to see where a directory is, relative to where you currently are.
For example, if you wanted to go to a directory called `src`, located inside a directory called `project`, located on the `Desktop`, you could type these three commands to get there from your home folder:
```bash
cd Desktop
cd project
cd src
```
But this a waste of time β instead, you can type one command, with the different items in the path separated by forward slashes, just like you do when specifying paths to images or other assets in CSS, HTML, or JavaScript code:
```bash
cd Desktop/project/src
```
Note that including a leading slash on your path makes the path absolute, for example `/Users/your-user-name/Desktop`. Omitting the leading slash as we've done above makes the path relative to your present working directory. This is exactly the same as you would see with URLs in your web browser. A leading slash means "at the root of the website", whereas omitting the slash means "the URL is relative to my current page".
**Note:** On windows, you use backslashes instead of forward slashes, e.g. `cd Desktop\project\src` β this may seem really odd, but if you are interested in why, watch this YouTube clip featuring an explanation by one of Microsoft's Principal engineers.
### Listing directory contents
Another built-in Unix command is `ls` (short for list), which lists the contents of the directory you're currently in. Note that this won't work if you're using the default Windows command prompt (`cmd`) β the equivalent there is `dir`.
Try running this now in your terminal:
```bash
ls
```
This gives you a list of the files and directories in your present working directory, but the information is really basic β you only get the name of each item present, not whether it is a file or a directory, or anything else. Fortunately, a small change to the command usage can give you a lot more information.
### Introducing command options
Most terminal commands have options β these are modifiers that you add onto the end of a command, which make it behave in a slightly different way. These usually consist of a space after the command name, followed by a dash, followed by one or more letters.
For example, give this a go and see what you get:
```bash
ls -l
```
In the case of `ls`, the `-l` (*dash ell*) option gives you a listing with one file or directory on each line, and a lot more information shown. Directories can be identified by looking for a letter "d" on the very left-hand side of the lines. Those are the ones we can `cd` into.
Below is a screenshot with a "vanilla" macOS terminal at the top, and a customized terminal with some extra icons and colors to keep it looking lively β both showing the results of running `ls -l`:
![A vanilla macOS terminal and a more colorful custom macOS terminal, showing a file listing - the result of running the ls -l command](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line/mac-terminals-ls.png)
**Note:** To find out exactly what options each command has available, you can look at its man page. This is done by typing the `man` command, followed by the name of the command you want to look up, for example `man ls`. This will open up the man page in the terminal's default text file viewer (for example, `less` in my terminal), and you should then be able to scroll through the page using the arrow keys, or some similar mechanism. The man page lists all the options in great detail, which may be a bit intimidating to begin with, but at least you know it's there if you need it. Once you are finished looking through the man page, you need to quit out of it using your text viewer's quit command ("q" in `less`; you may have to search on the web to find it if it isn't obvious).
**Note:** To run a command with multiple options at the same time, you can usually put them all in a single string after the dash character, for example `ls -lah`, or `ls -ltrh`. Try looking at the `ls` man page to work out what these extra options do!
Now that we've discussed two fundamental commands, have a little poke around your directory and see if you can navigate from one place to the next.
### Creating, copying, moving, removing
There are a number of other basic utility commands that you'll probably end up using quite a lot as you work with the terminal. They are pretty simple, so we won't explain them all in quite as much detail as the previous couple.
Have a play with them in a test directory you've created somewhere so that you don't accidentally delete anything important, using the example commands below for guidance:
* `mkdir` β this creates a new directory inside the current directory you are in, with the name you provide after the command name. For example, `mkdir my-awesome-website` will make a new directory called `my-awesome-website`.
* `rmdir` β removes the named directory, but only if it's empty. For example, `rmdir my-awesome-website` will remove the directory we created above. If you want to remove a directory that is not empty (and also remove everything it contains), then you can use the `-r` option (recursive), but this is dangerous. Make sure there is nothing you might need inside the directory later on, as it will be gone forever.
* `touch` β creates a new empty file, inside the current directory. For example, `touch mdn-example.md` creates a new empty file called `mdn-example.md`.
* `mv` β moves a file from the first specified file location to the second specified file location, for example `mv mdn-example.md mdn-example.txt` (the locations are written as file paths). This command moves a file called `mdn-example.md` in the current directory to a file called `mdn-example.txt` in the current directory. Technically the file is being moved, but from a practical perspective, this command is actually renaming the file.
* `cp` β similar in usage to `mv`, `cp` creates a copy of the file in the first location specified, in the second location specified. For example, `cp mdn-example.txt mdn-example.txt.bak` creates a copy of `mdn-example.txt` called `mdn-example.txt.bak` (you can of course call it something else if you wish).
* `rm` β removes the specified file. For example, `rm mdn-example.txt` deletes a single file called `mdn-example.txt`. Note that this delete is permanent and can't be undone via the recycle bin that you might have on your desktop user interface.
**Note:** Many terminal commands allow you to use asterisks as "wild card" characters, meaning "any sequence of characters". This allows you to run an operation against a potentially large number of files at once, all of which match the specified pattern. As an example, `rm mdn-*` would delete all files beginning with `mdn-`. `rm mdn-*.bak` would delete all files that start with `mdn-` and end with `.bak`.
Terminal β considered harmful?
------------------------------
We've alluded to this before, but to be clear β you need to be careful with the terminal. Simple commands do not carry too much danger, but as you start putting together more complex commands, you need to think carefully about what the command will do, and try testing them out first before you finally run them in the intended directory.
Let's say you had 1000 text files in a directory, and you wanted to go through them all and only delete the ones that have a certain substring inside the filename. If you are not careful, then you might end up deleting something important, losing you a load of your work in the process.
One good habit to get into is to write your terminal command out inside a text editor, figure out how you think it should look, and then make a backup copy of your directory and try running the command on that first, to test it.
Another good tip β if you're not comfortable trying terminal commands out on your own machine, a nice safe place to try them is over at Glitch.com. Along with being a great place to try out web development code, the projects also give you access to a terminal, so you can run all these commands directly in that terminal, safe in the knowledge that you won't break your own machine.
![a double screenshot showing the glitch.com home page, and the glitch terminal emulator](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line/glitch.png)
A great resource for getting a quick overview of specific terminal commands is tldr.sh. This is a community-driven documentation service, similar to MDN, but specific to terminal commands.
In the next section let's step it up a notch (or several notches in fact) and see how we can connect tools together on the command line to really see how the terminal can be advantageous over the regular desktop user interface.
Connecting commands together with pipes
---------------------------------------
The terminal really comes into its own when you start to chain commands together using the `|` (pipe) symbol. Let's look at a very quick example of what this means.
We've already looked at `ls`, which outputs the contents of the current directory:
```bash
ls
```
But what if we wanted to quickly count the number of files and directories inside the current directory? `ls` can't do that on its own.
There is another Unix tool available called `wc`. This counts the number of words, lines, characters, or bytes of whatever is inputted into it. This can be a text file β the below example outputs the number of lines in `myfile.txt`:
```bash
wc -l myfile.txt
```
But it can also count the number of lines of whatever output is **piped** into it. For example, the below command counts the number of lines outputted by the `ls` command (what it would normally print to the terminal if run on its own) and outputs that count to the terminal instead:
```bash
ls | wc -l
```
Since `ls` prints each file or directory on its own line, that effectively gives us a directory and file count.
So what is going on here? A general philosophy of (unix) command line tools is that they print text to the terminal (also referred to "printing to standard output" or `STDOUT`). A good deal of commands can also read content from streamed input (known as "standard input" or `STDIN`).
The pipe operator can *connect* these inputs and outputs together, allowing us to build up increasingly more complex operations to suit our needs β the output from one command can become the input to the next command. In this case, `ls` would normally print its output to `STDOUT`, but instead `ls`'s output is being piped into `wc`, which takes that output as an input, counting the number of lines it contains, and prints that count to `STDOUT` instead.
A slightly more complex example
-------------------------------
Let's go through something a bit more complicated.
We will first try to fetch the contents of MDN's "fetch" page using the `curl` command (which can be used to request content from URLs), from `https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch`.
Try it now:
```bash
curl https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
```
You won't get an output because the page has been redirected (to /Web/API/fetch).
We need to explicitly tell `curl` to follow redirects using the `-L` flag.
Let's also look at the headers that `developer.mozilla.org` returns using `curl`'s `-I` flag, and print all the location redirects it sends to the terminal, by piping the output of `curl` into `grep` (we will ask `grep` to return all the lines that contain the word "location").
Try running the following (you'll see that there is just one redirect before we reach the final page):
```bash
curl https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch -L -I | grep location
```
Your output should look something like this (`curl` will first output some download counters and suchlike):
```bash
location: /en-US/docs/Web/API/fetch
```
Although contrived, we could take this result a little further and transform the `location:` line contents, adding the base origin to the start of each one so that we get complete URLs printed out.
For that, we'll add `awk` to the mix (which is a programming language akin to JavaScript or Ruby or Python, just a lot older!).
Try running this:
```bash
curl https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch -L -I | grep location | awk '{ print "https://developer.mozilla.org" $2 }'
```
Your final output should look something like this:
```bash
https://developer.mozilla.org/en-US/docs/Web/API/fetch
```
By combining these commands we've customized the output to show the full URLs that the Mozilla server is redirecting through when we request the `/docs/Web/API/WindowOrWorkerGlobalScope/fetch` URL.
Getting to know your system will prove useful in years to come β learn how these single serving tools work and how they can become part of your toolkit to solve niche problems.
Adding powerups
---------------
Now we've had a look at some of the built-in commands your system comes equipped with, let's look at how we can install a third-party CLI tool and make use of it.
The vast ecosystem of installable tools for front-end web development currently exists mostly inside npm, a privately owned, package hosting service that works closely together with Node.js.
This is slowly expanding β you can expect to see more package providers as time goes on.
Installing Node.js also installs the npm command line tool (and a supplementary npm-centric tool called npx), which offers a gateway to installing additional command line tools. Node.js and npm work the same across all systems: macOS, Windows, and Linux.
Install npm on your system now, by going to the URL above and downloading and running a Node.js installer appropriate to your operating system. If prompted, make sure to include npm as part of the installation.
![the Node.js installer on windows, showing the option to include npm](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line/npm-install-option.png)
Although we'll look at a number of different tools in the next article onwards, we'll cut our teeth on Prettier.
Prettier is an opinionated code formatter that only has a "few options".
Fewer options tends to mean simpler.
Given how tooling can sometimes get out of hand in terms of complexity, "few options" can be very appealing.
### Where to install our CLI tools?
Before we dive into installing Prettier, there's a question to answer β "where should we install it?"
With `npm` we have the choice of installing tools globally β so we can access them anywhere β or locally to the current project directory.
There are pros and cons each way β and the following lists of pros and cons for installing globally are far from exhaustive.
**Pros of installing globally:**
* Accessible anywhere in your terminal
* Only install once
* Uses less disk space
* Always the same version
* Feels like any other unix command
**Cons of installing globally:**
* May not be compatible with your project's codebase
* Other developers in your team won't have access to these tools, for example if you are sharing the codebase over a tool like git.
* Related to the previous point, it makes project code harder to replicate (if you install your tools locally, they can be set up as dependencies and installed with `npm install`).
Although the *cons* list is shorter, the negative impact of global installing is potentially much larger than the benefits.
Here we'll install locally, but feel free to install globally once you understand the relative risks.
### Installing Prettier
Prettier is an opinionated code formatting tool for front-end developers, focusing on JavaScript-based languages and adding support for HTML, CSS, SCSS, JSON, and more.
Prettier can:
* Save the cognitive overhead of getting the style consistent manually across all your code files; Prettier can do this for you automatically.
* Help newcomers to web development format their code in best-practice fashion.
* Be installed on any operating system and even as a direct part of project tooling, ensuring that colleagues and friends who work on your code use the code style you're using.
* Be configured to run upon save, as you type, or even before publishing your code (with additional tooling that we'll see later on in the module).
For this article, we will install Prettier locally, as suggested in the Prettier installation guide
Once you've installed node, open up the terminal and run the following command to install Prettier:
```bash
npm install prettier
```
You can now run the file locally using the npx tool.
Running the command without any arguments, as with many other commands, will offer up usage and help information.
Try this now:
```bash
npx prettier
```
Your output should look something like this:
```bash
Usage: prettier [options] [file/glob ...]
By default, output is written to stdout.
Stdin is read if it is piped to Prettier and no files are given.
β¦
```
It's always worth at the very least skimming over the usage information, even if it is long.
It'll help you to understand better how the tool is intended to be used.
**Note:** If you have not first installed Prettier locally, then running `npx prettier` will download and run the latest version of Prettier all in one go *just for that command*.
While that might sound great, new versions of Prettier may slightly modify the output.
You want to install it locally so that you are fixing the version of Prettier that you are using for formatting until you are ready to change it.
### Playing with Prettier
Let's have a quick play with Prettier, so you can see how it works.
First of all, create a new directory somewhere on your file system that is easy to find. Maybe a directory called `prettier-test` on your `Desktop`.
Now save the following code in a new file called `index.js`, inside your test directory:
```js
const myObj = {
a:1,b:{c:2}}
function printMe(obj){console.log(obj.b.c)}
printMe(myObj)
```
We can run Prettier against a codebase to just check if our code wants adjusting. `cd` into your directory, and try running this command:
```bash
npx prettier --check index.js
```
You should get an output along the lines of:
```bash
Checking formatting...
index.js
Code style issues found in the above file(s). Forgot to run Prettier?
```
So, there's some code styles that can be fixed. No problem. Adding the `--write` option to the `prettier` command will fix those up, leaving us to focus on actually writing useful code.
Now try running this version of the command:
```bash
npx prettier --write index.js
```
You'll get an output like this
```bash
Checking formatting...
index.js
Code style issues fixed in the above file(s).
```
But more importantly, if you look back at your JavaScript file you'll find it has been reformatted to something like this:
```js
const myObj = {
a: 1,
b: { c: 2 },
};
function printMe(obj) {
console.log(obj.b.c);
}
printMe(myObj);
```
Depending on your workflow (or the workflow that you pick) you can make this an automated part of your process. Automation is really where tools excel; our personal preference is the kind of automation that "just happens" without having to configure anything.
With Prettier there's a number of ways automation can be achieved and though they're beyond the scope of this article, there's some excellent resources online to help (some of which have been linked to). You can invoke Prettier:
* Before you commit your code into a git repository using Husky.
* Whenever you hit "save" in your code editor, be it VS Code, or Sublime Text.
* As part of continuous integration checks using tools like GitHub Actions.
Our personal preference is the second one β while using say VS Code, Prettier kicks in and cleans up any formatting it needs to do every time we hit save. You can find a lot more information about using Prettier in different ways in the Prettier docs.
Other tools to play with
------------------------
If you want to play with a few more tools, here's a brief list that are fun to try out:
* `bat` β A "nicer" `cat` (`cat` is used to print the contents of files).
* `prettyping` β `ping` on the command line, but visualized (`ping` is a useful tool to check if a server is responding).
* `htop` β A process viewer, useful for when something is making your CPU fan behave like a jet engine and you want to identify the offending program.
* `tldr` β mentioned earlier in this chapter, but available as a command line tool.
Note that some of the above suggestions may need installing using npm, like we did with Prettier.
Summary
-------
That brings us to the end of our brief tour of the terminal/command line. Next up we'll be looking in more detail at package managers, and what we can do with them.
* Previous
* Overview: Understanding client-side tools
* Next |