Dealing with files - Learn web development

Dealing with files
==================

* Previous
* Overview: Getting started with the web
* Next

A website consists of many files: text content, code, stylesheets, media content, and so on. When you're building a website, you need to assemble these files into a sensible structure on your local computer, make sure they can talk to one another, and get all your content looking right before you eventually upload them to a server. *Dealing with files* discusses some issues you should be aware of so you can set up a sensible file structure for your website.

Where should your website live on your computer?
------------------------------------------------

When you are working on a website locally on your computer, you should keep all the related files in a single folder that mirrors the published website's file structure on the server. This folder can live anywhere you like, but you should put it somewhere where you can easily find it, maybe on your Desktop, in your Home folder, or at the root of your hard drive.

1. Choose a place to store your website projects. Inside your chosen place, create a new folder called `web-projects` (or similar). This is where all your website projects will live.
2. Inside this first folder, create another folder to store your first website in. Call it `test-site` (or something more imaginative).
An aside on casing and spacing
------------------------------

You'll notice that throughout this article, we ask you to name folders and files completely in lowercase with no spaces. This is because:

1. Many computers, particularly web servers, are case-sensitive. So for example, if you put an image on your website at `test-site/MyImage.jpg` and then in a different file you try to invoke the image as `test-site/myimage.jpg`, it may not work.
2. Browsers, web servers, and programming languages do not handle spaces consistently. For example, if you use spaces in your filename, some systems may treat the filename as two filenames. Some servers will replace the spaces in your filenames with "%20" (the character code for spaces in URLs), resulting in all your links being broken. It's better to separate words with hyphens, rather than underscores: `my-file.html` vs. `my_file.html`.

The short answer is that you should use a hyphen for your file names. The Google search engine treats a hyphen as a word separator but does not regard an underscore that way. For these reasons, it is best to get into the habit of writing your folder and file names in lowercase with no spaces and with words separated by hyphens, at least until you know what you're doing. That way you'll bump into fewer problems down the road.

What structure should your website have?
----------------------------------------

Next, let's look at what structure our test site should have. The most common things we'll have on any website project we create are an index HTML file and folders to contain images, style files, and script files. Let's create these now:

1. **`index.html`**: This file will generally contain your homepage content, that is, the text and images that people see when they first go to your site. Using your text editor, create a new file called `index.html` and save it just inside your `test-site` folder.
2. **`images` folder**: This folder will contain all the images that you use on your site. Create a folder called `images`, inside your `test-site` folder.
3. **`styles` folder**: This folder will contain the CSS code used to style your content (for example, setting text and background colors). Create a folder called `styles`, inside your `test-site` folder.
4. **`scripts` folder**: This folder will contain all the JavaScript code used to add interactive functionality to your site (e.g. buttons that load data when clicked). Create a folder called `scripts`, inside your `test-site` folder.

**Note:** On Windows computers, you might have trouble seeing the file names, because Windows has an option called **Hide extensions for known file types** turned on by default. Generally, you can turn this off by going to Windows Explorer, selecting the **Folder options…** option, unchecking the **Hide extensions for known file types** check box, then clicking **OK**. For more specific information covering your version of Windows, you can search on the web.

File paths
----------

To make files talk to one another, you have to provide a file path between them — basically a route, so one file knows where another one is. To demonstrate this, we will insert a little bit of HTML into our `index.html` file, and make it display the image you chose in the article "What will your website look like?" Alternatively, you can choose an existing image at your disposal, on your computer or from the Web, and use it in the following steps:

1. Copy the image you chose earlier into your `images` folder.
2. Open up your `index.html` file, and insert the following code into the file exactly as shown. Don't worry about what it all means for now — we'll look at the structures in more detail later in the series.

```html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>My test page</title>
  </head>
  <body>
    <img src="" alt="My test image" />
  </body>
</html>
```

3. The line `<img src="" alt="My test image">` is the HTML code that inserts an image into the page. We need to tell the HTML where the image is. The image is inside the *images* directory, which is in the same directory as `index.html`. To walk down the file structure from `index.html` to our image, the file path we'd need is `images/your-image-filename`. For example, our image is called `firefox-icon.png`, so the file path is `images/firefox-icon.png`.
4. Insert the file path into your HTML code between the double quote marks of the `src=""` code.
5. Change the contents of the `alt` attribute to a description of the image you are including. In this case, `alt="Firefox logo: flaming fox wrapping the world"`.
6. Save your HTML file, then load it in your web browser (double-click the file). You should see your new webpage displaying your image!

![A screenshot of our basic website showing just the Firefox logo - a flaming fox wrapping the world](/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files/website-screenshot.png)

Some general rules for file paths:

* To link to a target file in the same directory as the invoking HTML file, just use the filename, e.g. `my-image.jpg`.
* To reference a file in a subdirectory, write the directory name in front of the path, plus a forward slash, e.g. `subdirectory/my-image.jpg`.
* To link to a target file in the directory **above** the invoking HTML file, write two dots. So for example, if `index.html` was inside a subfolder of `test-site` and `my-image.jpg` was inside `test-site`, you could reference `my-image.jpg` from `index.html` using `../my-image.jpg`.
* You can combine these as much as you like, for example `../subdirectory/another-subdirectory/my-image.jpg`.

For now, this is about all you need to know.

**Note:** The Windows file system tends to use backslashes, not forward slashes, e.g. `C:\Windows`. This doesn't matter in HTML — even if you are developing your website on Windows, you should still use forward slashes in your code.

What else should be done?
-------------------------

That is about it for now. Your folder structure should look something like this:

![A file structure in macOS finder, showing an images folder with an image in, empty scripts and styles folders, and an index.html file](/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files/file-structure.png)

* Previous
* Overview: Getting started with the web
* Next


Installing basic software - Learn web development

Installing basic software
=========================

* Overview: Getting started with the web
* Next

In *Installing basic software*, we show you what tools you need to do simple web development and how to install them properly.

What tools do I actually need, right now?
-----------------------------------------

In this article, we'll set you up with the bare minimum — a text editor and some modern web browsers.

### Installing a text editor

You probably already have a basic text editor on your computer. By default Windows includes Notepad and macOS comes with TextEdit. Linux distros vary; the Ubuntu 22.04 LTS release comes with GNOME Text Editor by default.

For web development, you can probably do better than Notepad or TextEdit. We recommend starting with Visual Studio Code, which is a free editor, that offers live previews and code hints.

### Installing modern web browsers

For now, we'll install a couple of desktop web browsers to test our code in. Choose your operating system below and click the relevant links to download installers for your favorite browsers:

* Linux: Firefox, Chrome, Opera, Brave.
* Windows: Firefox, Chrome, Opera, Microsoft Edge, Brave (Windows 10 comes with Edge by default; otherwise, you should install an alternative browser).
* macOS: Firefox, Chrome, Opera, Safari, Brave (macOS and iOS come with Safari by default).

Before going on, you should install at least two of these browsers and have them ready for testing.

### Installing a local web server

Some examples will need to be run by a web server to work successfully. You can find out how to do this in How do you set up a local testing server?

What tools do the professionals use?
------------------------------------

The following looks like a scary list, but fortunately, you can get started in web development without knowing anything about most of these.

* **A computer**. Maybe that sounds obvious to some people, but some of you are reading this article on your phone or a library computer. For serious web development, it's better to invest in a desktop or laptop computer running Windows, macOS or Linux.
* **A text editor**, to write code in. This could be a text editor (e.g. Visual Studio Code, Notepad++, Sublime Text, GNU Emacs, or VIM), or a hybrid editor (e.g. Dreamweaver or WebStorm). Office document editors are not suitable for this use, as they rely on hidden elements that interfere with the rendering engines used by web browsers.
* **Web browsers**, to test code in. Currently, the most-used browsers are Firefox, Chrome, Safari, and Microsoft Edge. You should also test how your site performs on mobile devices and on any old browsers your target audience may still be using (such as IE 8–10). Lynx, a text-based terminal web browser, is great for seeing how your site is experienced by visually-impaired users.
* **A graphics editor**, like GIMP, Figma, Paint.NET, Photoshop, Sketch or XD, to make images or graphics for your web pages.
* **A version control system**, to manage files on servers, collaborate on a project with a team, share code and assets and avoid editing conflicts. Right now, Git is the most popular version control system along with the GitHub or GitLab hosting service.
* **An FTP program**, used on older web hosting accounts to manage files on servers (Git is increasingly replacing FTP for this purpose). There are loads of (S)FTP programs available including Cyberduck, Fetch and FileZilla.
* **An automation system,** like Webpack, Grunt, or Gulp to automatically perform repetitive tasks, such as minifying code and running tests.
* Libraries, frameworks, etc., to speed up writing common functionality. A library tends to be an existing JavaScript or CSS file that provides ready-rolled functionality for you to make use of in your code. A framework tends to take this idea further, offering a complete system with some custom syntaxes for you to write a web app on top of.
* More tools besides!
* Overview: Getting started with the web
* Next


How the web works - Learn web development

