├── README.md ├── files └── en-us │ ├── web │ ├── css │ │ └── background-image │ │ │ └── index.html │ └── api │ │ ├── windoworworkerglobalscope │ │ └── fetch │ │ │ └── index.html │ │ ├── xmlhttprequest │ │ └── index.html │ │ └── web_storage_api │ │ └── using_the_web_storage_api │ │ └── index.html │ └── learn │ └── getting_started_with_the_web │ └── javascript_basics │ └── index.html └── LICENSE.md /README.md: -------------------------------------------------------------------------------- 1 | # machine-translation-testing-content 2 | This is a repository for testing machine translations of English content. 3 | -------------------------------------------------------------------------------- /files/en-us/web/css/background-image/index.html: -------------------------------------------------------------------------------- 1 | --- 2 | title: background-image 3 | slug: Web/CSS/background-image 4 | tags: 5 | - CSS 6 | - CSS Background 7 | - CSS Property 8 | - Reference 9 | - 'recipe:css-property' 10 | --- 11 |
{{CSSRef}}
12 | 13 |The background-image CSS property sets one or more background images on an element.
The background images are drawn on stacking context layers on top of each other. The first layer specified is drawn as if it is closest to the user.
20 | 21 |The borders of the element are then drawn on top of them, and the {{cssxref("background-color")}} is drawn beneath them. How the images are drawn relative to the box and its borders is defined by the {{cssxref("background-clip")}} and {{cssxref("background-origin")}} CSS properties.
22 | 23 |If a specified image cannot be drawn (for example, when the file denoted by the specified URI cannot be loaded), browsers handle it as they would a none value.
Each background image is specified either as the keyword none or as an {{cssxref("<image>")}} value.
To specify multiple background images, supply multiple values, separated by a comma:
32 | 33 |background-image:
34 | linear-gradient(to bottom, rgba(255,255,0,0.5), rgba(0,0,255,0.5)),
35 | url('https://mdn.mozillademos.org/files/7693/catfront.png');
36 |
37 | none<image>Browsers do not provide any special information on background images to assistive technology. This is important primarily for screen readers, as a screen reader will not announce its presence and therefore convey nothing to its users. If the image contains information critical to understanding the page's overall purpose, it is better to describe it semantically in the document.
49 | 50 |{{cssinfo}}
58 | 59 |{{csssyntax}}
62 |
63 | Note that the star image is partially transparent and is layered over the cat image.
68 | 69 |<div> 72 | <p class="catsandstars"> 73 | This paragraph is full of cats<br />and stars. 74 | </p> 75 | <p>This paragraph is not.</p> 76 | <p class="catsandstars"> 77 | Here are more cats for you.<br />Look at them! 78 | </p> 79 | <p>And no more.</p> 80 | </div>81 | 82 |
p {
85 | font-size: 1.5em;
86 | color: #FE7F88;
87 | background-image: none;
88 | background-color: transparent;
89 | }
90 |
91 | div {
92 | background-image:
93 | url("https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png");
94 | }
95 |
96 | .catsandstars {
97 | background-image:
98 | url("https://mdn.mozillademos.org/files/11991/startransparent.gif"),
99 | url("https://mdn.mozillademos.org/files/7693/catfront.png");
100 | background-color: transparent;
101 | }
102 |
103 |
104 | {{EmbedLiveSample('Layering_background_images')}}
107 | 108 || Specification | 114 |Status | 115 |Comment | 116 |
|---|---|---|
| {{SpecName('CSS3 Backgrounds', '#background-image', 'background-image')}} | 121 |{{Spec2('CSS3 Backgrounds')}} | 122 |From CSS2 Revision 1, the property has been extended to support multiple backgrounds and any {{cssxref("<image>")}} CSS data type. | 123 |
| {{SpecName('CSS2.1', 'colors.html#propdef-background-image', 'background-image')}} | 126 |{{Spec2('CSS2.1')}} | 127 |From CSS1, the way images with and without intrinsic dimensions are handled is now described. | 128 |
| {{SpecName('CSS1', '#background-image', 'background-image')}} | 131 |{{Spec2('CSS1')}} | 132 |Initial definition. | 133 |
{{APIRef("Fetch API")}}
16 | 17 |The fetch() method of the {{domxref("WindowOrWorkerGlobalScope")}} mixin starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the {{domxref("Response")}} object representing the response to your request. The promise does not reject on HTTP errors — it only rejects on network errors. You must use then handlers to check for HTTP errors.
WindowOrWorkerGlobalScope is implemented by both {{domxref("Window")}} and {{domxref("WorkerGlobalScope")}}, which means that the fetch() method is available in pretty much any context in which you might want to fetch resources.
A {{domxref("WindowOrWorkerGlobalScope.fetch","fetch()")}} promise only rejects when a network error is encountered (which is usually when there’s a permissions issue or similar). A {{domxref("WindowOrWorkerGlobalScope.fetch","fetch()")}} promise does not reject on HTTP errors (404, etc.). Instead, a then() handler must check the {{domxref("Response.ok")}} and/or {{domxref("Response.status")}} properties.
The fetch() method is controlled by the connect-src directive of Content Security Policy rather than the directive of the resources it's retrieving.
Note: The fetch() method's parameters are identical to those of the {{domxref("Request.Request","Request()")}} constructor.
const fetchResponsePromise = fetch(resource [, init]) 32 |33 | 34 |
resourceblob: and data: schemes.init {{optional_inline}}An object containing any custom settings that you want to apply to the request. The possible options are:
47 | 48 |methodGET, POST. Note that the {{httpheader("Origin")}} header is not set on Fetch requests with a method of {{HTTPMethod("HEAD")}} or {{HTTPMethod("GET")}}.headersbodyGET or HEAD method cannot have a body.modecors, no-cors, or same-origin.credentialsomit, same-origin, or include. To automatically send cookies for the current domain, this option must be provided. Starting with Chrome 50, this property also takes a {{domxref("FederatedCredential")}} instance or a {{domxref("PasswordCredential")}} instance.cacheredirectfollow (automatically follow redirects), error (abort with an error if a redirect occurs), or manual (handle redirects manually). In Chrome the default is follow (before Chrome 47 it defaulted to manual).referrerabout:client, or an empty string.referrerPolicyno-referrer, no-referrer-when-downgrade, same-origin, origin, strict-origin, origin-when-cross-origin, strict-origin-when-cross-origin, or unsafe-url.integritysha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).keepalivekeepalive option can be used to allow the request to outlive the page. Fetch with the keepalive flag is a replacement for the {{domxref("Navigator.sendBeacon()")}} API.signalA {{domxref("Promise")}} that resolves to a {{domxref("Response")}} object.
81 | 82 |AbortErrorTypeErrorIn our Fetch Request example (see Fetch Request live) we create a new {{domxref("Request")}} object using the relevant constructor, then fetch it using a fetch() call. Since we are fetching an image, we run {{domxref("Body.blob()")}} on the response to give it the proper MIME type so it will be handled properly, then create an Object URL of it and display it in an {{htmlelement("img")}} element.
const myImage = document.querySelector('img');
96 |
97 | let myRequest = new Request('flowers.jpg');
98 |
99 | fetch(myRequest)
100 | .then(function(response) {
101 | if (!response.ok) {
102 | throw new Error(`HTTP error! status: ${response.status}`);
103 | }
104 | return response.blob();
105 | })
106 | .then(function(response) {
107 | let objectURL = URL.createObjectURL(response);
108 | myImage.src = objectURL;
109 | });
110 |
111 | In the Fetch with init then Request example (see Fetch Request init live), we do the same thing except that we pass in an init object when we invoke fetch():
const myImage = document.querySelector('img');
114 |
115 | let myHeaders = new Headers();
116 | myHeaders.append('Content-Type', 'image/jpeg');
117 |
118 | const myInit = {
119 | method: 'GET',
120 | headers: myHeaders,
121 | mode: 'cors',
122 | cache: 'default'
123 | };
124 |
125 | let myRequest = new Request('flowers.jpg');
126 |
127 | fetch(myRequest, myInit).then(function(response) {
128 | // ...
129 | });
130 |
131 | You could also pass the init object in with the Request constructor to get the same effect:
let myRequest = new Request('flowers.jpg', myInit);
134 |
135 | You can also use an object literal as headers in init.
const myInit = {
138 | method: 'GET',
139 | headers: {
140 | 'Content-Type': 'image/jpeg'
141 | },
142 | mode: 'cors',
143 | cache: 'default'
144 | };
145 |
146 | let myRequest = new Request('flowers.jpg', myInit);
147 |
148 |
149 | | Specification | 155 |Status | 156 |Comment | 157 |
|---|---|---|
| {{SpecName('Fetch','#fetch-method','fetch()')}} | 162 |{{Spec2('Fetch')}} | 163 |Defined in a WindowOrWorkerGlobalScope partial in the newest spec. |
164 |
| {{SpecName('Fetch','#dom-global-fetch','fetch()')}} | 167 |{{Spec2('Fetch')}} | 168 |Initial definition | 169 |
| {{SpecName('Credential Management')}} | 172 |{{Spec2('Credential Management')}} | 173 |Adds {{domxref("FederatedCredential")}} or {{domxref("PasswordCredential")}} instance as a possible value for init.credentials. |
174 |
{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}
183 | 184 |XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in {{Glossary("AJAX")}} programming.
{{InheritanceDiagram(650, 150)}}
20 | 21 |Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML.
If your communication needs to involve receiving event data or message data from a server, consider using server-sent events through the {{domxref("EventSource")}} interface. For full-duplex communication, WebSockets may be a better choice.
24 | 25 |This interface also inherits properties of {{domxref("XMLHttpRequestEventTarget")}} and of {{domxref("EventTarget")}}.
35 | 36 |readyState attribute changes.unsigned short, the state of the request.null if the request was unsuccessful or has not yet been sent.null if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. Not available in workers.unsigned short with the status of the response of the request.200 OK", for example).
55 | Note: According to the HTTP/2 specification (8.1.2.4 Response Pseudo-Header Fields), HTTP/2 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line.
57 |unsigned long representing the number of milliseconds a request can take before automatically being terminated.Access-Control requests should be made using credentials such as cookies or authorization headers.responseText from progress events instead.onreadystatechange as a property of the XMLHttpRequest instance is supported in all browsers.
Since then, a number of additional event handlers have been implemented in various browsers (onload, onerror, onprogress, etc.). See Using XMLHttpRequest.
More recent browsers, including Firefox, also support listening to the XMLHttpRequest events via standard {{domxref("EventTarget.addEventListener", "addEventListener()")}} APIs in addition to setting on* properties to a handler function.
null if no response has been received.null if either the response has not yet been received or the header doesn't exist in the response.setRequestHeader()after open(), but before send().open() instead. See the documentation for open().send() method that sends binary data.| Specification | 158 |Status | 159 |Comment | 160 |
|---|---|---|
| {{SpecName('XMLHttpRequest')}} | 165 |{{Spec2('XMLHttpRequest')}} | 166 |Live standard, latest version | 167 |
XMLHttpRequest:
182 | The Web Storage API provides mechanisms by which browsers can securely store key/value pairs.
15 | 16 |This article provides a walkthrough of how to make use of this technology.
17 | 18 |Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings). You can access these values like an object, or with the {{domxref("Storage.getItem()")}} and {{domxref("Storage.setItem()")}} methods. These three lines all set the (same) colorSetting entry:
21 | 22 |localStorage.colorSetting = '#a4509b';
23 | localStorage['colorSetting'] = '#a4509b';
24 | localStorage.setItem('colorSetting', '#a4509b');
25 |
26 | Note: It's recommended to use the Web Storage API (setItem, getItem, removeItem, key, length) to prevent the pitfalls associated with using plain objects as key-value stores.
The two mechanisms within Web Storage are as follows:
31 | 32 |sessionStorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).localStorage does the same thing, but persists even when the browser is closed and reopened.These mechanisms are available via the {{domxref("Window.sessionStorage")}} and {{domxref("Window.localStorage")}} properties (to be more precise, in supporting browsers the Window object implements the WindowLocalStorage and WindowSessionStorage objects, which the localStorage and sessionStorage properties are members of) — invoking one of these will create an instance of the {{domxref("Storage")}} object, through which data items can be set, retrieved, and removed. A different Storage object is used for the sessionStorage and localStorage for each origin — they function and are controlled separately.
So, for example, initially calling localStorage on a document will return a {{domxref("Storage")}} object; calling sessionStorage on a document will return a different {{domxref("Storage")}} object. Both of these can be manipulated in the same way, but separately.
To be able to use localStorage, we should first verify that it is supported and available in the current browsing session.
44 | 45 |Note: This API is available in current versions of all major browsers. Testing for availability is necessary only if you must support very old browsers, such as Internet Explorer 6 or 7, or in the limited circumstances described below.
49 |Browsers that support localStorage have a property on the window object named localStorage. However, just asserting that that property exists may throw exceptions. If the localStorage object does exist, there is still no guarantee that the localStorage API is actually available, as various browsers offer settings that disable localStorage. So a browser may support localStorage, but not make it available to the scripts on the page.
For example, Safari browser in Private Browsing mode gives us an empty localStorage object with a quota of zero, effectively making it unusable. Conversely, we might get a legitimate QuotaExceededError, which means that we've used up all available storage space, but storage is actually available. Our feature detection should take these scenarios into account.
Here is a function that detects whether localStorage is both supported and available:
56 | 57 |function storageAvailable(type) {
58 | var storage;
59 | try {
60 | storage = window[type];
61 | var x = '__storage_test__';
62 | storage.setItem(x, x);
63 | storage.removeItem(x);
64 | return true;
65 | }
66 | catch(e) {
67 | return e instanceof DOMException && (
68 | // everything except Firefox
69 | e.code === 22 ||
70 | // Firefox
71 | e.code === 1014 ||
72 | // test name field too, because code might not be present
73 | // everything except Firefox
74 | e.name === 'QuotaExceededError' ||
75 | // Firefox
76 | e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
77 | // acknowledge QuotaExceededError only if there's something already stored
78 | (storage && storage.length !== 0);
79 | }
80 | }
81 |
82 | And here is how you would use it:
83 | 84 |if (storageAvailable('localStorage')) {
85 | // Yippee! We can use localStorage awesomeness
86 | }
87 | else {
88 | // Too bad, no localStorage for us
89 | }
90 |
91 | You can test for sessionStorage instead by calling storageAvailable('sessionStorage').
See here for a brief history of feature-detecting localStorage.
94 | 95 |To illustrate some typical web storage usage, we have created an example, imaginatively called Web Storage Demo. The landing page provides controls that can be used to customize the color, font, and decorative image:
98 | 99 |
When you choose different options, the page is instantly updated; in addition, your choices are stored in localStorage, so that when you leave the page and load it again, later on, your choices are remembered.
We have also provided an event output page — if you load this page in another tab, then make changes to your choices in the landing page, you'll see the updated storage information outputted as a {{domxref("StorageEvent")}} is fired.
102 | 103 |
Note: As well as viewing the example pages live using the above links, you can also check out the source code.
107 |To start with, in main.js, we test whether the storage object has already been populated (i.e., the page was previously accessed):
112 | 113 |if(!localStorage.getItem('bgcolor')) {
114 | populateStorage();
115 | } else {
116 | setStyles();
117 | }
118 |
119 | The {{domxref("Storage.getItem()")}} method is used to get a data item from storage; in this case, we are testing to see whether the bgcolor item exists; if not, we run populateStorage() to add the existing customization values to the storage. If there are already values there, we run setStyles() to update the page styling with the stored values.
Note: You could also use {{domxref("Storage.length")}} to test whether the storage object is empty or not.
122 | 123 |As noted above, values can be retrieved from storage using {{domxref("Storage.getItem()")}}. This takes the key of the data item as an argument, and returns the data value. For example:
126 | 127 |function setStyles() {
128 | var currentColor = localStorage.getItem('bgcolor');
129 | var currentFont = localStorage.getItem('font');
130 | var currentImage = localStorage.getItem('image');
131 |
132 | document.getElementById('bgcolor').value = currentColor;
133 | document.getElementById('font').value = currentFont;
134 | document.getElementById('image').value = currentImage;
135 |
136 | htmlElem.style.backgroundColor = '#' + currentColor;
137 | pElem.style.fontFamily = currentFont;
138 | imgElem.setAttribute('src', currentImage);
139 | }
140 |
141 | Here, the first three lines grab the values from local storage. Next, we set the values displayed in the form elements to those values, so that they keep in sync when you reload the page. Finally, we update the styles/decorative image on the page, so your customization options come up again on reload.
142 | 143 |{{domxref("Storage.setItem()")}} is used both to create new data items, and (if the data item already exists) update existing values. This takes two arguments — the key of the data item to create/modify, and the value to store in it.
146 | 147 |function populateStorage() {
148 | localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
149 | localStorage.setItem('font', document.getElementById('font').value);
150 | localStorage.setItem('image', document.getElementById('image').value);
151 |
152 | setStyles();
153 | }
154 |
155 | The populateStorage() function sets three items in local storage — the background color, font, and image path. It then runs the setStyles() function to update the page styles, etc.
We've also included an onchange handler on each form element so that the data and styling are updated whenever a form value is changed:
bgcolorForm.onchange = populateStorage; 160 | fontForm.onchange = populateStorage; 161 | imageForm.onchange = populateStorage;162 | 163 |
The {{domxref("StorageEvent")}} is fired whenever a change is made to the {{domxref("Storage")}} object (note that this event is not fired for sessionStorage changes). This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects.
166 | 167 |On the events page (see events.js) the only JavaScript is as follows:
168 | 169 |window.addEventListener('storage', function(e) {
170 | document.querySelector('.my-key').textContent = e.key;
171 | document.querySelector('.my-old').textContent = e.oldValue;
172 | document.querySelector('.my-new').textContent = e.newValue;
173 | document.querySelector('.my-url').textContent = e.url;
174 | document.querySelector('.my-storage').textContent = JSON.stringify(e.storageArea);
175 | });
176 |
177 | Here we add an event listener to the window object that fires when the {{domxref("Storage")}} object associated with the current origin is changed. As you can see above, the event object associated with this event has a number of properties containing useful information — the key of the data that changed, the old value before the change, the new value after that change, the URL of the document that changed the storage, and the storage object itself (which we've stringified so you can see its content).
Web Storage also provides a couple of simple methods to remove data. We don't use these in our demo, but they are very simple to add to your project:
182 | 183 || Specification | 194 |Status | 195 |Comment | 196 |
|---|---|---|
| {{SpecName('HTML WHATWG', 'webstorage.html#webstorage')}} | 201 |{{Spec2('HTML WHATWG')}} | 202 |203 | |
Window.localStorage{{Compat("api.Window.localStorage")}}
215 | 216 |Window.sessionStorage{{Compat("api.Window.sessionStorage")}}
222 |All browsers have varying capacity levels for both localStorage and sessionStorage. Here is a detailed rundown of all the storage capacities for various browsers.
226 | 227 |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.
18 |{{Glossary("JavaScript")}} ("JS" for short) is a full-fledged {{Glossary("Dynamic programming language", "dynamic programming language")}} that can add interactivity to a website. It was invented by Brendan Eich (co-founder of the Mozilla project, the Mozilla Foundation, and the Mozilla Corporation).
23 | 24 |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!
25 | 26 |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:
27 | 28 |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.
35 | 36 |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!
37 | 38 |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.
41 | 42 |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.)
43 | 44 |Important: If you haven't been following along with the rest of our course, download this example code and use it as a starting point.
46 |scripts. Within the scripts folder, create a new file called main.js, and save it.index.html file, enter this code on a new line, just before the closing </body> tag:
51 | <script src="scripts/main.js"></script>52 |
main.js file:
55 | const myHeading = document.querySelector('h1');
56 | myHeading.textContent = 'Hello world!';
57 | index.html in your browser. You should see something like this:
Note: The reason the instructions (above) place the {{htmlelement("script")}} element near the bottom of the HTML file is that the browser reads code in the order it appears in the file.
63 | 64 |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.
65 |The heading text changed to Hello world! using JavaScript. You did this by using a function called {{domxref("Document.querySelector", "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 {{domxref("Node.textContent", "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.
75 |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!
80 | 81 |Important: In this article, try entering the example code lines into your JavaScript console to see what happens. For more details on JavaScript consoles, see Discover browser developer tools.
83 |{{Glossary("Variable", "Variables")}} are containers that store values. You start by declaring a variable with the var (less recommended, dive deeper for the explanation) or the let keyword, followed by the name you give to the variable:
let myVariable;90 | 91 |
Note: 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.
93 |Note: 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.
97 |Note: JavaScript is case sensitive. This means myVariable is not the same as myvariable. If you have problems in your code, check the case!
Note: For more details about the difference between var and let, see The difference between var and let.
After declaring a variable, you can give it a value:
108 | 109 |myVariable = 'Bob'; 110 |111 | 112 |
Also, you can do both these operations on the same line:
113 | 114 |let myVariable = 'Bob';115 | 116 |
You retrieve the value by calling the variable name:
117 | 118 |myVariable;119 | 120 |
After assigning a value to a variable, you can change it later in the code:
121 | 122 |let myVariable = 'Bob'; 123 | myVariable = 'Steve';124 | 125 |
Note that variables may hold values that have different data types:
126 | 127 || Variable | 131 |Explanation | 132 |Example | 133 |
|---|---|---|
| {{Glossary("String")}} | 138 |This is a sequence of text known as a string. To signify that the value is a string, enclose it in single quote marks. | 139 |let myVariable = 'Bob'; |
140 |
| {{Glossary("Number")}} | 143 |This is a number. Numbers don't have quotes around them. | 144 |let myVariable = 10; |
145 |
| {{Glossary("Boolean")}} | 148 |This is a True/False value. The words true and false are special keywords that don't need quote marks. |
149 | let myVariable = true; |
150 |
| {{Glossary("Array")}} | 153 |This is a structure that allows you to store multiple values in a single reference. | 154 |let myVariable = [1,'Bob','Steve',10];155 | Refer to each member of the array like this: 156 | myVariable[0], myVariable[1], etc. |
157 |
| {{Glossary("Object")}} | 160 |This can be anything. Everything in JavaScript is an object, and can be stored in a variable. Keep this in mind as you learn. | 161 |let myVariable = document.querySelector('h1');162 | All of the above examples too. |
163 |
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.
168 | 169 |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:
172 | 173 |/* 174 | Everything in between is a comment. 175 | */176 | 177 |
If your comment contains no line breaks, it's an option to put it behind two slashes like this:
178 | 179 |// This is a comment 180 |181 | 182 |
An {{Glossary("operator")}} is a mathematical symbol which 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 | 190 |Explanation | 191 |Symbol(s) | 192 |Example | 193 |
|---|---|---|---|
| Addition | 198 |Add two numbers together or combine two strings. | 199 |+ |
200 | 6 + 9; |
202 |
| Subtraction, Multiplication, Division | 205 |These do what you'd expect them to do in basic math. | 206 |-, *, / |
207 | 9 - 3; |
210 |
| Assignment | 213 |As you've seen already: this assigns a value to a variable. | 214 |= |
215 | let myVariable = 'Bob'; |
216 |
| Equality | 219 |This performs a test to see if two values are equal. It returns a true/false (Boolean) result. |
220 | === |
221 | let myVariable = 3; |
223 |
| Not, Does-not-equal | 226 |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. |
227 | !, !== |
228 |
229 | For "Not", the basic expression is
"Does-not-equal" gives basically the same result with different syntax. Here we are testing "is
|
239 |
There are a lot more operators to explore, but this is enough for now. See Expressions and operators for a complete list.
244 | 245 |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 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:
let iceCream = 'chocolate';
254 | if(iceCream === 'chocolate') {
255 | alert('Yay, I love chocolate ice cream!');
256 | } else {
257 | alert('Awwww, but chocolate is my favorite...');
258 | }
259 |
260 | The expression inside the if( ... ) is the test. This uses the identity operator (as described above) to compare the variable iceCream with the string chocolate to see if the two are equal. If this comparison returns true, the first block of code runs. If the comparison is not true, the second block of code—after the else statement—runs instead.
{{Glossary("Function", "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 previously. For example:
265 | 266 |let myVariable = document.querySelector('h1');
269 | alert('hello!');
272 | 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 {{Glossary("Argument", "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:
282 | 283 |function multiply(num1,num2) {
284 | let result = num1 * num2;
285 | return result;
286 | }
287 |
288 | Try running this in the console; then test with several arguments. For example:
289 | 290 |multiply(4, 7); 291 | multiply(20, 20); 292 | multiply(0.5, 3);293 | 294 |
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 {{Glossary("Scope", "scoping")}}. (Read more about variable scoping.)
Real interactivity on a website requires events 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:
301 | 302 |document.querySelector('html').onclick = function() {
303 | alert('Ouch! Stop poking me!');
304 | }
305 |
306 | There are many ways to attach an event handler to an element. Here we select the {{htmlelement("html")}} element, setting its onclick handler property equal to an anonymous (i.e. nameless) function, which contains the code we want the click event to run.
Note that
309 | 310 |document.querySelector('html').onclick = function() {};
311 |
312 | is equivalent to
313 | 314 |let myHTML = document.querySelector('html');
315 | myHTML.onclick = function() {};
316 |
317 | It's just shorter.
318 | 319 |With this review of JavaScript basics completed (above), let's add some new features to our example site.
322 | 323 |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.
326 | 327 |images folder.main.js file. (Also delete your Hello world! JavaScript from the earlier exercise.)
332 | 342 |letmyImage = document.querySelector('img'); 333 | 334 | myImage.onclick = function() { 335 |letmySrc = myImage.getAttribute('src'); 336 | if(mySrc === 'images/firefox-icon.png') { 337 | myImage.setAttribute('src','images/firefox2.png'); 338 | } else { 339 | myImage.setAttribute('src','images/firefox-icon.png'); 340 | } 341 | }
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 {{htmlelement("img")}} element in the myImage variable. Next, you made this variable's onclick event handler property equal to a function with no name (an "anonymous" function). So every time this element is clicked:
src attribute.src value is equal to the path of the original image:
351 | src value to the path of the second image, forcing the other image to be loaded inside the {{htmlelement("img")}} element.src value swaps back to the original image path, to the original state.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.
361 | 362 |index.html, add the following line just before the {{htmlelement("script")}} element:
364 |
365 | <button>Change user</button>366 |
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:
368 | 370 |letmyButton = document.querySelector('button'); 369 |letmyHeading = document.querySelector('h1');
function setUserName() {
373 | let myName = prompt('Please enter your name.');
374 | localStorage.setItem('name', myName);
375 | myHeading.textContent = 'Mozilla is cool, ' + myName;
376 | }
377 | 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.if ... else block (below). We could call this initialization code, as it structures the app when it first loads.
379 | if(!localStorage.getItem('name')) {
380 | setUserName();
381 | } else {
382 | let storedName = localStorage.getItem('name');
383 | myHeading.textContent = 'Mozilla is cool, ' + storedName;
384 | }
385 | 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().onclick event handler (below) on the button. When clicked, setUserName() runs. This allows the user to enter a different name by pressing the button.
387 | myButton.onclick = function() {
388 | setUserName();
389 | }
390 |
391 | 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.
399 | 400 |To avoid these problems, you could check that the user hasn't entered a blank name. Update your setUserName() function to this:
function setUserName() {
403 | let myName = prompt('Please enter your name.');
404 | if(!myName) {
405 | setUserName();
406 | } else {
407 | localStorage.setItem('name', myName);
408 | myHeading.innerHTML = 'Mozilla is cool, ' + myName;
409 | }
410 | }
411 |
412 | 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.
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.
417 | 418 |
If you get stuck, you can compare your work with our finished example code on GitHub.
421 | 422 |We have just scratched the surface of JavaScript. If you enjoyed playing, and wish to go further, take advantage of the resources listed below.
423 | 424 |{{PreviousMenuNext("Learn/Getting_started_with_the_web/CSS_basics", "Learn/Getting_started_with_the_web/Publishing_your_website", "Learn/Getting_started_with_the_web")}}
434 | 435 |