How the web works
=================

* Previous
* Overview: Getting started with the web

*How the web works* provides a simplified view of what happens when you view a webpage in a web browser on your computer or phone.

This theory is not essential to writing web code in the short term, but before long you'll really start to benefit from understanding what's happening in the background.

Clients and servers
-------------------

Computers connected to the internet are called **clients** and **servers**. A simplified diagram of how they interact might look like this:

![Two circles representing client and server. An arrow labelled request is going from client to server, and an arrow labelled responses is going from server to client](/en-US/docs/Learn/Getting_started_with_the_web/How_the_Web_works/simple-client-server.png)

* Clients are the typical web user's internet-connected devices (for example, your computer connected to your Wi-Fi, or your phone connected to your mobile network) and web-accessing software available on those devices (usually a web browser like Firefox or Chrome).
* Servers are computers that store webpages, sites, or apps. When a client device wants to access a webpage, a copy of the webpage is downloaded from the server onto the client machine to be displayed in the user's web browser.
The other parts of the toolbox
------------------------------

The client and server we've described above don't tell the whole story. There are many other parts involved, and we'll describe them below.

For now, let's imagine that the web is a road. On one end of the road is the client, which is like your house. On the other end of the road is the server, which is a shop you want to buy something from.

![A black-and-white photo of a person crossing a road at a crosswalk](/en-US/docs/Learn/Getting_started_with_the_web/How_the_Web_works/road.jpg)

In addition to the client and the server, we also need to say hello to:

* **Your internet connection**: Allows you to send and receive data on the web. It's basically like the street between your house and the shop.
* **TCP/IP**: Transmission Control Protocol and Internet Protocol are communication protocols that define how data should travel across the internet. This is like the transport mechanisms that let you place an order, go to the shop, and buy your goods. In our example, this is like a car or a bike (or however else you might get around).
* **DNS**: Domain Name System is like an address book for websites. When you type a web address in your browser, the browser looks at the DNS to find the website's IP address before it can retrieve the website. The browser needs to find out which server the website lives on, so it can send HTTP messages to the right place (see below). This is like looking up the address of the shop so you can access it.
* **HTTP**: Hypertext Transfer Protocol is an application protocol that defines a language for clients and servers to speak to each other. This is like the language you use to order your goods.
* **Component files**: A website is made up of many different files, which are like the different parts of the goods you buy from the shop. These files come in two main types:
    + **Code files**: Websites are built primarily from HTML, CSS, and JavaScript, though you'll meet other technologies a bit later.
    + **Assets**: This is a collective name for all the other stuff that makes up a website, such as images, music, video, Word documents, and PDFs.
So what happens, exactly?
-------------------------

When you type a web address into your browser (for our analogy that's like walking to the shop):

1. The browser goes to the DNS server, and finds the real address of the server that the website lives on (you find the address of the shop).
2. The browser sends an HTTP request message to the server, asking it to send a copy of the website to the client (you go to the shop and order your goods). This message, and all other data sent between the client and the server, is sent across your internet connection using TCP/IP.
3. If the server approves the client's request, the server sends the client a "200 OK" message, which means "Of course you can look at that website! Here it is", and then starts sending the website's files to the browser as a series of small chunks called data packets (the shop gives you your goods, and you bring them back to your house).
4. The browser assembles the small chunks into a complete web page and displays it to you (the goods arrive at your door — new shiny stuff, awesome!).
Order in which component files are parsed
-----------------------------------------

When browsers send requests to servers for HTML files, those HTML files often contain `<link>` elements referencing external CSS stylesheets and `<script>` elements referencing external JavaScript scripts. It's important to know the order in which those files are parsed by the browser as the browser loads the page:

* The browser parses the HTML file first, and that leads to the browser recognizing any `<link>`-element references to external CSS stylesheets and any `<script>`-element references to scripts.
* As the browser parses the HTML, it sends requests back to the server for any CSS files it has found from `<link>` elements, and any JavaScript files it has found from `<script>` elements, and from those, then parses the CSS and JavaScript.
* The browser generates an in-memory DOM tree from the parsed HTML, generates an in-memory CSSOM structure from the parsed CSS, and compiles and executes the parsed JavaScript.
* As the browser builds the DOM tree and applies the styles from the CSSOM tree and executes the JavaScript, a visual representation of the page is painted to the screen, and the user sees the page content and can begin to interact with it.
DNS explained
-------------

Real web addresses aren't the nice, memorable strings you type into your address bar to find your favorite websites. They are special numbers that look like this: `192.0.2.172`.

This is called an IP address, and it represents a unique location on the web. However, it's not very easy to remember, is it? That's why the Domain Name System was invented. This system uses special servers that match up a web address you type into your browser (like "mozilla.org") to the website's real (IP) address.

Websites can be reached directly via their IP addresses. You can use a DNS lookup tool to find the IP address of a website.

Packets explained
-----------------

Earlier we used the term "packets" to describe the format in which the data is transferred between the client and server. What do we mean here? Basically, when data is sent across the web, it is sent in thousands of small chunks. There are multiple reasons why data is sent in small packets. They are sometimes dropped or corrupted, and it's easier to replace small chunks when this happens. Additionally, the packets can be routed along different paths, making the exchange faster and allowing many different users to download the same website at the same time. If each website was sent as a single big chunk, only one user could download it at a time, which obviously would make the web very inefficient and not much fun to use.

See also
--------

* How the Internet works
* HTTP — an Application-Level Protocol
* HTTP: Let's GET It On!
* HTTP: Response Codes
Credit
------

Street photo: Street composing, by kevin digga.

* Previous
* Overview: Getting started with the web


HTML basics - Learn web development

HTML basics
===========

* Previous
* Overview: Getting started with the web
* Next

HTML (**H**yper**T**ext **M**arkup **L**anguage) is the code that is used to structure a web page and its content. For example, content could be structured within a set of paragraphs, a list of bulleted points, or using images and data tables. As the title suggests, this article will give you a basic understanding of HTML and its functions.

So what is HTML?
----------------

HTML is a *markup language* that defines the structure of your content. HTML consists of a series of **elements**, which you use to enclose, or wrap, different parts of the content to make it appear a certain way, or act a certain way. The enclosing tags can make a word or image hyperlink to somewhere else, can italicize words, can make the font bigger or smaller, and so on. For example, take the following line of content:
```

My cat is very grumpy
```

If we wanted the line to stand by itself, we could specify that it is a paragraph by enclosing it in paragraph tags:

```html
<p>My cat is very grumpy</p>
```

### Anatomy of an HTML element

Let's explore this paragraph element a bit further.

![paragraph element including opening tag, content reading 'my cat is very grumpy', and a closing tag](/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics/grumpy-cat-small.png)

The main parts of our element are as follows:

1. **The opening tag:** This consists of the name of the element (in this case, p), wrapped in opening and closing **angle brackets**. This states where the element begins or starts to take effect — in this case where the paragraph begins.
2. **The closing tag:** This is the same as the opening tag, except that it includes a *forward slash* before the element name. This states where the element ends — in this case where the paragraph ends. Failing to add a closing tag is one of the standard beginner errors and can lead to strange results.
3. **The content:** This is the content of the element, which in this case, is just text.
4. **The element:** The opening tag, the closing tag, and the content together comprise the element.

Elements can also have attributes that look like the following:

![Paragraph opening tag with a class attribute highlighted: class=editor-note](/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics/grumpy-cat-attribute-small.png)

 Attributes contain extra information about the element that you don't want to appear in the actual content. Here, `class` is the attribute *name* and `editor-note` is the attribute *value*. The `class` attribute allows you to give the element a non-unique identifier that can be used to target it (and any other elements with the same `class` value) with style information and other things.
 Some attributes have no value, such as `required`.

Attributes that set a value always have:

1. A space between it and the element name (or the previous attribute, if the element already has one or more attributes).
2. The attribute name followed by an equal sign.
3. The attribute value wrapped by opening and closing quotation marks.

**Note:** Simple attribute values that don't contain ASCII whitespace (or any of the characters `"` `'` ``` `=` `<` `>`) can remain unquoted, but it is recommended that you quote all attribute values, as it makes the code more consistent and understandable.

### Nesting elements

You can put elements inside other elements too — this is called **nesting**. If we wanted to state that our cat is **very** grumpy, we could wrap the word "very" in a `<strong>` element, which means that the word is to be strongly emphasized:

```html

My cat is very grumpy.

```

You do however need to make sure that your elements are properly nested. In the example above, we opened the `<p>` element first, then the `<strong>` element; therefore, we have to close the `<strong>` element first, then the `<p>` element. The following is incorrect:

```html

My cat is very grumpy.

```

The elements have to open and close correctly so that they are clearly inside or outside one another. If they overlap as shown above, then your web browser will try to make the best guess at what you were trying to say, which can lead to unexpected results. So don't do it!

### Void elements

Some elements have no content and are called **void elements**. Take the `<img>` element that we already have in our HTML page:

```html

```

This contains two attributes, but there is no closing `</img>` tag and no inner content. This is because an image element doesn't wrap content to affect it. Its purpose is to embed an image in the HTML page in the place it appears.

### Anatomy of an HTML document

That wraps up the basics of individual HTML elements, but they aren't handy on their own. Now we'll look at how individual elements are combined to form an entire HTML page. Let's revisit the code we put into our `index.html` example (which we first met in the Dealing with files article):

```html
<!doctype html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>My test page</title>

```

Here, we have the following:

* `<!DOCTYPE html>` — doctype. It is a required preamble. In the mists of time, when HTML was young (around 1991/92), doctypes were meant to act as links to a set of rules that the HTML page had to follow to be considered good HTML, which could mean automatic error checking and other useful things. However, these days, they don't do much and are basically just needed to make sure your document behaves correctly. That's all you need to know for now.
* `<html></html>` — the `<html>` element. This element wraps all the content on the entire page and is sometimes known as the root element. It also includes the `lang` attribute, setting the primary language of the document.
* `<head></head>` — the `<head>` element. This element acts as a container for all the stuff you want to include on the HTML page that *isn't* the content you are showing to your page's viewers. This includes things like keywords and a page description that you want to appear in search results, CSS to style our content, character set declarations, and more.
* `<meta charset="utf-8">` — This element sets the character set your document should use to UTF-8 which includes most characters from the vast majority of written languages. Essentially, it can now handle any textual content you might put on it. There is no reason not to set this, and it can help avoid some problems later on.
* `<meta name="viewport" content="width=device-width">` — This viewport element ensures the page renders at the width of viewport, preventing mobile browsers from rendering pages wider than the viewport and then shrinking them down.
* `<title></title>` — the `<title>` element. This sets the title of your page, which is the title that appears in the browser tab the page is loaded in. It is also used to describe the page when you bookmark/favorite it.
* `<body></body>` — the `<body>` element. This contains *all* the content that you want to show to web users when they visit your page, whether that's text, images, videos, games, playable audio tracks, or whatever else.
Images
------

Let's turn our attention to the `<img>` element again:

```html

```

As we said before, it embeds an image into our page in the position it appears. It does this via the `src` (source) attribute, which contains the path to our image file.

We have also included an `alt` (alternative) attribute. In the `alt` attribute, you specify descriptive text for users who cannot see the image, possibly because of the following reasons:

1. They are visually impaired. Users with significant visual impairments often use tools called screen readers to read out the alt text to them.
2. Something has gone wrong causing the image not to display. For example, try deliberately changing the path inside your `src` attribute to make it incorrect. If you save and reload the page, you should see something like this in place of the image:

![The words: my test image](/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics/alt-text-example.png)

The keywords for alt text are "descriptive text". The alt text you write should provide the reader with enough information to have a good idea of what the image conveys. In this example, our current text of "My test image" is no good at all. A much better alternative for our Firefox logo would be "The Firefox logo: a flaming fox surrounding the Earth."

Try coming up with some better alt text for your image now.

**Note:** Find out more about accessibility in our accessibility learning module.

Marking up text
---------------

This section will cover some essential HTML elements you'll use for marking up the text.

### Headings

Heading elements allow you to specify that certain parts of your content are headings — or subheadings. In the same way that a book has the main title, chapter titles, and subtitles, an HTML document can too. HTML contains 6 heading levels, <h1> - <h6>, although you'll commonly only use 3 to 4 at most:

```html

My main title

My top level heading

My subheading

My sub-subheading

```

**Note:** Anything in HTML between `<!--` and `-->` is an **HTML comment**. The browser ignores comments as it renders the code. In other words, they are not visible on the page - just in the code. HTML comments are a way for you to write helpful notes about your code or logic.

Now try adding a suitable title to your HTML page just above your `<img>` element.

**Note:** You'll see that your heading level 1 has an implicit style. Don't use heading elements to make text bigger or bold, because they are used for accessibility and other reasons such as SEO. Try to create a meaningful sequence of headings on your pages, without skipping levels.

### Paragraphs

As explained above, `<p>` elements are for containing paragraphs of text; you'll use these frequently when marking up regular text content:

```html

This is a single paragraph

```

Add your sample text (you should have it from *What will your website look like?*) into one or a few paragraphs, placed directly below your `<img>` element.

### Lists

A lot of the web's content is lists and HTML has special elements for these. Marking up lists always consists of at least 2 elements. The most common list types are ordered and unordered lists:

1. **Unordered lists** are for lists where the order of the items doesn't matter, such as a shopping list. These are wrapped in a `<ul>` element.
2. **Ordered lists** are for lists where the order of the items does matter, such as a recipe. These are wrapped in an `<ol>` element.

Each item inside the lists is put inside an `<li>` (list item) element.

For example, if we wanted to turn the part of the following paragraph fragment into a list

```html

  At Mozilla, we're a global community of technologists, thinkers, and builders
  working together…

```

We could modify the markup to this

```html

At Mozilla, we're a global community of

technologists

thinkers

builders

working together…

```

Try adding an ordered or unordered list to your example page.

Links
-----

Links are very important — they are what makes the web a web! To add a link, we need to use a simple element — `<a>` — "a" being the short form for "anchor". To make text within your paragraph into a link, follow these steps:

1. Choose some text. We chose the text "Mozilla Manifesto".
2. Wrap the text in an `<a>` element, as shown below:

```html
Mozilla Manifesto
```

3. Give the `<a>` element an `href` attribute, as shown below:

```html
Mozilla Manifesto
```

4. Fill in the value of this attribute with the web address that you want the link to:

```html

  Mozilla Manifesto

```

You might get unexpected results if you omit the `https://` or `http://` part, called the *protocol*, at the beginning of the web address. After making a link, click it to make sure it is sending you where you wanted it to.

**Note:** `href` might appear like a rather obscure choice for an attribute name at first. If you are having trouble remembering it, remember that it stands for ***h**ypertext **ref**erence*.

Add a link to your page now, if you haven't already done so.

Conclusion
----------

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

![A web page screenshot showing a Firefox logo, a heading saying Mozilla is cool, and two paragraphs of filler text](/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics/finished-test-page-small.png)

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

Here, we have only really scratched the surface of HTML. To find out more, go to our Learning HTML topic.

* Previous
* Overview: Getting started with the web
* Next


CSS basics - Learn web development

CSS basics
==========

* Previous
* Overview: Getting started with the web
* Next

CSS (Cascading Style Sheets) is the code that styles web content. *CSS basics* walks through what you need to get started. We'll answer questions like: How do I make text red? How do I make content display at a certain location in the (webpage) layout? How do I decorate my webpage with background images and colors?

What is CSS?
------------

Like HTML, CSS is not a programming language. It's not a markup language either. **CSS is a style sheet language.** CSS is what you use to selectively style HTML elements. For example, this CSS selects paragraph text, setting the color to red:

```css
p {
  color: red;
}
```

Let's try it out! Using a text editor, paste the three lines of CSS (above) into a new file. Save the file as `style.css` in a directory named `styles`.

To make the code work, we still need to apply this CSS (above) to your HTML document. Otherwise, the styling won't change the appearance of the HTML. (If you haven't been following our project, pause here to read Dealing with files and HTML basics.)

1. Open your `index.html` file. Paste the following line in the head (between the `<head>` and `</head>` tags):

```html
<link href="styles/style.css" rel="stylesheet" />
```

2. Save `index.html` and load it in your browser. You should see something like this:

![A Mozilla logo and some paragraphs. The paragraph text has been styled red by our css.](/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics/website-screenshot-styled.png)If your paragraph text is red, congratulations! Your CSS is working.

### Anatomy of a CSS ruleset

Let's dissect the CSS code for red paragraph text to understand how it works:

![CSS p declaration color red](/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics/css-declaration-small.png)

The whole structure is called a **ruleset**. (The term *ruleset* is often referred to as just *rule*.) Note the names of the individual parts:

Selector

This is the HTML element name at the start of the ruleset. It defines the element(s) to be styled (in this example, `<p>` elements). To style a different element, change the selector.

Declaration

This is a single rule like `color: red;`. It specifies which of the element's **properties** you want to style.

Properties

These are ways in which you can style an HTML element. (In this example, `color` is a property of the `<p>` elements.) In CSS, you choose which properties you want to affect in the rule.

Property value

To the right of the property—after the colon—there is the **property value**. This chooses one out of many possible appearances for a given property. (For example, there are many `color` values in addition to `red`.)

Note the other important parts of the syntax:

* Apart from the selector, each ruleset must be wrapped in curly braces. (`{}`)
* Within each declaration, you must use a colon (`:`) to separate the property from its value or values.
* Within each ruleset, you must use a semicolon (`;`) to separate each declaration from the next one.

To modify multiple property values in one ruleset, write them separated by semicolons, like this:

```css
p {
  color: red;
  width: 500px;
  border: 1px solid black;
}
```

### Selecting multiple elements

You can also select multiple elements and apply a single ruleset to all of them. Separate multiple selectors by commas. For example:

```css
p,
li,
h1 {
  color: red;
}
```

### Different types of selectors

There are many different types of selectors. The examples above use **element selectors**, which select all elements of a given type. But we can make more specific selections as well. Here are some of the more common types of selectors:

| Selector name | What does it select | Example |
| --- | --- | --- |
| Element selector (sometimes called a tag or type selector) | All HTML elements of the specified type. | `p`selects `<p>` |
| ID selector |
 The element on the page with the specified ID. On a given HTML page,
 each id value should be unique.
  | `#my-id`selects `<p id="my-id">` or
 `<a id="my-id">` |
| Class selector |
 The element(s) on the page with the specified class. Multiple instances
 of the same class can appear on a page.
  | `.my-class`selects
 `<p class="my-class">` and
 `<a class="my-class">` |
| Attribute selector | The element(s) on the page with the specified attribute. | `img[src]`selects
 `<img src="myimage.png">` but not
 `<img>` |
| Pseudo-class selector |
 The specified element(s), but only when in the specified state. (For
 example, when a cursor hovers over a link.)
  | `a:hover`selects `<a>`, but only when
 the mouse pointer is hovering over the link.
  |

There are many more selectors to discover. To learn more, see the MDN Selectors guide.

Fonts and text
--------------

Now that we've explored some CSS fundamentals, let's improve the appearance of the example by adding more rules and information to the `style.css` file.

1. First, find the output from Google Fonts that you previously saved from What will your website look like?. Add the `<link>` element somewhere inside your `index.html`'s head (anywhere between the `<head>` and `</head>` tags). It looks something like this:

```html
<link
 href="https://fonts.googleapis.com/css?family=Open+Sans"
 rel="stylesheet" />
```

This code links your page to a style sheet that loads the Open Sans font family with your webpage.
2. Next, delete the existing rule you have in your `style.css` file. It was a good test, but let's not continue with lots of red text.
3. Add the following lines (shown below), replacing the `font-family` assignment with your `font-family` selection from What will your website look like?. The property `font-family` refers to the font(s) you want to use for text. This rule defines a global base font and font size for the whole page. Since `<html>` is the parent element of the whole page, all elements inside it inherit the same `font-size` and `font-family`.

```css
html {
  font-size: 10px; /\* px means "pixels": the base font size is now 10 pixels high \*/
  font-family: "Open Sans", sans-serif; /\* this should be the rest of the output you got from Google Fonts \*/
}
```

**Note:** Anything in CSS between `/*` and `*/` is a **CSS comment**. The browser ignores comments as it renders the code. CSS comments are a way for you to write helpful notes about your code or logic.
4. Now let's set font sizes for elements that will have text inside the HTML body (<h1>, `<li>`, and `<p>`). We'll also center the heading. Finally, let's expand the second ruleset (below) with settings for line height and letter spacing to make body content more readable.

```css
h1 {
  font-size: 60px;
  text-align: center;
}

p,
li {
  font-size: 16px;
  line-height: 2;
  letter-spacing: 1px;
}
```

Adjust the `px` values as you like. Your work-in-progress should look similar to this:

![A Mozilla logo and some paragraphs. A sans-serif font has been set, the font sizes, line height and letter spacing are adjusted, and the main page heading has been centered](/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics/website-screenshot-font-small.png)

CSS: all about boxes
--------------------

Something you'll notice about writing CSS: a lot of it is about boxes. This includes setting size, color, and position. Most HTML elements on your page can be thought of as boxes sitting on top of other boxes.

![A big stack of boxes or crates sat on top of one another](/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics/boxes.jpg)

Photo from https://www.geograph.org.uk/photo/3418115 Copyright © Jim Barton cc-by-sa/2.0

CSS layout is mostly based on the *box model.* Each box taking up space on your page has properties like:

* `padding`, the space around the content. In the example below, it is the space around the paragraph text.
* `border`, the solid line that is just outside the padding.
* `margin`, the space around the outside of the border.

![Three boxes sat inside one another. From outside to in they are labelled margin, border and padding](/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics/box-model.png)

In this section we also use:

* `width` (of an element).
* `background-color`, the color behind an element's content and padding.
* `color`, the color of an element's content (usually text).
* `text-shadow` sets a drop shadow on the text inside an element.
* `display` sets the display mode of an element. (keep reading to learn more)

To continue, let's add more CSS. Keep adding these new rules at the bottom of `style.css`. Experiment with changing values to see what happens.

### Changing the page color

```css
html {
  background-color: #00539f;
}
```

This rule sets a background color for the entire page. Change the color code to the color you chose in What will my website look like?.

### Styling the body

```css
body {
  width: 600px;
  margin: 0 auto;
  background-color: #ff9500;
  padding: 0 20px 20px 20px;
  border: 5px solid black;
}
```

There are several declarations for the `<body>` element. Let's go through these line-by-line:

* `width: 600px;` This forces the body to always be 600 pixels wide.
* `margin: 0 auto;` When you set two values on a property like `margin` or `padding`, the first value affects the element's top *and* bottom side (setting it to `0` in this case); the second value affects the left *and* right side. (Here, `auto` is a special value that divides the available horizontal space evenly between left and right). You can also use one, two, three, or four values, as documented in Margin Syntax.
* `background-color: #FF9500;` This sets the element's background color. This project uses a reddish orange for the body background color, as opposed to dark blue for the `<html>` element. (Feel free to experiment.)
* `padding: 0 20px 20px 20px;` This sets four values for padding. The goal is to put some space around the content. In this example, there is no padding on the top of the body, and 20 pixels on the right, bottom and left. The values set top, right, bottom, left, in that order. As with `margin`, you can use one, two, three, or four values, as documented in Padding Syntax.
* `border: 5px solid black;` This sets values for the width, style and color of the border. In this case, it's a five-pixel–wide, solid black border, on all sides of the body.
### Positioning and styling the main page title

```css
h1 {
  margin: 0;
  padding: 20px 0;
  color: #00539f;
  text-shadow: 3px 3px 1px black;
}
```

You may have noticed there's a horrible gap at the top of the body. That happens because browsers apply default styling to the h1 element (among others). That might seem like a bad idea, but the intent is to provide basic readability for unstyled pages. To eliminate the gap, we overwrite the browser's default styling with the setting `margin: 0;`.

Next, we set the heading's top and bottom padding to 20 pixels.

Following that, we set the heading text to be the same color as the HTML background color.

Finally, `text-shadow` applies a shadow to the text content of the element. Its four values are:

* The first pixel value sets the **horizontal offset** of the shadow from the text: how far it moves across.
* The second pixel value sets the **vertical offset** of the shadow from the text: how far it moves down.
* The third pixel value sets the **blur radius** of the shadow. A larger value produces a more fuzzy-looking shadow.
* The fourth value sets the base color of the shadow.

Try experimenting with different values to see how it changes the appearance.

### Centering the image

```css
img {
  display: block;
  margin: 0 auto;
}
```

Next, we center the image to make it look better. We could use the `margin: 0 auto` trick again as we did for the body. But there are differences that require an additional setting to make the CSS work.

The `<body>` is a **block** element, meaning it takes up space on the page. The margin applied to a block element will be respected by other elements on the page. In contrast, images are **inline** elements, for the auto margin trick to work on this image, we must give it block-level behavior using `display: block;`.

**Note:** The instructions above assume that you're using an image smaller than the width set on the body. (600 pixels) If your image is larger, it will overflow the body, spilling into the rest of the page. To fix this, you can either: 1) reduce the image width using a graphics editor, or 2) use CSS to size the image by setting the `width` property on the `<img>` element with a smaller value.

**Note:** Don't be too concerned if you don't completely understand `display: block;` or the differences between a block element and an inline element. It will make more sense as you continue your study of CSS. You can find more information about different display values on MDN's display reference page.

Conclusion
----------

If you followed all the instructions in this article, you should have a page that looks similar to this one:

![A Mozilla logo, centered, and a header and paragraphs. It now looks nicely styled, with a blue background for the whole page and orange background for the centered main content strip.](/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics/website-screenshot-final.png)

(You can view our version here.) If you get stuck, you can always compare your work with our finished example code on GitHub.

In this exercise, we have just scratched the surface of CSS. To go further, see Learning to style HTML using CSS.

* Previous
* Overview: Getting started with the web
* Next


The web and web standards - Learn web development

The web and web standards
=========================

This article provides some useful background on the Web — how it came about, what web standard technologies are, how they work together, why "web developer" is a great career to choose, and what kinds of best practices you'll learn about through the course.

Brief history of the web
------------------------

We'll keep this very brief, as there are many (more) detailed accounts of the web's history out there, which we'll link to later on (also try searching for "history of the web" in your favorite search engine and see what you get, if you are interested in more detail.)

In the late 1960s, the US military developed a communication network called ARPANET. This can be considered a forerunner of the Web, as it worked on packet switching, and featured the first implementation of the TCP/IP protocol suite. These two technologies form the basis of the infrastructure that the internet is built on.

In 1980, Tim Berners-Lee (often referred to as TimBL) wrote a notebook program called ENQUIRE, which featured the concept of links between different nodes. Sound familiar?

Fast forward to 1989, and TimBL wrote Information Management: A Proposal and HyperText at CERN; these two publications together provided the background for how the web would work. They received a fair amount of interest, enough to convince TimBL's bosses to allow him to go ahead and create a global hypertext system.

By late 1990, TimBL had created all the things needed to run the first version of the web — HTTP, HTML, the first web browser, which was called WorldWideWeb, an HTTP server, and some web pages to look at.

In the next few years that followed, the web exploded, with multiple browsers being released, thousands of web servers being set up, and millions of web pages being created. OK, that's a very simple summary of what happened, but we did promise you a brief summary.

One last significant data point to share is that in 1994, TimBL founded the World Wide Web Consortium (W3C), an organization that brings together representatives from many different technology companies to work together on the creation of web technology specifications. After that other technologies followed such as CSS and JavaScript, and the web started to look more like the web we know today.

Web standards
-------------

**Web standards** are the technologies we use to build websites. These standards exist as long technical documents called specifications, which detail exactly how the technology should work. These documents are not very useful for learning how to use the technologies they describe (this is why we have sites like MDN Web Docs), but instead are intended to be used by software engineers to implement these technologies (usually in web browsers).

For example, the HTML Living Standard describes exactly how HTML (all the HTML elements, and their associated APIs, and other surrounding technologies) should be implemented.

Web standards are created by standards bodies — institutions that invite groups of people from different technology companies to come together and agree on how the technologies should work in the best way to fulfill all of their use cases. The W3C is the best known web standards body, but there are others such as the WHATWG (who maintain the living standards for the HTML language), ECMA (who publish the standard for ECMAScript, which JavaScript is based on), Khronos (who publish technologies for 3D graphics, such as WebGL), and others.

### "Open" standards

One of the key aspects of web standards, which TimBL and the W3C agreed on from the start, is that the web (and web technologies) should be free to both contribute and use, and not encumbered by patents/licensing. Therefore anyone can write the code to build a website for free, and anyone can contribute to the standards creation process, where the specs are written.

Because web technologies are created openly, in collaboration between many different companies, it means that no one company gets to control them, which is a really good thing. You wouldn't want a single company suddenly deciding to put the entire web behind a paywall, or releasing a new version of HTML that everyone has to buy to continue making websites, or worse still, just deciding they aren't interested any more and just turning it off.

This allows the web to remain a freely-available public resource.

### Don't break the web

Another phrase you'll hear around open web standards is "don't break the web" — the idea is that any new web technology that is introduced should be backwards compatible with what went before it (i.e. old websites will still continue to work), and forwards compatible (future technologies in turn will be compatible with what we currently have). As you go through the learning material presented here, you'll start to learn how this is made possible with some very clever design and implementation work.

Being a web developer is good
-----------------------------

The web industry is a very attractive market to enter if you are looking for a job. Recent published figures say that there are currently around 19 million web developers in the world, and that figure is set more than double in the next decade. And at the same time, there is a skill shortage in the industry — so what better time to learn web development?

It isn't all fun and games however — building websites is a more complicated proposition than it used to be, and you'll have to put some time in to studying all the different technologies you need to use, all the techniques and best practices you need to know, and all the typical patterns you'll be called upon to implement. It'll take you a few months to really start to get into it, and then you'll need to keep learning so that your knowledge stays up-to-date with all the new tools and features that appear on the web platform, and keep practicing and refining your craft.

*The only constant is change.*

Does this sound hard? Don't worry — we aim to give you everything you need to know to get started, and things will get easier. Once you embrace the constant change and uncertainty of the web, you'll start to enjoy yourself. As a part of the web community, you'll have an entire web of contacts and useful material to help you, and you'll start to enjoy the creative possibilities it brings.

You're a digital creative now. Enjoy the experience, and the potential for earning a living.

Overview of modern web technologies
-----------------------------------

There are a number of technologies to learn if you want to be a front-end web developer. In this section we will describe them briefly. For a more detailed explanation of how some of them work together, read our article How the web works.

### Browsers

You are probably reading these words inside a web browser in this very moment (unless you've printed it out, or are using assistive technology, such as a screen reader to read it out to you). Web browsers are the software programs people use to consume the web, and include Firefox, Chrome, Opera, Safari, and Edge.

### HTTP

Hypertext Transfer Protocol, or HTTP, is a messaging protocol that allows web browsers to communicate with web servers (where websites are stored). A typical conversation goes something like
```

"Hello web server. Can you give me the files I need to render bbc.co.uk"?

"Sure thing web browser — here you go"

[Downloads files and renders web page]
```

The actual syntax for HTTP messages (called requests and responses) is not that human-readable, but this gives you the basic idea.

### HTML, CSS, and JavaScript

HTML, CSS, and JavaScript are the main three technologies you'll use to build a website:

* HyperText Markup Language, or **HTML**, is a markup language consisting of different elements you can wrap (mark up) content in to give it meaning (semantics) and structure. Simple HTML looks like this:

```html
<h1>This is a top-level heading</h1>

<p>This is a paragraph of text.</p>

<img src="cat.jpg" alt="A picture of my cat" />
```

If we adopted a house-building analogy, HTML would be like the foundations and walls of the house, which give it structure and hold it together.
* Cascading Style Sheets (**CSS**) is a rule-based language used to apply styles to your HTML — for example, setting text and background colors, adding borders, animating things, or laying out a page in a certain way. As a simple example, the following code would turn our HTML paragraph red:

```css
p {
  color: red;
}
```

In the house analogy, CSS is like the paint, wallpaper, carpets and paintings you'd use to make the house look nice.
* **JavaScript** is the programming language we use to add interactivity to websites, from dynamic style switching, to fetching updates from the server, right through to complex 3D graphics. The following simple JavaScript will store a reference to our paragraph in memory and change the text inside it:

```js
let pElem = document.querySelector("p");
pElem.textContent = "We changed the text!";
```

In the house analogy, JavaScript is like the cooker, TV, Microwave, or hairdryer — the things that give your house useful functionality.
### Tools

Once you've learned the "raw" technologies that can be used to build web pages (such as HTML, CSS, and JavaScript), you'll soon start to come across various tools that can be used to make your work easier or more efficient. Examples include:

* The developer tools inside modern browsers that can be used to debug your code.
* Testing tools that can be used to run tests to show whether your code is behaving as you intended it to.
* Libraries and frameworks built on top of JavaScript that allow you to build certain types of website much more quickly and effectively.
* So-called "Linters", which take a set of rules, look at your code, and highlight places where you haven't followed the rules properly.
* Minifiers, which remove all the whitespace from your code files to make it so that they are smaller and therefore download from the server more quickly.
### Server-side languages and frameworks

HTML, CSS, and JavaScript are front-end (or client-side) languages, which means they are run by the browser to produce a website front-end that your users can use.

There are another class of languages called back-end (or server-side) languages, meaning that they are run on the server before the result is then sent to the browser to be displayed. A typical use for a server-side language is to get some data out of a database and generate some HTML to contain the data, before then sending the HTML over to the browser to display it to the user.

Example server-side frameworks include ASP.NET (in C#), Django (in Python), Laravel (in PHP), and Next.js (in JavaScript).

Web best practices
------------------

We have briefly talked about the technologies that you'll use to build websites. Now let's discuss the best practices you should employ to make sure you are using those technologies in the best way that you can.

When doing web development, the main cause of uncertainty comes from the fact that you don't know what combination of technology each user will use to view your website:

* User 1 might be looking at it on an iPhone, with a small, narrow screen.
* User 2 might be looking at it on a Windows laptop with a widescreen monitor attached to it.
* User 3 might be blind, and using a screen reader to read the web page out to them.
* User 4 might be using a really old desktop machine that can't run modern browsers.

Because you don't know exactly what your users will use, you need to design defensively — make your website as flexible as possible, so that all of the above users can make use of it, even if they might not all get the same experience. In short, we are trying to make the web work for all, as much as possible.

You'll come across the below concepts at some point in your studies.

* **Cross-browser compatibility** is the practice of trying to make sure your webpage works across as many devices as possible. This includes using technologies that all the browsers support, delivering better experiences to browsers that can handle them (progressive enhancement), and/or writing code so that it falls back to a simpler but still usable experience in older browsers (graceful degradation). It also involves a lot of testing to see if anything fails in certain browsers, and then more work to fix those failures.
* **Responsive web design** is the practice of making your functionality and layouts flexible so they can automatically adapt to different browsers. An obvious example is a website that is laid out one way in a widescreen browser on the desktop, but displays as a more compact, single-column layout on mobile phone browsers. Try adjusting the width of your browser window now, and see what happens.
* **Performance** means getting websites to load as quickly as possible, but also making them intuitive and easy to use so that users don't get frustrated and go somewhere else.
* **Accessibility** means making your websites usable by as many different kinds of people as possible (related concepts are diversity and inclusion, and inclusive design). This includes people with visual impairments, hearing impairments, cognitive disabilities, or physical disabilities. It also goes beyond people with disabilities — how about young or old people, people from different cultures, people using mobile devices, or people with unreliable or slow network connections?
* **Internationalization** means making websites usable by people from different cultures, who speak different languages to your own. There are technical considerations here (such as altering your layout so that it still works OK for right-to-left, or even vertical languages), and human ones (such as using simple, non-slang language so that people who have your language as their second or third language are more likely to understand your text).
* **Privacy & Security**. These two concepts are related but different. Privacy refers to allowing people to go about their business privately and not spying on them or collecting more of their data than you absolutely need to. Security refers to constructing your website in a secure way so that malicious users cannot steal information contained on it from you or your users.
See also
--------

* History of the World Wide Web
* How does the internet work?


JavaScript basics - Learn web development

JavaScript basics
=================

* Previous
* Overview: Getting started with the web
* Next

 JavaScript is a programming language that adds interactivity to your website. This happens in games, in the behavior of responses when buttons are pressed or with data entry on forms; with dynamic styling; with animation, etc.
 This article helps you get started with JavaScript and furthers your understanding of what is possible.

What is JavaScript?
-------------------

JavaScript is a powerful programming language that can add interactivity to a website.
 It was invented by Brendan Eich.

 JavaScript is versatile and beginner-friendly.
 With more experience, you'll be able to create games, animated 2D and 3D graphics, comprehensive database-driven apps, and much more!

JavaScript itself is relatively compact, yet very flexible. Developers have written a variety of tools on top of the core JavaScript language, unlocking a vast amount of functionality with minimum effort. These include:

* Browser Application Programming Interfaces (APIs) built into web browsers, providing functionality such as dynamically creating HTML and setting CSS styles; collecting and manipulating a video stream from a user's webcam, or generating 3D graphics and audio samples.
* Third-party APIs that allow developers to incorporate functionality in sites from other content providers, such as Twitter or Facebook.
* Third-party frameworks and libraries that you can apply to HTML to accelerate the work of building sites and applications.

It's outside the scope of this article—as a light introduction to JavaScript—to present the details of how the core JavaScript language is different from the tools listed above. You can learn more in MDN's JavaScript learning area, as well as in other parts of MDN.

The section below introduces some aspects of the core language and offers an opportunity to play with a few browser API features too. Have fun!

A "Hello world!" example
------------------------

JavaScript is one of the most popular modern web technologies! As your JavaScript skills grow, your websites will enter a new dimension of power and creativity.

However, getting comfortable with JavaScript is more challenging than getting comfortable with HTML and CSS. You may have to start small, and progress gradually. To begin, let's examine how to add JavaScript to your page for creating a *Hello world!* example. (*Hello world!* is the standard for introductory programming examples.)

**Warning:** If you haven't been following along with the rest of our course, download this example code and use it as a starting point.

1. Go to your test site and create a new folder named `scripts`. Within the scripts folder, create a new text document called `main.js`, and save it.
2. In your `index.html` file, enter this code on a new line, just before the closing `</body>` tag:

```html
<script src="scripts/main.js"></script>
```

3. This is doing the same job as the `<link>` element for CSS. It applies the JavaScript to the page, so it can have an effect on the HTML (along with the CSS, and anything else on the page).
4. Add this code to the `main.js` file:

```js
const myHeading = document.querySelector("h1");
myHeading.textContent = "Hello world!";
```

5. Make sure the HTML and JavaScript files are saved. Then load `index.html` in your browser. You should see something like this:

![Heading "hello world" above a firefox logo](/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics/hello-world.png)

**Note:** The reason the instructions (above) place the `<script>` element near the bottom of the HTML file is that **the browser reads code in the order it appears in the file**.

If the JavaScript loads first and it is supposed to affect the HTML that hasn't loaded yet, there could be problems. Placing JavaScript near the bottom of an HTML page is one way to accommodate this dependency. To learn more about alternative approaches, see Script loading strategies.

### What happened?

The heading text changed to *Hello world!* using JavaScript. You did this by using a function called `querySelector()` to grab a reference to your heading, and then store it in a variable called `myHeading`. This is similar to what we did using CSS selectors. When you want to do something to an element, you need to select it first.

Following that, the code set the value of the `myHeading` variable's `textContent` property (which represents the content of the heading) to *Hello world!*.

**Note:** Both of the features you used in this exercise are parts of the Document Object Model (DOM) API, which has the capability to manipulate documents.

Language basics crash course
----------------------------

To give you a better understanding of how JavaScript works, let's explain some of the core features of the language. It's worth noting that these features are common to all programming languages. If you master these fundamentals, you have a head start on coding in other languages too!

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

### Variables

Variables are containers that store values. You start by declaring a variable with the `let` keyword, followed by the name you give to the variable:

```js
let myVariable;
```

A semicolon at the end of a line indicates where a statement ends. It is only required when you need to separate statements on a single line. However, some people believe it's good practice to have semicolons at the end of each statement. There are other rules for when you should and shouldn't use semicolons. For more details, see Your Guide to Semicolons in JavaScript.

You can name a variable nearly anything, but there are some restrictions. (See this section about naming rules.) If you are unsure, you can check your variable name to see if it's valid.

JavaScript is case sensitive. This means `myVariable` is not the same as `myvariable`. If you have problems in your code, check the case!

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

```js
myVariable = "Bob";
```

Also, you can do both these operations on the same line:

```js
let myVariable = "Bob";
```

You retrieve the value by calling the variable name:

```js
myVariable;
```

After assigning a value to a variable, you can change it later in the code:

```js
let myVariable = "Bob";
myVariable = "Steve";
```

Note that variables may hold values that have different data types:

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

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

### Comments

Comments are snippets of text that can be added along with code. The browser ignores text marked as comments. You can write comments in JavaScript just as you can in CSS:

```js
/\*
Everything in between is a comment.
\*/
```

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

```js
// This is a comment
```

### Operators

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

| Operator | Explanation | Symbol(s) | Example |
| --- | --- | --- | --- |
| Addition | Add two numbers together or combine two strings. | `+` | `6 + 9;'Hello ' + 'world!';` |
| Subtraction, Multiplication, Division | These do what you'd expect them to do in basic math. | `-`, `*`, `/` | `9 - 3;8 * 2; // multiply in JS is an asterisk9 / 3;` |
| Assignment | As you've seen already: this assigns a value to a variable. | `=` | `let myVariable = 'Bob';` |
| Strict equality |
 This performs a test to see if two values are equal and of the same data type. It returns a
 `true`/`false` (Boolean) result.
  | `===` | `let myVariable = 3;myVariable === 4;` |
| Not, Does-not-equal |
 This returns the logically opposite value of what it precedes. It turns
 a `true` into a `false`, etc.. When it is used
 alongside the Equality operator, the negation operator tests whether two
 values are *not* equal.
  | `!`, `!==` |
 For "Not", the basic expression is `true`, but the
 comparison returns `false` because we negate it:

`let myVariable = 3;!(myVariable === 3);`

 "Does-not-equal" gives basically the same result with different
 syntax. Here we are testing "is `myVariable` NOT equal to
 3". This returns `false` because `myVariable` IS
 equal to 3:

`let myVariable = 3;myVariable !== 3;` |

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

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

### Conditionals

Conditionals are code structures used to test if an expression returns true or not. A very common form of conditionals is the `if...else` statement. For example:

```js
let iceCream = "chocolate";
if (iceCream === "chocolate") {
  alert("Yay, I love chocolate ice cream!");
} else {
  alert("Awwww, but chocolate is my favorite…");
}
```

The expression inside the `if ()` is the test. This uses the strict equality operator (as described above) to compare the variable `iceCream` with the string `chocolate` to see if the two are equal. If this comparison returns `true`, the first block of code runs. If the comparison is not true, the second block of code—after the `else` statement—runs instead.

### Functions

Functions are a way of packaging functionality that you wish to reuse. It's possible to define a body of code as a function that executes when you call the function name in your code. This is a good alternative to repeatedly writing the same code. You have already seen some uses of functions. For example:

```js
let myVariable = document.querySelector("h1");
```

```js
alert("hello!");
```

These functions, `document.querySelector` and `alert`, are built into the browser.

If you see something which looks like a variable name, but it's followed by parentheses— `()` —it is likely a function. Functions often take arguments: bits of data they need to do their job. Arguments go inside the parentheses, separated by commas if there is more than one argument.

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

You can also define your own functions. In the next example, we create a simple function which takes two numbers as arguments and multiplies them:

```js
function multiply(num1, num2) {
  let result = num1 \* num2;
  return result;
}
```

Try running this in the console; then test with several arguments. For example:

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

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

### Events

Real interactivity on a website requires event handlers. These are code structures that listen for activity in the browser, and run code in response. The most obvious example is handling the click event, which is fired by the browser when you click on something with your mouse. To demonstrate this, enter the following into your console, then click on the current webpage:

```js
document.querySelector("html").addEventListener("click", function () {
  alert("Ouch! Stop poking me!");
});
```

 There are a number of ways to attach an event handler to an element.
 Here we select the `<html>` element. We then call its `addEventListener()` function, passing in the name of the event to listen to (`'click'`) and a function to run when the event happens.

 The function we just passed to `addEventListener()` here is called an *anonymous function*, because it doesn't have a name. There's an alternative way of writing anonymous functions, which we call an *arrow function*.
 An arrow function uses `() =>` instead of `function ()`:

```js
document.querySelector("html").addEventListener("click", () => {
  alert("Ouch! Stop poking me!");
});
```

Supercharging our example website
---------------------------------

With this review of JavaScript basics completed (above), let's add some new features to our example site.

Before going any further, delete the current contents of your `main.js` file — the bit you added earlier during the "Hello world!" example — and save the empty file. If you don't, the existing code will clash with the new code you are about to add.

### Adding an image changer

In this section, you will learn how to use JavaScript and DOM API features to alternate the display of one of two images. This change will happen as a user clicks the displayed image.

1. Choose an image you want to feature on your example site. Ideally, the image will be the same size as the image you added previously, or as close as possible.
2. Save this image in your `images` folder.
3. Rename the image *firefox2.png*.
4. Add the following JavaScript code to your `main.js` file.

```js
const myImage = document.querySelector("img");

myImage.onclick = () => {
  const mySrc = myImage.getAttribute("src");
  if (mySrc === "images/firefox-icon.png") {
    myImage.setAttribute("src", "images/firefox2.png");
  } else {
    myImage.setAttribute("src", "images/firefox-icon.png");
  }
};
```

5. Save all files and load `index.html` in the browser. Now when you click the image, it should change to the other one.

This is what happened. You stored a reference to your `<img>` element in `myImage`. Next, you made its `onclick` event handler property equal to a function with no name (an "anonymous" function). So every time this element is clicked:

1. The code retrieves the value of the image's `src` attribute.
2. The code uses a conditional to check if the `src` value is equal to the path of the original image:
    1. If it is, the code changes the `src` value to the path of the second image, forcing the other image to be loaded inside the `<img>` element.
    2. If it isn't (meaning it must already have changed), the `src` value swaps back to the original image path, to the original state.
### Adding a personalized welcome message

Next, let's change the page title to a personalized welcome message when the user first visits the site. This welcome message will persist. Should the user leave the site and return later, we will save the message using the Web Storage API. We will also include an option to change the user, and therefore, the welcome message.

1. In `index.html`, add the following line just before the `<script>` element:

```html
<button>Change user</button>
```

2. In `main.js`, place the following code at the bottom of the file, exactly as it is written. This takes references to the new button and the heading, storing each inside variables:

```js
let myButton = document.querySelector("button");
let myHeading = document.querySelector("h1");
```

3. Add the following function to set the personalized greeting. This won't do anything yet, but this will change soon.

```js
function setUserName() {
  const myName = prompt("Please enter your name.");
  localStorage.setItem("name", myName);
  myHeading.textContent = `Mozilla is cool, ${myName}`;
}
```

The `setUserName()` function contains a `prompt()` function, which displays a dialog box, similar to `alert()`. This `prompt()` function does more than `alert()`, asking the user to enter data, and storing it in a variable after the user clicks *OK.* In this case, we are asking the user to enter a name. Next, the code calls on an API `localStorage`, which allows us to store data in the browser and retrieve it later. We use localStorage's `setItem()` function to create and store a data item called `'name'`, setting its value to the `myName` variable which contains the user's entry for the name. Finally, we set the `textContent` of the heading to a string, plus the user's newly stored name.
4. Add the following condition block. We could call this initialization code, as it structures the app when it first loads.

```js
if (!localStorage.getItem("name")) {
  setUserName();
} else {
  const storedName = localStorage.getItem("name");
  myHeading.textContent = `Mozilla is cool, ${storedName}`;
}
```

This first line of this block uses the negation operator (logical NOT, represented by the `!`) to check whether the `name` data exists. If not, the `setUserName()` function runs to create it. If it exists (that is, the user set a user name during a previous visit), we retrieve the stored name using `getItem()` and set the `textContent` of the heading to a string, plus the user's name, as we did inside `setUserName()`.
5. Put this `onclick` event handler (below) on the button. When clicked, `setUserName()` runs. This allows the user to enter a different name by pressing the button.

```js
myButton.onclick = () => {
  setUserName();
};
```

### A user name of null?

When you run the example and get the dialog box that prompts you to enter your user name, try pressing the *Cancel* button. You should end up with a title that reads *Mozilla is cool, null*. This happens because—when you cancel the prompt—the value is set as `null`. *Null* is a special value in JavaScript that refers to the absence of a value.

Also, try clicking *OK* without entering a name. You should end up with a title that reads *Mozilla is cool,* for fairly obvious reasons.

To avoid these problems, you could check that the user hasn't entered a blank name. Update your `setUserName()` function to this:

```js
function setUserName() {
  const myName = prompt("Please enter your name.");
  if (!myName) {
    setUserName();
  } else {
    localStorage.setItem("name", myName);
    myHeading.textContent = `Mozilla is cool, ${myName}`;
  }
}
```

In human language, this means: If `myName` has no value, run `setUserName()` again from the start. If it does have a value (if the above statement is not true), then store the value in `localStorage` and set it as the heading's text.

Conclusion
----------

If you have followed all the instructions in this article, you should end up with a page that looks something like the image below. You can also view our version.

![Final look of HTML page after creating elements: a header, large centered logo, content, and a button](/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics/website-screen-scripted.png)

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

We have just scratched the surface of JavaScript. If you enjoyed playing, and wish to go further, take advantage of the resources listed below.

See also
--------

Dynamic client-side scripting with JavaScript

Dive into JavaScript in much more detail.

Learn JavaScript

This is an excellent resource for aspiring web developers! Learn JavaScript in an interactive environment, with short lessons and interactive tests, guided by an automated assessment. The first 40 lessons are free. The complete course is available for a small one-time payment.

* Previous
* Overview: Getting started with the web
* Next


Publishing your website - Learn web development

Publishing your website
=======================

* Previous
* Overview: Getting started with the web
* Next

Once you finish writing the code and organizing the files that make up your website, you need to put it all online so people can find it. This article explains how to get your simple sample code online with little effort.

What are the options?
---------------------

Publishing a website is a complex topic because there are many ways to go about it. This article doesn't attempt to document all the possible methods. Instead, it explains the advantages and disadvantages of three approaches that are practical for beginners. Then it steps through one method that can work right away for many readers.

### Getting hosting and a domain name

To have more control over content and website appearance, most people choose to buy web hosting and a domain name:

* Web hosting is rented file space on a hosting company's web server. You put website files on the web server. The web server provides website content to website visitors.
* A domain name is the unique address where people find your website, such as `https://www.mozilla.org` or `https://www.bbc.co.uk`. You can rent your domain name for as many years as you want from a **domain registrar**.

Many professional websites go online this way.

In addition, you will need a File Transfer Protocol (FTP) program (see How much does it cost: software for more details) to actually transfer the website files over to the server. FTP programs vary widely, but generally, you have to connect to your web server using details provided by your hosting company (typically username, password, hostname). Then the program shows you your local files and the web server's files in two windows, and provides a way for you to transfer files back and forth.

![An FTP client showing all files and folders of a website and uploading them to a server](/en-US/docs/Learn/Getting_started_with_the_web/Publishing_your_website/ftp.jpg)

#### Tips for finding hosting and domains

* MDN does not promote specific commercial hosting companies or domain name registrars. To find hosting companies and registrars, just search for "web hosting" and "domain names". All registrars will have a feature to allow you to check if the domain name you want is available.
* Your home or office internet service provider may provide some limited hosting for a small website. The available feature set will be limited, but it might be perfect for your first experiments.
* There are also free services available like Neocities, Google Sites, Blogger, and WordPress. Sometimes you get what you pay for, but sometimes these resources are good enough for your initial experiments.
* Many companies provide hosting and domains.
### Using an online tool like GitHub or Google App Engine

Some tools let you publish your website online:

* GitHub is a "social coding" site. It allows you to upload code repositories for storage in the Git **version control system.** You can then collaborate on code projects, and the system is open-source by default, meaning that anyone in the world can find your GitHub code, use it, learn from it, and improve on it. GitHub has a very useful feature called GitHub Pages, which allows you to expose website code live on the web.
* Google App Engine is a powerful platform that lets you build and run applications on Google's infrastructure — whether you need to build a multi-tiered web application from scratch or host a static website. See How do you host your website on Google App Engine? for more information.

These options are usually free, but you may outgrow the limited feature-set.

### Using a web-based IDE such as CodePen

There are a number of web apps that emulate a website development environment, allowing you to enter HTML, CSS and JavaScript, and then display the result of that code as a website — all in one browser tab. Generally speaking, these tools are relatively easy, great for learning, good for sharing code (for example, if you want to share a technique with or ask for debugging help from colleagues in a different office), and free (for basic features). They host your rendered page at a unique web address. However, the features are limited, and these apps usually don't provide hosting space for assets (like images).

Try playing with some of these examples to find out which one works best for you:

* JSFiddle
* Glitch
* JS Bin
* CodePen

![Screenshot of JS Bin web based IDE](/en-US/docs/Learn/Getting_started_with_the_web/Publishing_your_website/jsbin-screen.png)

Publishing via GitHub
---------------------

Now let's examine how to easily publish your site via GitHub Pages.

1. First of all, sign up for GitHub and verify your email address.
2. Next, you need to create a repository to store files.
3. On this page, in the *Repository name* box, enter *username*.github.io, where *username* is your username. For example, our friend Bob Smith would enter *bobsmith.github.io*.
 Check the "*Initialize this repository with a README"* box. Then click *Create repository*.
 ![A sample of a GitHub repository page](/en-US/docs/Learn/Getting_started_with_the_web/Publishing_your_website/github-create-repo.png)
4. Drag and drop the content of your website folder into your repository. Then click *Commit changes*.

**Note:** Make sure your folder has an `index.html` file.
5. Navigate your browser to *username*.github.io to see your website online. For example, for the username *chrisdavidmills*, go to *chrisdavidmills*.github.io.

**Note:** It may take a few minutes for your website to go live. If your website does not display immediately, wait a few minutes. Try again.

To learn more, see GitHub Pages Help.

Further reading
---------------

* What is a web server
* Understanding domain names
* How much does it cost to do something on the web?
* Deploy a Website: A nice tutorial from Codecademy that goes a bit further and shows some additional techniques.
* Previous
* Overview: Getting started with the web
* Next


What will your website look like? - Learn web development

What will your website look like?
=================================

* Previous
* Overview: Getting started with the web
* Next

*What will your website look like?* discusses the planning and design work you have to do for your website before writing code, including "What information does my website offer?", "What fonts and colors do I want?", and "What does my site do?"

First things first: planning
----------------------------

Before doing anything, you need some ideas. What should your website actually do? A website can do basically anything, but, for your first try, you should keep things simple. We'll start by creating a simple webpage with a heading, an image, and a few paragraphs.

To begin, you'll need to answer these questions:

1. **What is your website about?** Do you like dogs, New York, or Pac-Man?
2. **What information are you presenting on the subject?** Write a title and a few paragraphs and think of an image you'd like to show on your page.
3. **What does your website look like,** in simple high-level terms? What's the background color? What kind of font is appropriate: formal, cartoony, bold and loud, subtle?

**Note:** Complex projects need detailed guidelines that go into all the details of colors, fonts, spacing between items on a page, appropriate writing style, and so on. This is sometimes called a design guide, design system, or brand book, and you can see an example at the Firefox Photon Design System.

Sketching out your design
-------------------------

Next, grab pen and paper and sketch out roughly how you want your site to look. For your first simple webpage, there's not much to sketch out, but you should get in the habit of doing this now. It really helps — you don't have to be Van Gogh!

![A rough drawing and sketch of a website on paper](/en-US/docs/Learn/Getting_started_with_the_web/What_will_your_website_look_like/website-drawing-scan.png)

**Note:** Even on real, complex websites, the design teams usually start out with rough sketches on paper and later on build digital mockups using a graphics editor or web technologies.

Web teams often include both a graphic designer and a user experience (UX) designer. Graphic designers put together the visuals of the website. UX designers have a somewhat more abstract role in addressing how users will experience and interact with the website.

Choosing your assets
--------------------

At this point, it's good to start putting together the content that will eventually appear on your webpage.

### Text

You should still have your paragraphs and title from earlier. Keep these close by.

### Theme color

To choose a color, go to the Color Picker and find a color you like. When you click on a color, you'll see a strange six-character code like `#660066`. That's called a *hex code* (short for hexadecimal), and represents your color. Copy the code down somewhere safe for now.

![Color-Picker-Tool on MDN Docs website with RGB, HSL, and HEX colors ](/en-US/docs/Learn/Getting_started_with_the_web/What_will_your_website_look_like/color-picker.png)

### Images

To choose an image, go to Google Images and search for something suitable.

1. When you find the image you want, click on the image to get an enlarged view of it.
2. Right-click the image (Ctrl + click on a Mac), choose *Save Image As…*, and choose a safe place to save your image. Alternatively, copy the image's web address from your browser's address bar for later use.

![Search results for a search term on Google Images](/en-US/docs/Learn/Getting_started_with_the_web/What_will_your_website_look_like/updated-google-images.png)

Note that most images on the web, including in Google Images, are copyrighted. To reduce your likelihood of violating copyright, you can use Google's license filter. Click on the *Tools* button, then on the resulting *Usage rights* option that appears below. You should choose the option *Creative Commons licenses*.

![Filtered search results to get images of Creative Commons Licenses on Google Images](/en-US/docs/Learn/Getting_started_with_the_web/What_will_your_website_look_like/updated-google-images-licensing.png)

### Font

As with images, many fonts are protected by licenses, meaning you cannot freely use them in your site. Google Fonts is a web service owned by Google that provides access to many fonts.

Once you have found a font, there are two main ways of using it:

1. Add a reference in your code to load the font from Google's servers.
2. Download the font file to your own system, host the font yourself, and use your hosted copy in your website's code.

**Note:** Serving fonts hosted on Google Fonts may be incompatible with the European Union's data privacy regulation GDPR as the font service exposes the user's IP address. If this is a potential problem for you, choose the second option.

Alternatively you can use safe web fonts such as Arial, Times New Roman, or Courier New.

* Previous
* Overview: Getting started with the web
* Next


Assessment: Accessibility troubleshooting - Learn web development

Assessment: Accessibility troubleshooting
=========================================

* Previous
* Overview: Accessibility

In the assessment for this module, we present to you a simple site with a number of accessibility issues that you need to diagnose and fix.

|  |  |
| --- | --- |
| Prerequisites: |
 A basic understanding of HTML, CSS, and
 JavaScript, an understanding of the
 previous articles in the course.
  |
| Objective: | To test basic knowledge of accessibility fundamentals. |

Starting point
--------------

To get this assessment started, you should go and grab the ZIP containing the files that comprise the example. Decompress the contents into a new directory somewhere on your local computer.

Alternatively, you could use an online editor such as CodePen, JSFiddle, or Glitch.

The finished assessment site should look like so:

![Screenshot of the finished assessment site with good color contrast. The search input has placeholder text and a submit button that reads go, but no visible label.](/en-US/docs/Learn/Accessibility/Accessibility_troubleshooting/assessment-site-finished.png)

You will see some differences/issues with the display of the starting state of the assessment — this is mainly due to the differences in the markup, which in turn cause some styling issues as the CSS is not applied properly. Don't worry — you'll be fixing these problems in the upcoming sections!

**Note:** If you get stuck, you can reach out to us in one of our communication channels.

Project brief
-------------

For this project, you are presented with a fictional nature site displaying a "factual" article about bears. As it stands, it has a number of accessibility issues — your task is to explore the existing site and fix them to the best of your abilities, answering the questions given below.

### Color

The text is difficult to read because of the current color scheme. Can you do a test of the current color contrast (text/background), report the results of the test, and then fix it by changing the assigned colors?

### Semantic HTML

1. The content is still not very accessible — report on what happens when you try to navigate it using a screen reader.
2. Can you update the article text to make it easier for screen reader users to navigate?
3. The navigation menu part of the site (wrapped in `<div class="nav"></div>`) could be made more accessible by putting it in a proper HTML semantic element. Which one should it be updated to? Make the update.

**Note:** You'll need to update the CSS rule selectors that style the tags to their proper equivalents for the semantic headings. Once you add paragraph elements, you'll notice the styling looking better.

### The images

The images are currently inaccessible to screen reader users. Can you fix this?

### The audio player

1. The `<audio>` player isn't accessible to hearing impaired (deaf) people — can you add some kind of accessible alternative for these users?
2. The `<audio>` player isn't accessible to those using older browsers that don't support HTML audio. How can you allow them to still access the audio?
### The forms

1. The `<input>` element in the search form at the top could do with a label, but we don't want to add a visible text label that would potentially spoil the design and isn't really needed by sighted users. How can you add a label that is only accessible to screen readers?
2. The two `<input>` elements in the comment form have visible text labels, but they are not unambiguously associated with their labels — how do you achieve this? Note that you'll need to update some of the CSS rule as well.
### The show/hide comment control

The show/hide comment control button is not currently keyboard-accessible. Can you make it keyboard accessible, both in terms of focusing it using the tab key, and activating it using the return key?

### The table

The data table is not currently very accessible — it is hard for screen reader users to associate data rows and columns together, and the table also has no kind of summary to make it clear what it shows. Can you add some features to your HTML to fix this problem?

### Other considerations?

Can you list two more ideas for improvements that would make the website more accessible?

* Previous
* Overview: Accessibility