title
stringlengths
2
136
text
stringlengths
20
75.4k
Delete Author form - Learn web development
Delete Author form ================== This subarticle shows how to define a page to delete `Author` objects. As discussed in the form design section, our strategy will be to only allow deletion of objects that are not referenced by other objects (in this case that means we won't allow an `Author` to be deleted if it is referenced by a `Book`). In terms of implementation this means that the form needs to confirm that there are no associated books before the author is deleted. If there are associated books, it should display them, and state that they must be deleted before the `Author` object can be deleted. Controller—get route -------------------- Open **/controllers/authorController.js**. Find the exported `author_delete_get()` controller method and replace it with the following code. ```js // Display Author delete form on GET. exports.author_delete_get = asyncHandler(async (req, res, next) => { // Get details of author and all their books (in parallel) const [author, allBooksByAuthor] = await Promise.all([ Author.findById(req.params.id).exec(), Book.find({ author: req.params.id }, "title summary").exec(), ]); if (author === null) { // No results. res.redirect("/catalog/authors"); } res.render("author\_delete", { title: "Delete Author", author: author, author\_books: allBooksByAuthor, }); }); ``` The controller gets the id of the `Author` instance to be deleted from the URL parameter (`req.params.id`). It uses `await` on the promise returned by `Promise.all()` to asynchronously wait on the specified author record and all associated books (in parallel). When both operations have completed it renders the **author\_delete.pug** view, passing variables for the `title`, `author`, and `author_books`. **Note:** If `findById()` returns no results the author is not in the database. In this case there is nothing to delete, so we immediately redirect to the list of all authors. ```js if (author === null) { // No results. res.redirect("/catalog/authors"); } ``` Controller—post route --------------------- Find the exported `author_delete_post()` controller method, and replace it with the following code. ```js // Handle Author delete on POST. exports.author_delete_post = asyncHandler(async (req, res, next) => { // Get details of author and all their books (in parallel) const [author, allBooksByAuthor] = await Promise.all([ Author.findById(req.params.id).exec(), Book.find({ author: req.params.id }, "title summary").exec(), ]); if (allBooksByAuthor.length > 0) { // Author has books. Render in same way as for GET route. res.render("author\_delete", { title: "Delete Author", author: author, author\_books: allBooksByAuthor, }); return; } else { // Author has no books. Delete object and redirect to the list of authors. await Author.findByIdAndDelete(req.body.authorid); res.redirect("/catalog/authors"); } }); ``` First we validate that an id has been provided (this is sent via the form body parameters, rather than using the version in the URL). Then we get the author and their associated books in the same way as for the `GET` route. If there are no books then we delete the author object and redirect to the list of all authors. If there are still books then we just re-render the form, passing in the author and list of books to be deleted. **Note:** We could check if the call to `findById()` returns any result, and if not, immediately render the list of all authors. We've left the code as it is above for brevity (it will still return the list of authors if the id is not found, but this will happen after `findByIdAndDelete()`). View ---- Create **/views/author\_delete.pug** and copy in the text below. ```pug extends layout block content h1 #{title}: #{author.name} p= author.lifespan if author\_books.length p #[strong Delete the following books before attempting to delete this author.] div(style='margin-left:20px;margin-top:20px') h4 Books dl each book in author\_books dt a(href=book.url) #{book.title} dd #{book.summary} else p Do you really want to delete this Author? form(method='POST') div.form-group input#authorid.form-control(type='hidden', name='authorid', value=author.\_id ) button.btn.btn-primary(type='submit') Delete ``` The view extends the layout template, overriding the block named `content`. At the top it displays the author details. It then includes a conditional statement based on the number of **`author_books`** (the `if` and `else` clauses). * If there *are* books associated with the author then the page lists the books and states that these must be deleted before this `Author` may be deleted. * If there *are no* books then the page displays a confirmation prompt. * If the **Delete** button is clicked then the author id is sent to the server in a `POST` request and that author's record will be deleted. Add a delete control -------------------- Next we will add a **Delete** control to the *Author detail* view (the detail page is a good place from which to delete a record). **Note:** In a full implementation the control would be made visible only to authorized users. However at this point we haven't got an authorization system in place! Open the **author\_detail.pug** view and add the following lines at the bottom. ```pug hr p a(href=author.url+'/delete') Delete author ``` The control should now appear as a link, as shown below on the *Author detail* page. ![The Author details section of the Local library application. The left column has a vertical navigation bar. The right section contains the author details with a heading that has the Author's name followed by the life dates of the author and lists the books written by the author below it. There is a button labelled 'Delete Author' at the bottom.](/en-US/docs/Learn/Server-side/Express_Nodejs/forms/Delete_author_form/locallibary_express_author_detail_delete.png) What does it look like? ----------------------- Run the application and open your browser to `http://localhost:3000/`. Then select the *All authors* link, and then select a particular author. Finally select the *Delete author* link. If the author has no books, you'll be presented with a page like this. After pressing delete, the server will delete the author and redirect to the author list. ![The Delete Author section of the Local library application of an author who does not have any books. The left column has a vertical navigation bar. The right section contains the author's name and life dates. There is the question "Do you really want to delete this author" with a button labeled 'Delete'.](/en-US/docs/Learn/Server-side/Express_Nodejs/forms/Delete_author_form/locallibary_express_author_delete_nobooks.png) If the author does have books, then you'll be presented with a view like the following. You can then delete the books from their detail pages (once that code is implemented!). ![The Delete Author section of the Local library application of an author who does have books under his name. The section contains the author's name and life dates of the author. There is a statement that reads "Delete the following books before attempting to delete this author" followed by the author's books. The list includes the titles of each book, as links, followed by a brief description in plain text.](/en-US/docs/Learn/Server-side/Express_Nodejs/forms/Delete_author_form/locallibary_express_author_delete_withbooks.png) **Note:** The other pages for deleting objects can be implemented in much the same way. We've left that as a challenge. Next steps ---------- * Return to Express Tutorial Part 6: Working with forms. * Proceed to the final subarticle of part 6: Update Book form.
Create BookInstance form - Learn web development
Create BookInstance form ======================== This subarticle shows how to define a page/form to create `BookInstance` objects. This is very much like the form we used to create `Book` objects. Import validation and sanitization methods ------------------------------------------ Open **/controllers/bookinstanceController.js**, and add the following lines at the top of the file: ```js const { body, validationResult } = require("express-validator"); ``` Controller—get route -------------------- At the top of the file, require the *Book* module (needed because each `BookInstance` is associated with a particular `Book`). ```js const Book = require("../models/book"); ``` Find the exported `bookinstance_create_get()` controller method and replace it with the following code. ```js // Display BookInstance create form on GET. exports.bookinstance_create_get = asyncHandler(async (req, res, next) => { const allBooks = await Book.find({}, "title").sort({ title: 1 }).exec(); res.render("bookinstance\_form", { title: "Create BookInstance", book\_list: allBooks, }); }); ``` The controller gets a sorted list of all books (`allBooks`) and passes it via `book_list` to the view **`bookinstance_form.pug`** (along with a `title`). Note that no book has been selected when we first display this form, so we don't pass the `selected_book` variable to `render()`. Because of this, `selected_book` will have a value of `undefined` in the template. Controller—post route --------------------- Find the exported `bookinstance_create_post()` controller method and replace it with the following code. ```js // Handle BookInstance create on POST. exports.bookinstance_create_post = [ // Validate and sanitize fields. body("book", "Book must be specified").trim().isLength({ min: 1 }).escape(), body("imprint", "Imprint must be specified") .trim() .isLength({ min: 1 }) .escape(), body("status").escape(), body("due\_back", "Invalid date") .optional({ values: "falsy" }) .isISO8601() .toDate(), // Process request after validation and sanitization. asyncHandler(async (req, res, next) => { // Extract the validation errors from a request. const errors = validationResult(req); // Create a BookInstance object with escaped and trimmed data. const bookInstance = new BookInstance({ book: req.body.book, imprint: req.body.imprint, status: req.body.status, due\_back: req.body.due_back, }); if (!errors.isEmpty()) { // There are errors. // Render form again with sanitized values and error messages. const allBooks = await Book.find({}, "title").sort({ title: 1 }).exec(); res.render("bookinstance\_form", { title: "Create BookInstance", book\_list: allBooks, selected\_book: bookInstance.book._id, errors: errors.array(), bookinstance: bookInstance, }); return; } else { // Data from form is valid await bookInstance.save(); res.redirect(bookInstance.url); } }), ]; ``` The structure and behavior of this code is the same as for creating our other objects. First we validate and sanitize the data. If the data is invalid, we then re-display the form along with the data that was originally entered by the user and a list of error messages. If the data is valid, we save the new `BookInstance` record and redirect the user to the detail page. View ---- Create **/views/bookinstance\_form.pug** and copy in the text below. ```pug extends layout block content h1=title form(method='POST') div.form-group label(for='book') Book: select#book.form-control(name='book' required) option(value='') --Please select a book-- for book in book\_list if selected\_book==book.\_id.toString() option(value=book.\_id, selected) #{book.title} else option(value=book.\_id) #{book.title} div.form-group label(for='imprint') Imprint: input#imprint.form-control(type='text' placeholder='Publisher and date information' name='imprint' required value=(undefined===bookinstance ? '' : bookinstance.imprint) ) div.form-group label(for='due\_back') Date when book available: input#due\_back.form-control(type='date' name='due\_back' value=(undefined===bookinstance ? '' : bookinstance.due\_back\_yyyy\_mm\_dd)) div.form-group label(for='status') Status: select#status.form-control(name='status' required) option(value='') --Please select a status-- each val in ['Maintenance', 'Available', 'Loaned', 'Reserved'] if undefined===bookinstance || bookinstance.status!=val option(value=val)= val else option(value=val selected)= val button.btn.btn-primary(type='submit') Submit if errors ul for error in errors li!= error.msg ``` **Note:** The above template hard-codes the *Status* values (Maintenance, Available, etc.) and does not "remember" the user's entered values. Should you so wish, consider reimplementing the list, passing in option data from the controller and setting the selected value when the form is re-displayed. The view structure and behavior is almost the same as for the **book\_form.pug** template, so we won't go over it in detail. The one thing to note is the line where we set the "due back" date to `bookinstance.due_back_yyyy_mm_dd` if we are populating the date input for an existing instance. ```pug input#due\_back.form-control(type='date', name='due\_back' value=(undefined===bookinstance ? '' : bookinstance.due\_back\_yyyy\_mm\_dd)) ``` The date value has to be set in the format `YYYY-MM-DD` because this is expected by `<input>` elements with `type="date"`, however the date is not stored in this format so we have to convert it before setting the value in the control. The `due_back_yyyy_mm_dd()` method is added to the `BookInstance` model in the next section. Model—virtual `due_back_yyyy_mm_dd()` method -------------------------------------------- Open the file where you defined the `BookInstanceSchema` model (**models/bookinstance.js**). Add the `due_back_yyyy_mm_dd()` virtual function shown below (after the `due_back_formatted()` virtual function): ```js BookInstanceSchema.virtual("due\_back\_yyyy\_mm\_dd").get(function () { return DateTime.fromJSDate(this.due_back).toISODate(); // format 'YYYY-MM-DD' }); ``` What does it look like? ----------------------- Run the application and open your browser to `http://localhost:3000/`. Then select the *Create new book instance (copy)* link. If everything is set up correctly, your site should look something like the following screenshot. After you submit a valid `BookInstance`, it should be saved and you'll be taken to the detail page. ![Create BookInstance of the Local library application screenshot from localhost:3000. The page is divided into two columns. The narrow left column has a vertical navigation bar with 10 links separated into two sections by a light-colored horizontal line. The top section link to already created data. The bottom links go to create new data forms. The wide right column has the create book instance form with a 'Create BookInstance' heading and four input fields labeled 'Book', 'Imprint', 'Date when book available' and 'Status'. The form is filled. There is a 'Submit' button at the bottom of the form.](/en-US/docs/Learn/Server-side/Express_Nodejs/forms/Create_BookInstance_form/locallibary_express_bookinstance_create_empty.png) Next steps ---------- * Return to Express Tutorial Part 6: Working with forms. * Proceed to the next subarticle of part 6: Delete Author form.
Website security - Learn web development
Website security ================ * Previous * Overview: First steps Website security requires vigilance in all aspects of website design and usage. This introductory article won't make you a website security guru, but it will help you understand where threats come from, and what you can do to harden your web application against the most common attacks. | | | | --- | --- | | Prerequisites: | Basic computer literacy. | | Objective: | To understand the most common threats to web application security and what you can do to reduce the risk of your site being hacked. | What is website security? ------------------------- The Internet is a dangerous place! With great regularity, we hear about websites becoming unavailable due to denial of service attacks, or displaying modified (and often damaging) information on their homepages. In other high-profile cases, millions of passwords, email addresses, and credit card details have been leaked into the public domain, exposing website users to both personal embarrassment and financial risk. The purpose of website security is to prevent these (or any) sorts of attacks. The more formal definition of website security *is the act/practice of protecting websites from unauthorized access, use, modification, destruction, or disruption*. Effective website security requires design effort across the whole of the website: in your web application, the configuration of the web server, your policies for creating and renewing passwords, and the client-side code. While all that sounds very ominous, the good news is that if you're using a server-side web framework, it will almost certainly enable "by default" robust and well-thought-out defense mechanisms against a number of the more common attacks. Other attacks can be mitigated through your web server configuration, for example by enabling HTTPS. Finally, there are publicly available vulnerability scanner tools that can help you find out if you've made any obvious mistakes. The rest of this article gives you more details about a few common threats and some of the simple steps you can take to protect your site. **Note:** This is an introductory topic, designed to help you start thinking about website security, but it is not exhaustive. Website security threats ------------------------ This section lists just a few of the most common website threats and how they are mitigated. As you read, note how threats are most successful when the web application either trusts, or is *not paranoid enough* about the data coming from the browser. ### Cross-Site Scripting (XSS) XSS is a term used to describe a class of attacks that allow an attacker to inject client-side scripts *through* the website into the browsers of other users. Because the injected code comes to the browser from the site, the code is *trusted* and can do things like send the user's site authorization cookie to the attacker. When the attacker has the cookie, they can log into a site as though they were the user and do anything the user can, such as access their credit card details, see contact details, or change passwords. **Note:** XSS vulnerabilities have been historically more common than any other type of security threat. The XSS vulnerabilities are divided into *reflected* and *persistent*, based on how the site returns the injected scripts to a browser. * A *reflected* XSS vulnerability occurs when user content that is passed to the server is returned *immediately* and *unmodified* for display in the browser. Any scripts in the original user content will be run when the new page is loaded. For example, consider a site search function where the search terms are encoded as URL parameters, and these terms are displayed along with the results. An attacker can construct a search link that contains a malicious script as a parameter (e.g., `http://developer.mozilla.org?q=beer<script%20src="http://example.com/tricky.js"></script>`) and email it to another user. If the target user clicks this "interesting link", the script will be executed when the search results are displayed. As discussed earlier, this gives the attacker all the information they need to enter the site as the target user, potentially making purchases as the user or sharing their contact information. * A *persistent* XSS vulnerability occurs when the malicious script is *stored* on the website and then later redisplayed unmodified for other users to execute unwittingly. For example, a discussion board that accepts comments that contain unmodified HTML could store a malicious script from an attacker. When the comments are displayed, the script is executed and can send to the attacker the information required to access the user's account. This sort of attack is extremely popular and powerful, because the attacker might not even have any direct engagement with the victims. While the data from `POST` or `GET` requests is the most common source of XSS vulnerabilities, any data from the browser is potentially vulnerable, such as cookie data rendered by the browser, or user files that are uploaded and displayed. The best defense against XSS vulnerabilities is to remove or disable any markup that can potentially contain instructions to run the code. For HTML this includes elements, such as `<script>`, `<object>`, `<embed>`, and `<link>`. The process of modifying user data so that it can't be used to run scripts or otherwise affect the execution of server code is known as input sanitization. Many web frameworks automatically sanitize user input from HTML forms by default. ### SQL injection SQL injection vulnerabilities enable malicious users to execute arbitrary SQL code on a database, allowing data to be accessed, modified, or deleted irrespective of the user's permissions. A successful injection attack might spoof identities, create new identities with administration rights, access all data on the server, or destroy/modify the data to make it unusable. SQL injection types include Error-based SQL injection, SQL injection based on boolean errors, and Time-based SQL injection. This vulnerability is present if user input that is passed to an underlying SQL statement can change the meaning of the statement. For example, the following code is intended to list all users with a particular name (`userName`) that has been supplied from an HTML form: ```sql statement = "SELECT \* FROM users WHERE name = '" + userName + "';" ``` If the user specifies a real name, the statement will work as intended. However, a malicious user could completely change the behavior of this SQL statement to the new statement in the following example, by specifying `a';DROP TABLE users; SELECT * FROM userinfo WHERE 't' = 't` for the `userName`. ```sql SELECT \* FROM users WHERE name = 'a';DROP TABLE users; SELECT \* FROM userinfo WHERE 't' = 't'; ``` The modified statement creates a valid SQL statement that deletes the `users` table and selects all data from the `userinfo` table (which reveals the information of every user). This works because the first part of the injected text (`a';`) completes the original statement. To avoid this sort of attack, you must ensure that any user data that is passed to an SQL query cannot change the nature of the query. One way to do this is to escape all the characters in the user input that have a special meaning in SQL. **Note:** The SQL statement treats the **'** character as the beginning and end of a string literal. By putting a backslash in front of this character (**\'**), we escape the symbol, and tell SQL to instead treat it as a character (just a part of the string). In the following statement, we escape the **'** character. The SQL will now interpret the name as the whole string in bold (which is a very odd name indeed, but not harmful). ```sql SELECT \* FROM users WHERE name = 'a\';DROP TABLE users; SELECT \* FROM userinfo WHERE \'t\' = \'t'; ``` Web frameworks will often take care of the character escaping for you. Django, for example, ensures that any user-data passed to querysets (model queries) is escaped. **Note:** This section draws heavily on the information in Wikipedia here. ### Cross-Site Request Forgery (CSRF) CSRF attacks allow a malicious user to execute actions using the credentials of another user without that user's knowledge or consent. This type of attack is best explained by example. Josh is a malicious user who knows that a particular site allows logged-in users to send money to a specified account using an HTTP `POST` request that includes the account name and an amount of money. Josh constructs a form that includes his bank details and an amount of money as hidden fields, and emails it to other site users (with the *Submit* button disguised as a link to a "get rich quick" site). If a user clicks the submit button, an HTTP `POST` request will be sent to the server containing the transaction details and any client-side cookies that the browser associated with the site (adding associated site cookies to requests is normal browser behavior). The server will check the cookies, and use them to determine whether or not the user is logged in and has permission to make the transaction. The result is that any user who clicks the *Submit* button while they are logged in to the trading site will make the transaction. Josh gets rich. **Note:** The trick here is that Josh doesn't need to have access to the user's cookies (or access credentials). The browser of the user stores this information and automatically includes it in all requests to the associated server. One way to prevent this type of attack is for the server to require that `POST` requests include a user-specific site-generated secret. The secret would be supplied by the server when sending the web form used to make transfers. This approach prevents Josh from creating his own form, because he would have to know the secret that the server is providing for the user. Even if he found out the secret and created a form for a particular user, he would no longer be able to use that same form to attack every user. Web frameworks often include such CSRF prevention mechanisms. ### Other threats Other common attacks/vulnerabilities include: * Clickjacking. In this attack, a malicious user hijacks clicks meant for a visible top-level site and routes them to a hidden page beneath. This technique might be used, for example, to display a legitimate bank site but capture the login credentials into an invisible `<iframe>` controlled by the attacker. Clickjacking could also be used to get the user to click a button on a visible site, but in doing so actually unwittingly click a completely different button. As a defense, your site can prevent itself from being embedded in an iframe in another site by setting the appropriate HTTP headers. * Denial of Service (DoS). DoS is usually achieved by flooding a target site with fake requests so that access to a site is disrupted for legitimate users. The requests may be numerous, or they may individually consume large amounts of resource (e.g., slow reads or uploading of large files). DoS defenses usually work by identifying and blocking "bad" traffic while allowing legitimate messages through. These defenses are typically located before or in the web server (they are not part of the web application itself). * Directory Traversal (File and disclosure). In this attack, a malicious user attempts to access parts of the web server file system that they should not be able to access. This vulnerability occurs when the user is able to pass filenames that include file system navigation characters (for example, `../../`). The solution is to sanitize input before using it. * File Inclusion. In this attack, a user is able to specify an "unintended" file for display or execution in data passed to the server. When loaded, this file might be executed on the web server or the client-side (leading to an XSS attack). The solution is to sanitize input before using it. * Command Injection. Command injection attacks allow a malicious user to execute arbitrary system commands on the host operating system. The solution is to sanitize user input before it might be used in system calls. For a comprehensive listing of website security threats see Category: Web security exploits (Wikipedia) and Category: Attack (Open Web Application Security Project). A few key messages ------------------ Almost all of the security exploits in the previous sections are successful when the web application trusts data from the browser. Whatever else you do to improve the security of your website, you should sanitize all user-originating data before it is displayed in the browser, used in SQL queries, or passed to an operating system or file system call. **Warning:** The single most important lesson you can learn about website security is to **never trust data from the browser**. This includes, but is not limited to data in URL parameters of `GET` requests, `POST` requests, HTTP headers and cookies, and user-uploaded files. Always check and sanitize all incoming data. Always assume the worst. A number of other concrete steps you can take are: * Use more effective password management. Encourage strong passwords. Consider two-factor authentication for your site, so that in addition to a password the user must enter another authentication code (usually one that is delivered via some physical hardware that only the user will have, such as a code in an SMS sent to their phone). * Configure your web server to use HTTPS and HTTP Strict Transport Security (HSTS). HTTPS encrypts data sent between your client and server. This ensures that login credentials, cookies, `POST` requests data and header information are not easily available to attackers. * Keep track of the most popular threats (the current OWASP list is here) and address the most common vulnerabilities first. * Use vulnerability scanning tools to perform automated security testing on your site. Later on, your very successful website may also find bugs by offering a bug bounty like Mozilla does here. * Only store and display data that you need. For example, if your users must store sensitive information like credit card details, only display enough of the card number that it can be identified by the user, and not enough that it can be copied by an attacker and used on another site. The most common pattern at this time is to only display the last 4 digits of a credit card number. Web frameworks can help mitigate many of the more common vulnerabilities. Summary ------- This article has explained the concept of web security and some of the more common threats against which your website should attempt to protect. Most importantly, you should understand that a web application cannot trust any data from the web browser. All user data should be sanitized before it is displayed, or used in SQL queries and file system calls. With this article, you've come to the end of this module, covering your first steps in server-side website programming. We hope you've enjoyed learning these fundamental concepts, and you're now ready to select a Web Framework and start programming. * Previous * Overview: First steps
Introduction to the server side - Learn web development
Introduction to the server side =============================== * Overview: First steps * Next Welcome to the MDN beginner's server-side programming course! In this first article, we look at server-side programming from a high level, answering questions such as "what is it?", "how does it differ from client-side programming?", and "why it is so useful?". After reading this article you'll understand the additional power available to websites through server-side coding. | | | | --- | --- | | Prerequisites: | A basic understanding of what a web server is. | | Objective: | To gain familiarity with what server-side programming is, what it can do, and how it differs from client-side programming. | Most large-scale websites use server-side code to dynamically display different data when needed, generally pulled out of a database stored on a server and sent to the client to be displayed via some code (e.g. HTML and JavaScript). Perhaps the most significant benefit of server-side code is that it allows you to tailor website content for individual users. Dynamic sites can highlight content that is more relevant based on user preferences and habits. It can also make sites easier to use by storing personal preferences and information — for example reusing stored credit card details to streamline subsequent payments. It can even allow interaction with users of the site, sending notifications and updates via email or through other channels. All of these capabilities enable much deeper engagement with users. In the modern world of web development, learning about server-side development is highly recommended. What is server-side website programming? ---------------------------------------- Web browsers communicate with web servers using the **H**yper**T**ext **T**ransfer **P**rotocol (HTTP). When you click a link on a web page, submit a form, or run a search, an **HTTP request** is sent from your browser to the target server. The request includes a URL identifying the affected resource, a method that defines the required action (for example to get, delete, or post the resource), and may include additional information encoded in URL parameters (the field-value pairs sent via a query string), as POST data (data sent by the HTTP POST method), or in associated cookies. Web servers wait for client request messages, process them when they arrive, and reply to the web browser with an **HTTP response** message. The response contains a status line indicating whether or not the request succeeded (e.g. "HTTP/1.1 200 OK" for success). The body of a successful response to a request would contain the requested resource (e.g. a new HTML page, or an image), which could then be displayed by the web browser. ### Static sites The diagram below shows a basic web server architecture for a *static site* (a static site is one that returns the same hard-coded content from the server whenever a particular resource is requested). When a user wants to navigate to a page, the browser sends an HTTP "GET" request specifying its URL. The server retrieves the requested document from its file system and returns an HTTP response containing the document and a success status (usually 200 OK). If the file cannot be retrieved for some reason, an error status is returned (see client error responses and server error responses). ![A simplified diagram of a static web server.](/en-US/docs/Learn/Server-side/First_steps/Introduction/basic_static_app_server.png) ### Dynamic sites A dynamic website is one where some of the response content is generated *dynamically*, only when needed. On a dynamic website HTML pages are normally created by inserting data from a database into placeholders in HTML templates (this is a much more efficient way of storing large amounts of content than using static websites). A dynamic site can return different data for a URL based on information provided by the user or stored preferences and can perform other operations as part of returning a response (e.g. sending notifications). Most of the code to support a dynamic website must run on the server. Creating this code is known as "**server-side programming**" (or sometimes "**back-end scripting**"). The diagram below shows a simple architecture for a *dynamic website*. As in the previous diagram, browsers send HTTP requests to the server, then the server processes the requests and returns appropriate HTTP responses. Requests for *static* resources are handled in the same way as for static sites (static resources are any files that don't change — typically: CSS, JavaScript, Images, pre-created PDF files, etc.). ![A simplified diagram of a web server that uses server-side programming to get information from a database and construct HTML from templates. This is the same diagram as is in the Client-Server overview.](/en-US/docs/Learn/Server-side/First_steps/Introduction/web_application_with_html_and_steps.png) Requests for dynamic resources are instead forwarded (2) to server-side code (shown in the diagram as a *Web Application*). For "dynamic requests" the server interprets the request, reads required information from the database (3), combines the retrieved data with HTML templates (4), and sends back a response containing the generated HTML (5,6). Are server-side and client-side programming the same? ----------------------------------------------------- Let's now turn our attention to the code involved in server-side and client-side programming. In each case, the code is significantly different: * They have different purposes and concerns. * They generally don't use the same programming languages (the exception being JavaScript, which can be used on the server- and client-side). * They run inside different operating system environments. Code running in the browser is known as **client-side code** and is primarily concerned with improving the appearance and behavior of a rendered web page. This includes selecting and styling UI components, creating layouts, navigation, form validation, etc. By contrast, server-side website programming mostly involves choosing *which content* is returned to the browser in response to requests. The server-side code handles tasks like validating submitted data and requests, using databases to store and retrieve data and sending the correct data to the client as required. Client-side code is written using HTML, CSS, and JavaScript — it is run inside a web browser and has little or no access to the underlying operating system (including limited access to the file system). Web developers can't control what browser every user might be using to view a website — browsers provide inconsistent levels of compatibility with client-side code features, and part of the challenge of client-side programming is handling differences in browser support gracefully. Server-side code can be written in any number of programming languages — examples of popular server-side web languages include PHP, Python, Ruby, C#, and JavaScript (NodeJS). The server-side code has full access to the server operating system and the developer can choose what programming language (and specific version) they wish to use. Developers typically write their code using **web frameworks**. Web frameworks are collections of functions, objects, rules and other code constructs designed to solve common problems, speed up development, and simplify the different types of tasks faced in a particular domain. Again, while both client and server-side code use frameworks, the domains are very different, and hence so are the frameworks. Client-side web frameworks simplify layout and presentation tasks while server-side web frameworks provide a lot of "common" web server functionality that you might otherwise have to implement yourself (e.g. support for sessions, support for users and authentication, easy database access, templating libraries, etc.). **Note:** Client-side frameworks are often used to help speed up development of client-side code, but you can also choose to write all the code by hand; in fact, writing your code by hand can be quicker and more efficient if you only need a small, simple website UI. In contrast, you would almost never consider writing the server-side component of a web app without a framework — implementing a vital feature like an HTTP server is really hard to do from scratch in say Python, but Python web frameworks like Django provide one out of the box, along with other very useful tools. What can you do on the server-side? ----------------------------------- Server-side programming is very useful because it allows us to *efficiently* deliver information tailored for individual users and thereby create a much better user experience. Companies like Amazon use server-side programming to construct search results for products, make targeted product suggestions based on client preferences and previous buying habits, simplify purchases, etc. Banks use server-side programming to store account information and allow only authorized users to view and make transactions. Other services like Facebook, Twitter, Instagram, and Wikipedia use server-side programming to highlight, share, and control access to interesting content. Some of the common uses and benefits of server-side programming are listed below. You'll note that there is some overlap! ### Efficient storage and delivery of information Imagine how many products are available on Amazon, and imagine how many posts have been written on Facebook? Creating a separate static page for each product or post would be completely impractical. Server-side programming allows us to instead store the information in a database and dynamically construct and return HTML and other types of files (e.g. PDFs, images, etc.). It is also possible to return data (JSON, XML, etc.) for rendering by appropriate client-side web frameworks (this reduces the processing burden on the server and the amount of data that needs to be sent). The server is not limited to sending information from databases, and might alternatively return the result of software tools, or data from communications services. The content can even be targeted for the type of client device that is receiving it. Because the information is in a database, it can also more easily be shared and updated with other business systems (for example, when products are sold either online or in a shop, the shop might update its database of inventory). **Note:** Your imagination doesn't have to work hard to see the benefit of server-side code for efficient storage and delivery of information: 1. Go to Amazon or some other e-commerce site. 2. Search for a number of keywords and note how the page structure doesn't change, even though the results do. 3. Open two or three different products. Note again how they have a common structure and layout, but the content for different products has been pulled from the database. For a common search term ("fish", say) you can see literally millions of returned values. Using a database allows these to be stored and shared efficiently, and it allows the presentation of the information to be controlled in just one place. ### Customized user experience Servers can store and use information about clients to provide a convenient and tailored user experience. For example, many sites store credit cards so that details don't have to be entered again. Sites like Google Maps can use saved or current locations for providing routing information, and search or travel history to highlight local businesses in search results. A deeper analysis of user habits can be used to anticipate their interests and further customize responses and notifications, for example providing a list of previously visited or popular locations you may want to look at on a map. **Note:** Google Maps saves your search and visit history. Frequently visited or frequently searched locations are highlighted more than others. Google search results are optimized based on previous searches. 1. Go to Google search. 2. Search for "football". 3. Now try typing "favorite" in the search box and observe the autocomplete search predictions. Coincidence? Nada! ### Controlled access to content Server-side programming allows sites to restrict access to authorized users and serve only the information that a user is permitted to see. Real-world examples include social-networking sites which allow users to determine who can see the content they post to the site, and whose content appears in their feed. **Note:** Consider other real examples where access to content is controlled. For example, what can you see if you go to the online site for your bank? Log in to your account — what additional information can you see and modify? What information can you see that only the bank can change? ### Store session/state information Server-side programming allows developers to make use of **sessions** — basically, a mechanism that allows a server to store information associated with the current user of a site and send different responses based on that information. This allows, for example, a site to know that a user has previously logged in and display links to their emails or order history, or perhaps save the state of a simple game so that the user can go to a site again and carry on where they left it. **Note:** Visit a newspaper site that has a subscription model and open a bunch of tabs (e.g. The Age). Continue to visit the site over a few hours/days. Eventually, you will start to be redirected to pages explaining how to subscribe, and you will be unable to access articles. This information is an example of session information stored in cookies. ### Notifications and communication Servers can send general or user-specific notifications through the website itself or via email, SMS, instant messaging, video conversations, or other communications services. A few examples include: * Facebook and Twitter send emails and SMS messages to notify you of new communications. * Amazon regularly sends product emails that suggest products similar to those already bought or viewed that you might be interested in. * A web server might send warning messages to site administrators alerting them to low memory on the server, or suspicious user activity. **Note:** The most common type of notification is a "confirmation of registration". Pick almost any large site that you are interested in (Google, Amazon, Instagram, etc.) and create a new account using your email address. You will shortly receive an email confirming your registration, or requiring acknowledgment to activate your account. ### Data analysis A website may collect a lot of data about users: what they search for, what they buy, what they recommend, how long they stay on each page. Server-side programming can be used to refine responses based on analysis of this data. For example, Amazon and Google both advertise products based on previous searches (and purchases). **Note:** If you're a Facebook user, go to your main feed and look at the stream of posts. Note how some of the posts are out of numerical order - in particular, posts with more "likes" are often higher on the list than more recent posts. Also look at what kind of ads you are being shown — you might see ads for things you looked at on other sites. Facebook's algorithm for highlighting content and advertising can be a bit of a mystery, but it is clear that it does depend on your likes and viewing habits! Summary ------- Congratulations, you've reached the end of the first article about server-side programming. You've now learned that server-side code is run on a web server and that its main role is to control *what* information is sent to the user (while client-side code mainly handles the structure and presentation of that data to the user). You should also understand that it is useful because it allows us to create websites that *efficiently* deliver information tailored for individual users and have a good idea of some of the things you might be able to do when you're a server-side programmer. Lastly, you should understand that server-side code can be written in a number of programming languages and that you should use a web framework to make the whole process easier. In a future article we'll help you choose the best web framework for your first site. Here we'll take you through the main client-server interactions in just a little more detail. * Overview: First steps * Next
Client-Server Overview - Learn web development
Client-Server Overview ====================== * Previous * Overview: First steps * Next Now that you know the purpose and potential benefits of server-side programming, we're going to examine in detail what happens when a server receives a "dynamic request" from a browser. As most website server-side code handles requests and responses in similar ways, this will help you understand what you need to do when writing most of your own code. | | | | --- | --- | | Prerequisites: | A basic understanding of what a web server is. | | Objective: | To understand client-server interactions in a dynamic website, and in particular what operations need to be performed by server-side code. | There is no real code in the discussion because we haven't yet chosen a web framework to use to write our code! This discussion is however still very relevant, because the described behavior must be implemented by your server-side code, irrespective of which programming language or web framework you select. Web servers and HTTP (a primer) ------------------------------- Web browsers communicate with web servers using the **H**yper**T**ext **T**ransfer **P**rotocol (HTTP). When you click a link on a web page, submit a form, or run a search, the browser sends an *HTTP Request* to the server. This request includes: * A URL identifying the target server and resource (e.g. an HTML file, a particular data point on the server, or a tool to run). * A method that defines the required action (for example, to get a file or to save or update some data). The different methods/verbs and their associated actions are listed below: + `GET`: Get a specific resource (e.g. an HTML file containing information about a product, or a list of products). + `POST`: Create a new resource (e.g. add a new article to a wiki, add a new contact to a database). + `HEAD`: Get the metadata information about a specific resource without getting the body like `GET` would. You might for example use a `HEAD` request to find out the last time a resource was updated, and then only use the (more "expensive") `GET` request to download the resource if it has changed. + `PUT`: Update an existing resource (or create a new one if it doesn't exist). + `DELETE`: Delete the specified resource. + `TRACE`, `OPTIONS`, `CONNECT`, `PATCH`: These verbs are for less common/advanced tasks, so we won't cover them here. * Additional information can be encoded with the request (for example, HTML form data). Information can be encoded as: + URL parameters: `GET` requests encode data in the URL sent to the server by adding name/value pairs onto the end of it — for example `http://example.com?name=Fred&age=11`. You always have a question mark (`?`) separating the rest of the URL from the URL parameters, an equals sign (`=`) separating each name from its associated value, and an ampersand (`&`) separating each pair. URL parameters are inherently "insecure" as they can be changed by users and then resubmitted. As a result URL parameters/`GET` requests are not used for requests that update data on the server. + `POST` data. `POST` requests add new resources, the data for which is encoded within the request body. + Client-side cookies. Cookies contain session data about the client, including keys that the server can use to determine their login status and permissions/accesses to resources. Web servers wait for client request messages, process them when they arrive, and reply to the web browser with an HTTP Response message. The response contains an HTTP Response status code indicating whether or not the request succeeded (e.g. "`200 OK`" for success, "`404 Not Found`" if the resource cannot be found, "`403 Forbidden`" if the user isn't authorized to see the resource, etc.). The body of a successful response to a `GET` request would contain the requested resource. When an HTML page is returned it is rendered by the web browser. As part of processing, the browser may discover links to other resources (e.g. an HTML page usually references JavaScript and CSS files), and will send separate HTTP Requests to download these files. Both static and dynamic websites (discussed in the following sections) use exactly the same communication protocol/patterns. ### GET request/response example You can make a simple `GET` request by clicking on a link or searching on a site (like a search engine homepage). For example, the HTTP request that is sent when you perform a search on MDN for the term "client-server overview" will look a lot like the text shown below (it will not be identical because parts of the message depend on your browser/setup). **Note:** The format of HTTP messages is defined in a "web standard" (RFC9110). You don't need to know this level of detail, but at least now you know where this all came from! #### The request Each line of the request contains information about it. The first part is called the **header**, and contains useful information about the request, in the same way that an HTML head contains useful information about an HTML document (but not the actual content itself, which is in the body): ```http GET /en-US/search?q=client+server+overview&topic=apps&topic=html&topic=css&topic=js&topic=api&topic=webdev HTTP/1.1 Host: developer.mozilla.org Connection: keep-alive Pragma: no-cache Cache-Control: no-cache Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,\*/\*;q=0.8 Referer: https://developer.mozilla.org/en-US/ Accept-Encoding: gzip, deflate, sdch, br Accept-Charset: ISO-8859-1,UTF-8;q=0.7,\*;q=0.7 Accept-Language: en-US,en;q=0.8,es;q=0.6 Cookie: sessionid=6ynxs23n521lu21b1t136rhbv7ezngie; csrftoken=zIPUJsAZv6pcgCBJSCj1zU6pQZbfMUAT; dwf\_section\_edit=False; dwf\_sg\_task\_completion=False; \_gat=1; \_ga=GA1.2.1688886003.1471911953; ffo=true ``` The first and second lines contain most of the information we talked about above: * The type of request (`GET`). * The target resource URL (`/en-US/search`). * The URL parameters (`q=client%2Bserver%2Boverview&topic=apps&topic=html&topic=css&topic=js&topic=api&topic=webdev`). * The target/host website (developer.mozilla.org). * The end of the first line also includes a short string identifying the specific protocol version (`HTTP/1.1`). The final line contains information about the client-side cookies — you can see in this case the cookie includes an id for managing sessions (`Cookie: sessionid=6ynxs23n521lu21b1t136rhbv7ezngie; …`). The remaining lines contain information about the browser used and the sort of responses it can handle. For example, you can see here that: * My browser (`User-Agent`) is Mozilla Firefox (`Mozilla/5.0`). * It can accept gzip compressed information (`Accept-Encoding: gzip`). * It can accept the specified set of characters (`Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7`) and languages (`Accept-Language: en-US,en;q=0.8,es;q=0.6`). * The `Referer` line indicates the address of the web page that contained the link to this resource (i.e. the origin of the request, `https://developer.mozilla.org/en-US/`). HTTP requests can also have a body, but it is empty in this case. #### The response The first part of the response for this request is shown below. The header contains information like the following: * The first line includes the response code `200 OK`, which tells us that the request succeeded. * We can see that the response is `text/html` formatted (`Content-Type`). * We can also see that it uses the UTF-8 character set (`Content-Type: text/html; charset=utf-8`). * The head also tells us how big it is (`Content-Length: 41823`). At the end of the message we see the **body** content — which contains the actual HTML returned by the request. ```http HTTP/1.1 200 OK Server: Apache X-Backend-Server: developer1.webapp.scl3.mozilla.com Vary: Accept, Cookie, Accept-Encoding Content-Type: text/html; charset=utf-8 Date: Wed, 07 Sep 2016 00:11:31 GMT Keep-Alive: timeout=5, max=999 Connection: Keep-Alive X-Frame-Options: DENY Allow: GET X-Cache-Info: caching Content-Length: 41823 <!DOCTYPE html> <html lang="en-US" dir="ltr" class="redesign no-js" data-ffo-opensanslight=false data-ffo-opensans=false > <head prefix="og: http://ogp.me/ns#"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <script>(function(d) { d.className = d.className.replace(/\bno-js/, ''); })(document.documentElement);</script> … ``` The remainder of the response header includes information about the response (e.g. when it was generated), the server, and how it expects the browser to handle the page (e.g. the `X-Frame-Options: DENY` line tells the browser not to allow this page to be embedded in an `<iframe>` in another site). ### POST request/response example An HTTP `POST` is made when you submit a form containing information to be saved on the server. #### The request The text below shows the HTTP request made when a user submits new profile details on this site. The format of the request is almost the same as the `GET` request example shown previously, though the first line identifies this request as a `POST`. ```http POST /en-US/profiles/hamishwillee/edit HTTP/1.1 Host: developer.mozilla.org Connection: keep-alive Content-Length: 432 Pragma: no-cache Cache-Control: no-cache Origin: https://developer.mozilla.org Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Content-Type: application/x-www-form-urlencoded Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,\*/\*;q=0.8 Referer: https://developer.mozilla.org/en-US/profiles/hamishwillee/edit Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.8,es;q=0.6 Cookie: sessionid=6ynxs23n521lu21b1t136rhbv7ezngie; \_gat=1; csrftoken=zIPUJsAZv6pcgCBJSCj1zU6pQZbfMUAT; dwf\_section\_edit=False; dwf\_sg\_task\_completion=False; \_ga=GA1.2.1688886003.1471911953; ffo=true csrfmiddlewaretoken=zIPUJsAZv6pcgCBJSCj1zU6pQZbfMUAT&user-username=hamishwillee&user-fullname=Hamish+Willee&user-title=&user-organization=&user-location=Australia&user-locale=en-US&user-timezone=Australia%2FMelbourne&user-irc_nickname=&user-interests=&user-expertise=&user-twitter_url=&user-stackoverflow_url=&user-linkedin_url=&user-mozillians_url=&user-facebook_url= ``` The main difference is that the URL doesn't have any parameters. As you can see, the information from the form is encoded in the body of the request (for example, the new user fullname is set using: `&user-fullname=Hamish+Willee`). #### The response The response from the request is shown below. The status code of "`302 Found`" tells the browser that the post succeeded, and that it must issue a second HTTP request to load the page specified in the `Location` field. The information is otherwise similar to that for the response to a `GET` request. ```http HTTP/1.1 302 FOUND Server: Apache X-Backend-Server: developer3.webapp.scl3.mozilla.com Vary: Cookie Vary: Accept-Encoding Content-Type: text/html; charset=utf-8 Date: Wed, 07 Sep 2016 00:38:13 GMT Location: https://developer.mozilla.org/en-US/profiles/hamishwillee Keep-Alive: timeout=5, max=1000 Connection: Keep-Alive X-Frame-Options: DENY X-Cache-Info: not cacheable; request wasn't a GET or HEAD Content-Length: 0 ``` **Note:** The HTTP responses and requests shown in these examples were captured using the Fiddler application, but you can get similar information using web sniffers (e.g. Websniffer) or packet analyzers like Wireshark. You can try this yourself. Use any of the linked tools, and then navigate through a site and edit profile information to see the different requests and responses. Most modern browsers also have tools that monitor network requests (for example, the Network Monitor tool in Firefox). Static sites ------------ A *static site* is one that returns the same hard coded content from the server whenever a particular resource is requested. So for example if you have a page about a product at `/static/myproduct1.html`, this same page will be returned to every user. If you add another similar product to your site you will need to add another page (e.g. `myproduct2.html`) and so on. This can start to get really inefficient — what happens when you get to thousands of product pages? You would repeat a lot of code across each page (the basic page template, structure, etc.), and if you wanted to change anything about the page structure — like add a new "related products" section for example — then you'd have to change every page individually. **Note:** Static sites are excellent when you have a small number of pages and you want to send the same content to every user. However they can have a significant cost to maintain as the number of pages becomes larger. Let's recap on how this works, by looking again at the static site architecture diagram we looked at in the last article. ![A simplified diagram of a static web server.](/en-US/docs/Learn/Server-side/First_steps/Client-Server_overview/basic_static_app_server.png) When a user wants to navigate to a page, the browser sends an HTTP `GET` request specifying the URL of its HTML page. The server retrieves the requested document from its file system and returns an HTTP response containing the document and an HTTP Response status code of "`200 OK`" (indicating success). The server might return a different status code, for example "`404 Not Found`" if the file is not present on the server, or "`301 Moved Permanently`" if the file exists but has been redirected to a different location. The server for a static site will only ever need to process GET requests, because the server doesn't store any modifiable data. It also doesn't change its responses based on HTTP Request data (e.g. URL parameters or cookies). Understanding how static sites work is nevertheless useful when learning server-side programming, because dynamic sites handle requests for static files (CSS, JavaScript, static images, etc.) in exactly the same way. Dynamic sites ------------- A *dynamic site* is one that can generate and return content based on the specific request URL and data (rather than always returning the same hard-coded file for a particular URL). Using the example of a product site, the server would store product "data" in a database rather than individual HTML files. When receiving an HTTP `GET` Request for a product, the server determines the product ID, fetches the data from the database, and then constructs the HTML page for the response by inserting the data into an HTML template. This has major advantages over a static site: Using a database allows the product information to be stored efficiently in an easily extensible, modifiable, and searchable way. Using HTML templates makes it very easy to change the HTML structure, because this only needs to be done in one place, in a single template, and not across potentially thousands of static pages. ### Anatomy of a dynamic request This section provides a step-by-step overview of the "dynamic" HTTP request and response cycle, building on what we looked at in the last article with much more detail. In order to "keep things real" we'll use the context of a sports-team manager website where a coach can select their team name and team size in an HTML form and get back a suggested "best lineup" for their next game. The diagram below shows the main elements of the "team coach" website, along with numbered labels for the sequence of operations when the coach accesses their "best team" list. The parts of the site that make it dynamic are the *Web Application* (this is how we will refer to the server-side code that processes HTTP requests and returns HTTP responses), the *Database*, which contains information about players, teams, coaches and their relationships, and the *HTML Templates*. ![This is a diagram of a simple web server with step numbers for each of step of the client-server interaction.](/en-US/docs/Learn/Server-side/First_steps/Client-Server_overview/web_application_with_html_and_steps.png) After the coach submits the form with the team name and number of players, the sequence of operations is: 1. The web browser creates an HTTP `GET` request to the server using the base URL for the resource (`/best`) and encoding the team and player number either as URL parameters (e.g. `/best?team=my_team_name&show=11`) or as part of the URL pattern (e.g. `/best/my_team_name/11/`). A `GET` request is used because the request is only fetching data (not modifying data). 2. The *Web Server* detects that the request is "dynamic" and forwards it to the *Web Application* for processing (the web server determines how to handle different URLs based on pattern matching rules defined in its configuration). 3. The *Web Application* identifies that the *intention* of the request is to get the "best team list" based on the URL (`/best/`) and finds out the required team name and number of players from the URL. The *Web Application* then gets the required information from the database (using additional "internal" parameters to define which players are "best", and possibly also getting the identity of the logged in coach from a client-side cookie). 4. The *Web Application* dynamically creates an HTML page by putting the data (from the *Database*) into placeholders inside an HTML template. 5. The *Web Application* returns the generated HTML to the web browser (via the *Web Server*), along with an HTTP status code of 200 ("success"). If anything prevents the HTML from being returned then the *Web Application* will return another code — for example "404" to indicate that the team does not exist. 6. The Web Browser will then start to process the returned HTML, sending separate requests to get any other CSS or JavaScript files that it references (see step 7). 7. The Web Server loads static files from the file system and returns them to the browser directly (again, correct file handling is based on configuration rules and URL pattern matching). An operation to update a record in the database would be handled similarly, except that like any database update, the HTTP request from the browser should be encoded as a `POST` request. ### Doing other work A *Web Application's* job is to receive HTTP requests and return HTTP responses. While interacting with a database to get or update information are very common tasks, the code may do other things at the same time, or not interact with a database at all. A good example of an additional task that a *Web Application* might perform would be sending an email to users to confirm their registration with the site. The site might also perform logging or other operations. ### Returning something other than HTML Server-side website code does not have to return HTML snippets/files in the response. It can instead dynamically create and return other types of files (text, PDF, CSV, etc.) or even data (JSON, XML, etc.). This is especially relevant for websites that work by fetching content from the server using JavaScript and updating the page dynamically, rather than always loading a new page when new content is to be shown. See Fetching data from the server for more on the motivation for this approach, and what this model looks like from the client's point of view. Web frameworks simplify server-side web programming --------------------------------------------------- Server-side web frameworks make writing code to handle the operations described above much easier. One of the most important operations they perform is providing simple mechanisms to map URLs for different resources/pages to specific handler functions. This makes it easier to keep the code associated with each type of resource separate. It also has benefits in terms of maintenance, because you can change the URL used to deliver a particular feature in one place, without having to change the handler function. For example, consider the following Django (Python) code that maps two URL patterns to two view functions. The first pattern ensures that an HTTP request with a resource URL of `/best` will be passed to a function named `index()` in the `views` module. A request that has the pattern "`/best/junior`", will instead be passed to the `junior()` view function. ```python # file: best/urls.py # from django.conf.urls import url from . import views urlpatterns = [ # example: /best/ url(r'^$', views.index), # example: /best/junior/ url(r'^junior/$', views.junior), ] ``` **Note:** The first parameters in the `url()` functions may look a bit odd (e.g. `r'^junior/$'`) because they use a pattern matching technique called "regular expressions" (RegEx, or RE). You don't need to know how regular expressions work at this point, other than that they allow us to match patterns in the URL (rather than the hard coded values above) and use them as parameters in our view functions. As an example, a really simple RegEx might say "match a single uppercase letter, followed by between 4 and 7 lower case letters." The web framework also makes it easy for a view function to fetch information from the database. The structure of our data is defined in models, which are Python classes that define the fields to be stored in the underlying database. If we have a model named *Team* with a field of "*team\_type*" then we can use a simple query syntax to get back all teams that have a particular type. The example below gets a list of all teams that have the exact (case sensitive) `team_type` of "junior" — note the format: field name (`team_type`) followed by double underscore, and then the type of match to use (in this case `exact`). There are many other types of matches and we can daisy chain them. We can also control the order and the number of results returned. ```python #best/views.py from django.shortcuts import render from .models import Team def junior(request): list_teams = Team.objects.filter(team_type__exact="junior") context = {'list': list_teams} return render(request, 'best/index.html', context) ``` After the `junior()` function gets the list of junior teams, it calls the `render()` function, passing the original `HttpRequest`, an HTML template, and a "context" object defining the information to be included in the template. The `render()` function is a convenience function that generates HTML using a context and an HTML template, and returns it in an `HttpResponse` object. Obviously web frameworks can help you with a lot of other tasks. We discuss a lot more benefits and some popular web framework choices in the next article. Summary ------- At this point you should have a good overview of the operations that server-side code has to perform, and know some of the ways in which a server-side web framework can make this easier. In a following module we'll help you choose the best Web Framework for your first site. * Previous * Overview: First steps * Next
Server-side web frameworks - Learn web development
Server-side web frameworks ========================== * Previous * Overview: First steps * Next The previous article showed you what the communication between web clients and servers looks like, the nature of HTTP requests and responses, and what a server-side web application needs to do in order to respond to requests from a web browser. With this knowledge under our belt, it's time to explore how web frameworks can simplify these tasks, and give you an idea of how you'd choose a framework for your first server-side web application. | | | | --- | --- | | Prerequisites: | Basic understanding of how server-side code handles and responds to HTTP requests (see Client-Server overview). | | Objective: | To understand how web frameworks can simplify development/maintenance of server-side code and to get readers thinking about selecting a framework for their own development. | The following sections illustrate some points using code fragments taken from real web frameworks. Don't be concerned if it doesn't **all** make sense now; we'll be working you through the code in our framework-specific modules. Overview -------- Server-side web frameworks (a.k.a. "web application frameworks") are software frameworks that make it easier to write, maintain and scale web applications. They provide tools and libraries that simplify common web development tasks, including routing URLs to appropriate handlers, interacting with databases, supporting sessions and user authorization, formatting output (e.g. HTML, JSON, XML), and improving security against web attacks. The next section provides a bit more detail about how web frameworks can ease web application development. We then explain some of the criteria you can use for choosing a web framework, and then list some of your options. What can a web framework do for you? ------------------------------------ Web frameworks provide tools and libraries to simplify common web development operations. You don't *have* to use a server-side web framework, but it is strongly advised — it will make your life a lot easier. This section discusses some of the functionality that is often provided by web frameworks (not every framework will necessarily provide all of these features!). ### Work directly with HTTP requests and responses As we saw in the last article, web servers and browsers communicate via the HTTP protocol — servers wait for HTTP requests from the browser and then return information in HTTP responses. Web frameworks allow you to write simplified syntax that will generate server-side code to work with these requests and responses. This means that you will have an easier job, interacting with easier, higher-level code rather than lower level networking primitives. The example below shows how this works in the Django (Python) web framework. Every "view" function (a request handler) receives an `HttpRequest` object containing request information, and is required to return an `HttpResponse` object with the formatted output (in this case a string). ```python # Django view function from django.http import HttpResponse def index(request): # Get an HttpRequest (request) # perform operations using information from the request. # Return HttpResponse return HttpResponse('Output string to return') ``` ### Route requests to the appropriate handler Most sites will provide a number of different resources, accessible through distinct URLs. Handling these all in one function would be hard to maintain, so web frameworks provide simple mechanisms to map URL patterns to specific handler functions. This approach also has benefits in terms of maintenance, because you can change the URL used to deliver a particular feature without having to change the underlying code. Different frameworks use different mechanisms for the mapping. For example, the Flask (Python) web framework adds routes to view functions using a decorator. ```python @app.route("/") def hello(): return "Hello World!" ``` While Django expects developers to define a list of URL mappings between a URL pattern and a view function. ```python urlpatterns = [ url(r'^$', views.index), # example: /best/myteamname/5/ url(r'^best/(?P<team\_name>\w.+?)/(?P<team\_number>[0-9]+)/$', views.best), ] ``` ### Make it easy to access data in the request Data can be encoded in an HTTP request in a number of ways. An HTTP `GET` request to get files or data from the server may encode what data is required in URL parameters or within the URL structure. An HTTP `POST` request to update a resource on the server will instead include the update information as "POST data" within the body of the request. The HTTP request may also include information about the current session or user in a client-side cookie. Web frameworks provide programming-language-appropriate mechanisms to access this information. For example, the `HttpRequest` object that Django passes to every view function contains methods and properties for accessing the target URL, the type of request (e.g. an HTTP `GET`), `GET` or `POST` parameters, cookie and session data, etc. Django can also pass information encoded in the structure of the URL by defining "capture patterns" in the URL mapper (see the last code fragment in the section above). ### Abstract and simplify database access Websites use databases to store information both to be shared with users, and about users. Web frameworks often provide a database layer that abstracts database read, write, query, and delete operations. This abstraction layer is referred to as an Object-Relational Mapper (ORM). Using an ORM has two benefits: * You can replace the underlying database without necessarily needing to change the code that uses it. This allows developers to optimize for the characteristics of different databases based on their usage. * Basic validation of data can be implemented within the framework. This makes it easier and safer to check that data is stored in the correct type of database field, has the correct format (e.g. an email address), and isn't malicious in any way (hackers can use certain patterns of code to do bad things such as deleting database records). For example, the Django web framework provides an ORM, and refers to the object used to define the structure of a record as the *model*. The model specifies the field *types* to be stored, which may provide field-level validation on what information can be stored (e.g. an email field would only allow valid email addresses). The field definitions may also specify their maximum size, default values, selection list options, help text for documentation, label text for forms etc. The model doesn't state any information about the underlying database as that is a configuration setting that may be changed separately of our code. The first code snippet below shows a very simple Django model for a `Team` object. This stores the team name and team level as character fields and specifies a maximum number of characters to be stored for each record. The `team_level` is a choice field, so we also provide a mapping between choices to be displayed and data to be stored, along with a default value. ```python #best/models.py from django.db import models class Team(models.Model): team_name = models.CharField(max_length=40) TEAM_LEVELS = ( ('U09', 'Under 09s'), ('U10', 'Under 10s'), ('U11', 'Under 11s'), # List our other teams ) team_level = models.CharField(max_length=3,choices=TEAM_LEVELS,default='U11') ``` The Django model provides a simple query API for searching the database. This can match against a number of fields at a time using different criteria (e.g. exact, case-insensitive, greater than, etc.), and can support complex statements (for example, you can specify a search on U11 teams that have a team name that starts with "Fr" or ends with "al"). The second code snippet shows a view function (resource handler) for displaying all of our U09 teams. In this case we specify that we want to filter for all records where the `team_level` field has exactly the text 'U09' (note below how this criteria is passed to the `filter()` function as an argument with field name and match type separated by double underscores: **team\_level\_\_exact**). ```python #best/views.py from django.shortcuts import render from .models import Team def youngest(request): list_teams = Team.objects.filter(team_level__exact="U09") context = {'youngest\_teams': list_teams} return render(request, 'best/index.html', context) ``` ### Rendering data Web frameworks often provide templating systems. These allow you to specify the structure of an output document, using placeholders for data that will be added when a page is generated. Templates are often used to create HTML, but can also create other types of documents. Web frameworks often provide a mechanism to make it easy to generate other formats from stored data, including JSON and XML. For example, the Django template system allows you to specify variables using a "double-handlebars" syntax (e.g. `{{ variable_name }}`), which will be replaced by values passed in from the view function when a page is rendered. The template system also provides support for expressions (with syntax: `{% expression %}`), which allow templates to perform simple operations like iterating list values passed into the template. **Note:** Many other templating systems use a similar syntax, e.g.: Jinja2 (Python), handlebars (JavaScript), moustache (JavaScript), etc. The code snippet below shows how this works. Continuing the "youngest team" example from the previous section, the HTML template is passed a list variable called `youngest_teams` by the view. Inside the HTML skeleton we have an expression that first checks if the `youngest_teams` variable exists, and then iterates it in a `for` loop. On each iteration the template displays the team's `team_name` value in a list item. ```django #best/templates/best/index.html <!DOCTYPE html> <html lang="en"> <body> {% if youngest\_teams %} <ul> {% for team in youngest\_teams %} <li>{{ team.team\_name }}</li> {% endfor %} </ul> {% else %} <p>No teams are available.</p> {% endif %} </body> </html> ``` How to select a web framework ----------------------------- Numerous web frameworks exist for almost every programming language you might want to use (we list a few of the more popular frameworks in the following section). With so many choices, it can become difficult to work out what framework provides the best starting point for your new web application. Some of the factors that may affect your decision are: * **Effort to learn:** The effort to learn a web framework depends on how familiar you are with the underlying programming language, the consistency of its API, the quality of its documentation, and the size and activity of its community. If you're starting from absolutely no programming experience then consider Django (it is one of the easiest to learn based on the above criteria). If you are part of a development team that already has significant experience with a particular web framework or programming language, then it makes sense to stick with that. * **Productivity:** Productivity is a measure of how quickly you can create new features once you are familiar with the framework, and includes both the effort to write and maintain code (since you can't write new features while old ones are broken). Many of the factors affecting productivity are similar to those for "Effort to learn" — e.g. documentation, community, programming experience, etc. — other factors include: + *Framework purpose/origin*: Some web frameworks were initially created to solve certain types of problems, and remain *better* at creating web apps with similar constraints. For example, Django was created to support development of a newspaper website, so it's good for blogs and other sites that involve publishing things. By contrast, Flask is a much lighter-weight framework and is great for creating web apps running on embedded devices. + *Opinionated vs. unopinionated*: An opinionated framework is one in which there are recommended "best" ways to solve a particular problem. Opinionated frameworks tend to be more productive when you're trying to solve common problems, because they lead you in the right direction, however they are sometimes less flexible. + *Batteries included vs. get it yourself*: Some web frameworks include tools/libraries that address every problem their developers can think "by default", while more lightweight frameworks expect web developers to pick and choose solution to problems from separate libraries (Django is an example of the former, while Flask is an example of a very light-weight framework). Frameworks that include everything are often easier to get started with because you already have everything you need, and the chances are that it is well integrated and well documented. However if a smaller framework has everything you (will ever) need then it can run in more constrained environments and will have a smaller and easier subset of things to learn. + *Whether or not the framework encourages good development practices*: For example, a framework that encourages a Model-View-Controller architecture to separate code into logical functions will result in more maintainable code than one that has no expectations on developers. Similarly, framework design can have a large impact on how easy it is to test and re-use code. * **Performance of the framework/programming language:** Usually "speed" is not the biggest factor in selection because even relatively slow runtimes like Python are more than "good enough" for mid-sized sites running on moderate hardware. The perceived speed benefits of another language, e.g. C++ or JavaScript, may well be offset by the costs of learning and maintenance. * **Caching support:** As your website becomes more successful then you may find that it can no longer cope with the number of requests it is receiving as users access it. At this point you may consider adding support for caching. Caching is an optimization where you store all or part of a web response so that it does not have to be recalculated on subsequent requests. Returning a cached response is much faster than calculating one in the first place. Caching can be implemented in your code or in the server (see reverse proxy). Web frameworks will have different levels of support for defining what content can be cached. * **Scalability:** Once your website is fantastically successful you will exhaust the benefits of caching and even reach the limits of *vertical scaling* (running your web application on more powerful hardware). At this point you may need to *scale horizontally* (share the load by distributing your site across a number of web servers and databases) or scale "geographically" because some of your customers are based a long way away from your server. The web framework you choose can make a big difference on how easy it is to scale your site. * **Web security:** Some web frameworks provide better support for handling common web attacks. Django for example sanitizes all user input from HTML templates so that user-entered JavaScript cannot be run. Other frameworks provide similar protection, but it is not always enabled by default. There are many other possible factors, including licensing, whether or not the framework is under active development, etc. If you're an absolute beginner at programming then you'll probably choose your framework based on "ease of learning". In addition to "ease of use" of the language itself, high quality documentation/tutorials and an active community helping new users are your most valuable resources. We've chosen Django (Python) and Express (Node/JavaScript) to write our examples later on in the course, mainly because they are easy to learn and have good support. **Note:** Let's go to the main websites for Django (Python) and Express (Node/JavaScript) and check out their documentation and community. 1. Navigate to the main sites (linked above) * Click on the Documentation menu links (named things like "Documentation, Guide, API Reference, Getting Started", etc.). * Can you see topics showing how to set up URL routing, templates, and databases/models? * Are the documents clear? 2. Navigate to mailing lists for each site (accessible from Community links). * How many questions have been posted in the last few days * How many have responses? * Do they have an active community? A few good web frameworks? -------------------------- Let's now move on, and discuss a few specific server-side web frameworks. The server-side frameworks below represent *a few* of the most popular available at the time of writing. All of them have everything you need to be productive — they are open source, are under active development, have enthusiastic communities creating documentation and helping users on discussion boards, and are used in large numbers of high-profile websites. There are many other great server-side frameworks that you can discover using a basic internet search. **Note:** Descriptions come (partially) from the framework websites! ### Django (Python) Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. It's free and open source. Django follows the "Batteries included" philosophy and provides almost everything most developers might want to do "out of the box". Because everything is included, it all works together, follows consistent design principles, and has extensive and up-to-date documentation. It is also fast, secure, and very scalable. Being based on Python, Django code is easy to read and to maintain. Popular sites using Django (from Django home page) include: Disqus, Instagram, Knight Foundation, MacArthur Foundation, Mozilla, National Geographic, Open Knowledge Foundation, Pinterest, Open Stack. ### Flask (Python) Flask is a microframework for Python. While minimalist, Flask can create serious websites out of the box. It contains a development server and debugger, and includes support for Jinja2 templating, secure cookies, unit testing, and RESTful request dispatching. It has good documentation and an active community. Flask has become extremely popular, particularly for developers who need to provide web services on small, resource-constrained systems (e.g. running a web server on a Raspberry Pi, Drone controllers, etc.) ### Express (Node.js/JavaScript) Express is a fast, unopinionated, flexible and minimalist web framework for Node.js (node is a browserless environment for running JavaScript). It provides a robust set of features for web and mobile applications and delivers useful HTTP utility methods and middleware. Express is extremely popular, partially because it eases the migration of client-side JavaScript web programmers into server-side development, and partially because it is resource-efficient (the underlying node environment uses lightweight multitasking within a thread rather than spawning separate processes for every new web request). Because Express is a minimalist web framework it does not incorporate every component that you might want to use (for example, database access and support for users and sessions are provided through independent libraries). There are many excellent independent components, but sometimes it can be hard to work out which is the best for a particular purpose! Many popular server-side and full stack frameworks (comprising both server and client-side frameworks) are based on Express, including Feathers, ItemsAPI, KeystoneJS, Kraken, LoopBack, MEAN, and Sails. A lot of high profile companies use Express, including: Uber, Accenture, IBM, etc. (a list is provided here). ### Deno (JavaScript) Deno is a simple, modern, and secure JavaScript/TypeScript runtime and framework built on top of Chrome V8 and Rust. Deno is powered by Tokio — a Rust-based asynchronous runtime which lets it serve web pages faster. It also has internal support for WebAssembly, which enables the compilation of binary code for use on the client-side. Deno aims to fill in some of the loop-holes in Node.js by providing a mechanism that naturally maintains better security. Deno's features include: * Security by default. Deno modules restrict permissions to **file**, **network**, or **environment** access unless explicitly allowed. * TypeScript support **out-of-the-box**. * First-class await mechanism. * Built-in testing facility and code formatter (`deno fmt`) * (JavaScript) Browser compatibility: Deno programs that are written completely in JavaScript excluding the `Deno` namespace (or feature test for it), should work directly in any modern browser. * Script bundling into a single JavaScript file. Deno provides an easy yet powerful way to use JavaScript for both client- and server-side programming. ### Ruby on Rails (Ruby) Rails (usually referred to as "Ruby on Rails") is a web framework written for the Ruby programming language. Rails follows a very similar design philosophy to Django. Like Django it provides standard mechanisms for routing URLs, accessing data from a database, generating HTML from templates and formatting data as JSON or XML. It similarly encourages the use of design patterns like DRY ("don't repeat yourself" — write code only once if at all possible), MVC (model-view-controller) and a number of others. There are of course many differences due to specific design decisions and the nature of the languages. Rails has been used for high profile sites, including: Basecamp, GitHub, Shopify, Airbnb, Twitch, SoundCloud, Hulu, Zendesk, Square, Highrise. ### Laravel (PHP) Laravel is a web application framework with expressive, elegant syntax. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as: * Simple, fast routing engine. * Powerful dependency injection container. * Multiple back-ends for session and cache storage. * Expressive, intuitive database ORM. * Database agnostic schema migrations. * Robust background job processing. * Real-time event broadcasting. Laravel is accessible, yet powerful, providing tools needed for large, robust applications. ### ASP.NET ASP.NET is an open source web framework developed by Microsoft for building modern web applications and services. With ASP.NET you can quickly create websites based on HTML, CSS, and JavaScript, scale them for use by millions of users and easily add more complex capabilities like Web APIs, forms over data, or real time communications. One of the differentiators for ASP.NET is that it is built on the Common Language Runtime (CLR), allowing programmers to write ASP.NET code using any supported .NET language (C#, Visual Basic, etc.). Like many Microsoft products it benefits from excellent tools (often free), an active developer community, and well-written documentation. ASP.NET is used by Microsoft, Xbox.com, Stack Overflow, and many others. ### Mojolicious (Perl) Mojolicious is a next-generation web framework for the Perl programming language. Back in the early days of the web, many people learned Perl because of a wonderful Perl library called CGI. It was simple enough to get started without knowing much about the language and powerful enough to keep you going. Mojolicious implements this idea using bleeding edge technologies. Some of the features provided by Mojolicious are: * A real-time web framework, to easily grow single-file prototypes into well-structured MVC web applications. * RESTful routes, plugins, commands, Perl-ish templates, content negotiation, session management, form validation, testing framework, static file server, CGI/PSGI detection, and first-class Unicode support. * A full-stack HTTP and WebSocket client/server implementation with IPv6, TLS, SNI, IDNA, HTTP/SOCKS5 proxy, UNIX domain socket, Comet (long polling), keep-alive, connection pooling, timeout, cookie, multipart, and gzip compression support. * JSON and HTML/XML parsers and generators with CSS selector support. * Very clean, portable and object-oriented pure-Perl API with no hidden magic. * Fresh code based upon years of experience, free and open-source. ### Spring Boot (Java) Spring Boot is one of a number of projects provided by Spring. It is a good starting point for doing server-side web development using Java. Although definitely not the only framework based on Java it is easy to use to create stand-alone, production-grade Spring-based Applications that you can "just run". It is an opinionated view of the Spring platform and third-party libraries but allows to start with minimum fuss and configuration. It can be used for small problems but its strength is building larger scale applications that use a cloud approach. Usually multiple applications run in parallel talking to each other, with some providing user interaction and others doing back end work (e.g. accessing databases or other services). Load balancers help to ensure redundancy and reliability or allow geolocated handling of user requests to ensure responsiveness. Summary ------- This article has shown that web frameworks can make it easier to develop and maintain server-side code. It has also provided a high level overview of a few popular frameworks, and discussed criteria for choosing a web application framework. You should now have at least an idea of how to choose a web framework for your own server-side development. If not, then don't worry — later on in the course we'll give you detailed tutorials on Django and Express to give you some experience of actually working with a web framework. For the next article in this module we'll change direction slightly and consider web security. * Previous * Overview: First steps * Next
Django Tutorial Part 4: Django admin site - Learn web development
Django Tutorial Part 4: Django admin site ========================================= * Previous * Overview: Django * Next Now that we've created models for the LocalLibrary website, we'll use the Django Admin site to add some "real" book data. First we'll show you how to register the models with the admin site, then we'll show you how to login and create some data. At the end of the article we will show some of the ways you can further improve the presentation of the Admin site. | | | | --- | --- | | Prerequisites: | First complete: Django Tutorial Part 3: Using models. | | Objective: | To understand the benefits and limitations of the Django admin site, and use it to create some records for our models. | Overview -------- The Django admin *application* can use your models to automatically build a site area that you can use to create, view, update, and delete records. This can save you a lot of time during development, making it very easy to test your models and get a feel for whether you have the *right* data. The admin application can also be useful for managing data in production, depending on the type of website. The Django project recommends it only for internal data management (i.e. just for use by admins, or people internal to your organization), as the model-centric approach is not necessarily the best possible interface for all users, and exposes a lot of unnecessary detail about the models. All the configuration required to include the admin application in your website was done automatically when you created the skeleton project (for information about actual dependencies needed, see the Django docs here). As a result, all you **must** do to add your models to the admin application is to *register* them. At the end of this article we'll provide a brief demonstration of how you might further configure the admin area to better display our model data. After registering the models we'll show how to create a new "superuser", login to the site, and create some books, authors, book instances, and genres. These will be useful for testing the views and templates we'll start creating in the next tutorial. Registering models ------------------ First, open **admin.py** in the catalog application (**/locallibrary/catalog/admin.py**). It currently looks like this — note that it already imports `django.contrib.admin`: ```python from django.contrib import admin # Register your models here. ``` Register the models by copying the following text into the bottom of the file. This code imports the models and then calls `admin.site.register` to register each of them. ```python from .models import Author, Genre, Book, BookInstance, Language admin.site.register(Book) admin.site.register(Author) admin.site.register(Genre) admin.site.register(BookInstance) admin.site.register(Language) ``` **Note:** The lines above assume that you accepted the challenge to create a model to represent the natural language of a book (see the models tutorial article)! This is the simplest way of registering a model, or models, with the site. The admin site is highly customizable, and we'll talk more about the other ways of registering your models further down. Creating a superuser -------------------- In order to log into the admin site, we need a user account with *Staff* status enabled. In order to view and create records we also need this user to have permissions to manage all our objects. You can create a "superuser" account that has full access to the site and all needed permissions using **manage.py**. Call the following command, in the same directory as **manage.py**, to create the superuser. You will be prompted to enter a username, email address, and *strong* password. ```bash python3 manage.py createsuperuser ``` Once this command completes a new superuser will have been added to the database. Now restart the development server so we can test the login: ```bash python3 manage.py runserver ``` Logging in and using the site ----------------------------- To login to the site, open the */admin* URL (e.g. `http://127.0.0.1:8000/admin`) and enter your new superuser userid and password credentials (you'll be redirected to the *login* page, and then back to the */admin* URL after you've entered your details). This part of the site displays all our models, grouped by installed application. You can click on a model name to go to a screen that lists all its associated records, and you can further click on those records to edit them. You can also directly click the **Add** link next to each model to start creating a record of that type. ![Admin Site - Home page](/en-US/docs/Learn/Server-side/Django/Admin_site/admin_home.png) Click on the **Add** link to the right of *Books* to create a new book (this will display a dialog much like the one below). Note how the titles of each field, the type of widget used, and the `help_text` (if any) match the values you specified in the model. Enter values for the fields. You can create new authors or genres by pressing the **+** button next to the respective fields (or select existing values from the lists if you've already created them). When you're done you can press **SAVE**, **Save and add another**, or **Save and continue editing** to save the record. ![Admin Site - Book Add](/en-US/docs/Learn/Server-side/Django/Admin_site/admin_book_add.png) **Note:** At this point we'd like you to spend some time adding a few books, authors, languages, and genres (e.g. Fantasy) to your application. Make sure that each author and genre includes a couple of different books (this will make your list and detail views more interesting when we implement them later on in the article series). When you've finished adding books, click on the **Home** link in the top bookmark to be taken back to the main admin page. Then click on the **Books** link to display the current list of books (or on one of the other links to see other model lists). Now that you've added a few books, the list might look similar to the screenshot below. The title of each book is displayed; this is the value returned in the Book model's `__str__()` method that we specified in the last article. ![Admin Site - List of book objects](/en-US/docs/Learn/Server-side/Django/Admin_site/admin_book_list.png) From this list you can delete books by selecting the checkbox next to the book you don't want, selecting the *delete…* action from the *Action* drop-down list, and then pressing the **Go** button. You can also add new books by pressing the **ADD BOOK** button. You can edit a book by selecting its name in the link. The edit page for a book, shown below, is almost identical to the "Add" page. The main differences are the page title (*Change book*) and the addition of **Delete**, **HISTORY** and **VIEW ON SITE** buttons (this last button appears because we defined the `get_absolute_url()` method in our model). **Note:** Clicking the **VIEW ON SITE** button raises a `NoReverseMatch` exception because the `get_absolute_url()` method attempts to `reverse()` a named URL mapping ('book-detail') that has not yet been defined. We'll define a URL mapping and associated view in Django Tutorial Part 6: Generic list and detail views. ![Admin Site - Book Edit](/en-US/docs/Learn/Server-side/Django/Admin_site/admin_book_modify.png) Now navigate back to the **Home** page (using the *Home* link in the breadcrumb trail) and then view the **Author** and **Genre** lists — you should already have quite a few created from when you added the new books, but feel free to add some more. What you won't have is any *Book Instances*, because these are not created from Books (although you can create a `Book` from a `BookInstance` — this is the nature of the `ForeignKey` field). Navigate back to the *Home* page and press the associated **Add** button to display the *Add book instance* screen below. Note the large, globally unique Id, which can be used to separately identify a single copy of a book in the library. ![Admin Site - BookInstance Add](/en-US/docs/Learn/Server-side/Django/Admin_site/admin_bookinstance_add.png) Create a number of these records for each of your books. Set the status as *Available* for at least some records and *On loan* for others. If the status is **not** *Available*, then also set a future *Due back* date. That's it! You've now learned how to set up and use the administration site. You've also created records for `Book`, `BookInstance`, `Genre`, `Language` and `Author` that we'll be able to use once we create our own views and templates. Advanced configuration ---------------------- Django does a pretty good job of creating a basic admin site using the information from the registered models: * Each model has a list of individual records, identified by the string created with the model's `__str__()` method, and linked to detail views/forms for editing. By default, this view has an action menu at the top that you can use to perform bulk delete operations on records. * The model detail record forms for editing and adding records contain all the fields in the model, laid out vertically in their declaration order. You can further customize the interface to make it even easier to use. Some of the things you can do are: * List views: + Add additional fields/information displayed for each record. + Add filters to select which records are listed, based on date or some other selection value (e.g. Book loan status). + Add additional options to the actions menu in list views and choose where this menu is displayed on the form. * Detail views + Choose which fields to display (or exclude), along with their order, grouping, whether they are editable, the widget used, orientation etc. + Add related fields to a record to allow inline editing (e.g. add the ability to add and edit book records while you're creating their author record). In this section we're going to look at a few changes that will improve the interface for our *LocalLibrary*, including adding more information to `Book` and `Author` model lists, and improving the layout of their edit views. We won't change the `Language` and `Genre` model presentation because they only have one field each, so there is no real benefit in doing so! You can find a complete reference of all the admin site customization choices in The Django Admin site (Django Docs). ### Register a ModelAdmin class To change how a model is displayed in the admin interface you define a ModelAdmin class (which describes the layout) and register it with the model. Let's start with the `Author` model. Open **admin.py** in the catalog application (**/locallibrary/catalog/admin.py**). Comment out your original registration (prefix it with a #) for the `Author` model: ```python # admin.site.register(Author) ``` Now add a new `AuthorAdmin` and registration as shown below. ```python # Define the admin class class AuthorAdmin(admin.ModelAdmin): pass # Register the admin class with the associated model admin.site.register(Author, AuthorAdmin) ``` Now we'll add `ModelAdmin` classes for `Book`, and `BookInstance`. We again need to comment out the original registrations: ```python # admin.site.register(Book) # admin.site.register(BookInstance) ``` Now to create and register the new models; for the purpose of this demonstration, we'll instead use the `@register` decorator to register the models (this does exactly the same thing as the `admin.site.register()` syntax): ```python # Register the Admin classes for Book using the decorator @admin.register(Book) class BookAdmin(admin.ModelAdmin): pass # Register the Admin classes for BookInstance using the decorator @admin.register(BookInstance) class BookInstanceAdmin(admin.ModelAdmin): pass ``` Currently all of our admin classes are empty (see `pass`) so the admin behavior will be unchanged! We can now extend these to define our model-specific admin behavior. ### Configure list views The *LocalLibrary* currently lists all authors using the object name generated from the model `__str__()` method. This is fine when you only have a few authors, but once you have many you may end up having duplicates. To differentiate them, or just because you want to show more interesting information about each author, you can use list\_display to add additional fields to the view. Replace your `AuthorAdmin` class with the code below. The field names to be displayed in the list are declared in a *tuple* in the required order, as shown (these are the same names as specified in your original model). ```python class AuthorAdmin(admin.ModelAdmin): list_display = ('last\_name', 'first\_name', 'date\_of\_birth', 'date\_of\_death') ``` Now navigate to the author list in your website. The fields above should now be displayed, like so: ![Admin Site - Improved Author List](/en-US/docs/Learn/Server-side/Django/Admin_site/admin_improved_author_list.png) For our `Book` model we'll additionally display the `author` and `genre`. The `author` is a `ForeignKey` field (one-to-many) relationship, and so will be represented by the `__str__()` value for the associated record. Replace the `BookAdmin` class with the version below. ```python class BookAdmin(admin.ModelAdmin): list_display = ('title', 'author', 'display\_genre') ``` Unfortunately we can't directly specify the `genre` field in `list_display` because it is a `ManyToManyField` (Django prevents this because there would be a large database access "cost" in doing so). Instead we'll define a `display_genre` function to get the information as a string (this is the function we've called above; we'll define it below). **Note:** Getting the `genre` may not be a good idea here, because of the "cost" of the database operation. We're showing you how because calling functions in your models can be very useful for other reasons — for example to add a *Delete* link next to every item in the list. Add the following code into your `Book` model (**models.py**). This creates a string from the first three values of the `genre` field (if they exist) and creates a `short_description` that can be used in the admin site for this method. ```python def display\_genre(self): """Create a string for the Genre. This is required to display genre in Admin.""" return ', '.join(genre.name for genre in self.genre.all()[:3]) display_genre.short_description = 'Genre' ``` After saving the model and updated admin, open your website and go to the *Books* list page; you should see a book list like the one below: ![Admin Site - Improved Book List](/en-US/docs/Learn/Server-side/Django/Admin_site/admin_improved_book_list.png) The `Genre` model (and the `Language` model, if you defined one) both have a single field, so there is no point creating an additional model for them to display additional fields. **Note:** It is worth updating the `BookInstance` model list to show at least the status and the expected return date. We've added that as a challenge at the end of this article! ### Add list filters Once you've got a lot of items in a list, it can be useful to be able to filter which items are displayed. This is done by listing fields in the `list_filter` attribute. Replace your current `BookInstanceAdmin` class with the code fragment below. ```python class BookInstanceAdmin(admin.ModelAdmin): list_filter = ('status', 'due\_back') ``` The list view will now include a filter box to the right. Note how you can choose dates and status to filter the values: ![Admin Site - BookInstance List Filters](/en-US/docs/Learn/Server-side/Django/Admin_site/admin_improved_bookinstance_list_filters.png) ### Organize detail view layout By default, the detail views lay out all fields vertically, in their order of declaration in the model. You can change the order of declaration, which fields are displayed (or excluded), whether sections are used to organize the information, whether fields are displayed horizontally or vertically, and even what edit widgets are used in the admin forms. **Note:** The *LocalLibrary* models are relatively simple so there isn't a huge need for us to change the layout; we'll make some changes anyway however, just to show you how. #### Controlling which fields are displayed and laid out Update your `AuthorAdmin` class to add the `fields` line, as shown below: ```python class AuthorAdmin(admin.ModelAdmin): list_display = ('last\_name', 'first\_name', 'date\_of\_birth', 'date\_of\_death') fields = ['first\_name', 'last\_name', ('date\_of\_birth', 'date\_of\_death')] ``` The `fields` attribute lists just those fields that are to be displayed on the form, in order. Fields are displayed vertically by default, but will display horizontally if you further group them in a tuple (as shown in the "date" fields above). In your website go to the author detail view — it should now appear as shown below: ![Admin Site - Improved Author Detail](/en-US/docs/Learn/Server-side/Django/Admin_site/admin_improved_author_detail.png) **Note:** You can also use the `exclude` attribute to declare a list of attributes to be excluded from the form (all other attributes in the model will be displayed). #### Sectioning the detail view You can add "sections" to group related model information within the detail form, using the fieldsets attribute. In the `BookInstance` model we have information related to what the book is (i.e. `name`, `imprint`, and `id`) and when it will be available (`status`, `due_back`). We can add these to our `BookInstanceAdmin` class as shown below, using the `fieldsets` property. ```python @admin.register(BookInstance) class BookInstanceAdmin(admin.ModelAdmin): list_filter = ('status', 'due\_back') fieldsets = ( (None, { 'fields': ('book', 'imprint', 'id') }), ('Availability', { 'fields': ('status', 'due\_back') }), ) ``` Each section has its own title (or `None`, if you don't want a title) and an associated tuple of fields in a dictionary — the format is complicated to describe, but fairly easy to understand if you look at the code fragment immediately above. Now navigate to a book instance view in your website; the form should appear as shown below: ![Admin Site - Improved BookInstance Detail with sections](/en-US/docs/Learn/Server-side/Django/Admin_site/admin_improved_bookinstance_detail_sections.png) ### Inline editing of associated records Sometimes it can make sense to be able to add associated records at the same time. For example, it may make sense to have both the book information and information about the specific copies you've got on the same detail page. You can do this by declaring inlines, of type TabularInline (horizontal layout) or StackedInline (vertical layout, just like the default model layout). You can add the `BookInstance` information inline to our `Book` detail by specifying `inlines` in your `BookAdmin`: ```python class BooksInstanceInline(admin.TabularInline): model = BookInstance @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_display = ('title', 'author', 'display\_genre') inlines = [BooksInstanceInline] ``` Now navigate to a view for a `Book` in your website — at the bottom you should now see the book instances relating to this book (immediately below the book's genre fields): ![Admin Site - Book with Inlines](/en-US/docs/Learn/Server-side/Django/Admin_site/admin_improved_book_detail_inlines.png) In this case all we've done is declare our tabular inline class, which just adds all fields from the *inlined* model. You can specify all sorts of additional information for the layout, including the fields to display, their order, whether they are read only or not, etc. (see TabularInline for more information). **Note:** There are some painful limits in this functionality! In the screenshot above we have three existing book instances, followed by three placeholders for new book instances (which look very similar!). It would be better to have NO spare book instances by default and just add them with the **Add another Book instance** link, or to be able to just list the `BookInstance`s as non-readable links from here. The first option can be done by setting the `extra` attribute to `0` in `BooksInstanceInline` model, try it by yourself. Challenge yourself ------------------ We've learned a lot in this section, so now it is time for you to try a few things. 1. For the `BookInstance` list view, add code to display the book, status, due back date, and id (rather than the default `__str__()` text). 2. Add an inline listing of `Book` items to the `Author` detail view using the same approach as we did for `Book`/`BookInstance`. Summary ------- That's it! You've now learned how to set up the administration site in both its simplest and improved form, how to create a superuser, and how to navigate the admin site and view, delete, and update records. Along the way you've created a bunch of Books, BookInstances, Genres, and Authors that we'll be able to list and display once we create our own view and templates. Further reading --------------- * Writing your first Django app, part 2: Introducing the Django Admin (Django docs) * The Django Admin site (Django Docs) * Previous * Overview: Django * Next
Django Tutorial Part 5: Creating our home page - Learn web development
Django Tutorial Part 5: Creating our home page ============================================== * Previous * Overview: Django * Next We're now ready to add the code that displays our first complete page — a home page for the LocalLibrary website. The home page will show the number of records we have for each model type and provide sidebar navigation links to our other pages. Along the way we'll gain practical experience in writing basic URL maps and views, getting records from the database, and using templates. | | | | --- | --- | | Prerequisites: | Read the Django Introduction. Complete previous tutorial topics (including Django Tutorial Part 4: Django admin site). | | Objective: | Learn to create simple URL maps and views (where no data is encoded in the URL), get data from models, and create templates. | Overview -------- After we defined our models and created some initial library records to work with, it's time to write the code that presents that information to users. The first thing we need to do is determine what information we want to display in our pages, and define the URLs to use for returning those resources. Then we'll create a URL mapper, views, and templates to display the pages. The following diagram describes the main data flow, and the components required when handling HTTP requests and responses. As we already implemented the model, the main components we'll create are: * URL mappers to forward the supported URLs (and any information encoded in the URLs) to the appropriate view functions. * View functions to get the requested data from the models, create HTML pages that display the data, and return the pages to the user to view in the browser. * Templates to use when rendering data in the views. ![Main data flow diagram: URL, Model, View & Template component required when handling HTTP requests and responses in a Django application. A HTTP request hits a Django server gets forwarded to the 'urls.py' file of the URLS component. The request is forwarded to the appropriate view. The view can read and write data from the Models 'models.py' file containing the code related to models. The view also accesses the HTML file template component. The view returns the response back to the user.](/en-US/docs/Learn/Server-side/Django/Home_page/basic-django.png) As you'll see in the next section, we have 5 pages to display, which is too much information to document in a single article. Therefore, this article will focus on how to implement the home page, and we'll cover the other pages in a subsequent article. This should give you a good end-to-end understanding of how URL mappers, views, and models work in practice. Defining the resource URLs -------------------------- As this version of LocalLibrary is essentially read-only for end users, we just need to provide a landing page for the site (a home page), and pages that *display* list and detail views for books and authors. The URLs that we'll need for our pages are: * `catalog/` — The home (index) page. * `catalog/books/` — A list of all books. * `catalog/authors/` — A list of all authors. * `catalog/book/<id>` — The detail view for a particular book, with a field primary key of `<id>` (the default). For example, the URL for the third book added to the list will be `/catalog/book/3`. * `catalog/author/<id>` — The detail view for the specific author with a primary key field of `<id>`. For example, the URL for the 11th author added to the list will be `/catalog/author/11`. The first three URLs will return the index page, books list, and authors list. These URLs do not encode any additional information, and the queries that fetch data from the database will always be the same. However, the results that the queries return will depend on the contents of the database. By contrast the final two URLs will display detailed information about a specific book or author. These URLs encode the identity of the item to display (represented by `<id>` above). The URL mapper will extract the encoded information and pass it to the view, and the view will dynamically determine what information to get from the database. By encoding the information in the URL we will use a single set of a URL mapping, a view, and a template to handle all books (or authors). **Note:** With Django, you can construct your URLs however you require — you can encode information in the body of the URL as shown above, or include `GET` parameters in the URL, for example `/book/?id=6`. Whichever approach you use, the URLs should be kept clean, logical, and readable, as recommended by the W3C. The Django documentation recommends encoding information in the body of the URL to achieve better URL design. As mentioned in the overview, the rest of this article describes how to construct the index page. Creating the index page ----------------------- The first page we'll create is the index page (`catalog/`). The index page will include some static HTML, along with generated "counts" of different records in the database. To make this work we'll create a URL mapping, a view, and a template. **Note:** It's worth paying a little extra attention in this section. Most of the information also applies to the other pages we'll create. ### URL mapping When we created the skeleton website, we updated the **locallibrary/urls.py** file to ensure that whenever a URL that starts with `catalog/` is received, the *URLConf* module `catalog.urls` will process the remaining substring. The following code snippet from **locallibrary/urls.py** includes the `catalog.urls` module: ```python urlpatterns += [ path('catalog/', include('catalog.urls')), ] ``` **Note:** Whenever Django encounters the import function `django.urls.include()`, it splits the URL string at the designated end character and sends the remaining substring to the included *URLconf* module for further processing. We also created a placeholder file for the *URLConf* module, named **/catalog/urls.py**. Add the following lines to that file: ```python urlpatterns = [ path('', views.index, name='index'), ] ``` The `path()` function defines the following: * A URL pattern, which is an empty string: `''`. We'll discuss URL patterns in detail when working on the other views. * A view function that will be called if the URL pattern is detected: `views.index`, which is the function named `index()` in the **views.py** file. The `path()` function also specifies a `name` parameter, which is a unique identifier for *this* particular URL mapping. You can use the name to "reverse" the mapper, i.e. to dynamically create a URL that points to the resource that the mapper is designed to handle. For example, we can use the name parameter to link to our home page from any other page by adding the following link in a template: ```django <a href="{% url 'index' %}">Home</a>. ``` **Note:** We can hard code the link as in `<a href="/catalog/">Home</a>`), but if we change the pattern for our home page, for example, to `/catalog/index`) the templates will no longer link correctly. Using a reversed URL mapping is more robust. ### View (function-based) A view is a function that processes an HTTP request, fetches the required data from the database, renders the data in an HTML page using an HTML template, and then returns the generated HTML in an HTTP response to display the page to the user. The index view follows this model — it fetches information about the number of `Book`, `BookInstance`, available `BookInstance` and `Author` records that we have in the database, and passes that information to a template for display. Open **catalog/views.py** and note that the file already imports the render() shortcut function to generate an HTML file using a template and data: ```python from django.shortcuts import render # Create your views here. ``` Paste the following lines at the bottom of the file: ```python from .models import Book, Author, BookInstance, Genre def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter(status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() context = { 'num\_books': num_books, 'num\_instances': num_instances, 'num\_instances\_available': num_instances_available, 'num\_authors': num_authors, } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) ``` The first line imports the model classes that we'll use to access data in all our views. The first part of the view function fetches the number of records using the `objects.all()` attribute on the model classes. It also gets a list of `BookInstance` objects that have a value of 'a' (Available) in the status field. You can find more information about how to access model data in our previous tutorial Django Tutorial Part 3: Using models > Searching for records. At the end of the view function we call the `render()` function to create an HTML page and return the page as a response. This shortcut function wraps a number of other functions to simplify a very common use case. The `render()` function accepts the following parameters: * the original `request` object, which is an `HttpRequest`. * an HTML template with placeholders for the data. * a `context` variable, which is a Python dictionary, containing the data to insert into the placeholders. We'll talk more about templates and the `context` variable in the next section. Let's get to creating our template so we can actually display something to the user! ### Template A template is a text file that defines the structure or layout of a file (such as an HTML page), it uses placeholders to represent actual content. A Django application created using **startapp** (like the skeleton of this example) will look for templates in a subdirectory named '**templates**' of your applications. For example, in the index view that we just added, the `render()` function will expect to find the file ***index.html*** in **/locallibrary/catalog/templates/** and will raise an error if the file is not present. You can check this by saving the previous changes and accessing `127.0.0.1:8000` in your browser - it will display a fairly intuitive error message: "`TemplateDoesNotExist at /catalog/`", and other details. **Note:** Based on your project's settings file, Django will look for templates in a number of places, searching in your installed applications by default. You can find out more about how Django finds templates and what template formats it supports in the Templates section of the Django documentation. #### Extending templates The index template will need standard HTML markup for the head and body, along with navigation sections to link to the other pages of the site (which we haven't created yet), and to sections that display introductory text and book data. Much of the HTML and navigation structure will be the same in every page of our site. Instead of duplicating boilerplate code on every page, you can use the Django templating language to declare a base template, and then extend it to replace just the bits that are different for each specific page. The following code snippet is a sample base template from a **base\_generic.html** file. We'll be creating the template for LocalLibrary shortly. The sample below includes common HTML with sections for a title, a sidebar, and main contents marked with the named `block` and `endblock` template tags. You can leave the blocks empty, or include default content to use when rendering pages derived from the template. **Note:** Template *tags* are functions that you can use in a template to loop through lists, perform conditional operations based on the value of a variable, and so on. In addition to template tags, the template syntax allows you to reference variables that are passed into the template from the view, and use *template filters* to format variables (for example, to convert a string to lower case). ```django <!DOCTYPE html> <html lang="en"> <head> {% block title %} <title>Local Library</title> {% endblock %} </head> <body> {% block sidebar %} <!-- insert default navigation text for every page --> {% endblock %} {% block content %} <!-- default content text (typically empty) --> {% endblock %} </body> </html> ``` When defining a template for a particular view, we first specify the base template using the `extends` template tag — see the code sample below. Then we declare what sections from the template we want to replace (if any), using `block`/`endblock` sections as in the base template. For example, the code snippet below shows how to use the `extends` template tag and override the `content` block. The generated HTML will include the code and structure defined in the base template, including the default content you defined in the `title` block, but the new `content` block in place of the default one. ```django {% extends "base\_generic.html" %} {% block content %} <h1>Local Library Home</h1> <p> Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>! </p> {% endblock %} ``` #### The LocalLibrary base template We will use the following code snippet as the base template for the *LocalLibrary* website. As you can see, it contains some HTML code and defines blocks for `title`, `sidebar`, and `content`. We have a default title and a default sidebar with links to lists of all books and authors, both enclosed in blocks to be easily changed in the future. **Note:** We also introduce two additional template tags: `url` and `load static`. These tags will be explained in following sections. Create a new file **base\_generic.html** in **/locallibrary/catalog/templates/** and paste the following code to the file: ```django <!DOCTYPE html> <html lang="en"> <head> {% block title %} <title>Local Library</title> {% endblock %} <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <!-- Add additional CSS in static file --> {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}" /> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-sm-2"> {% block sidebar %} <ul class="sidebar-nav"> <li><a href="{% url 'index' %}">Home</a></li> <li><a href="">All books</a></li> <li><a href="">All authors</a></li> </ul> {% endblock %} </div> <div class="col-sm-10 ">{% block content %}{% endblock %}</div> </div> </div> </body> </html> ``` The template includes CSS from Bootstrap to improve the layout and presentation of the HTML page. Using Bootstrap (or another client-side web framework) is a quick way to create an attractive page that displays well on different screen sizes. The base template also references a local CSS file (**styles.css**) that provides additional styling. Create a **styles.css** file in **/locallibrary/catalog/static/css/** and paste the following code in the file: ```css .sidebar-nav { margin-top: 20px; padding: 0; list-style: none; } ``` #### The index template Create a new HTML file **index.html** in **/locallibrary/catalog/templates/** and paste the following code in the file. This code extends our base template on the first line, and then replaces the default `content` block for the template. ```django {% extends "base\_generic.html" %} {% block content %} <h1>Local Library Home</h1> <p> Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>! </p> <h2>Dynamic content</h2> <p>The library has the following record counts:</p> <ul> <li><strong>Books:</strong> {{ num\_books }}</li> <li><strong>Copies:</strong> {{ num\_instances }}</li> <li><strong>Copies available:</strong> {{ num\_instances\_available }}</li> <li><strong>Authors:</strong> {{ num\_authors }}</li> </ul> {% endblock %} ``` In the *Dynamic content* section we declare placeholders (*template variables*) for the information from the view that we want to include. The variables are enclosed with double brace (handlebars). **Note:** You can easily recognize template variables and template tags (functions) - variables are enclosed in double braces (`{{ num_books }}`), and tags are enclosed in single braces with percentage signs (`{% extends "base_generic.html" %}`). The important thing to note here is that variables are named with the *keys* that we pass into the `context` dictionary in the `render()` function of our view (see sample below). Variables will be replaced with their associated *values* when the template is rendered. ```python context = { 'num\_books': num_books, 'num\_instances': num_instances, 'num\_instances\_available': num_instances_available, 'num\_authors': num_authors, } return render(request, 'index.html', context=context) ``` #### Referencing static files in templates Your project is likely to use static resources, including JavaScript, CSS, and images. Because the location of these files might not be known (or might change), Django allows you to specify the location in your templates relative to the `STATIC_URL` global setting. The default skeleton website sets the value of `STATIC_URL` to '`/static/`', but you might choose to host these on a content delivery network or elsewhere. Within the template you first call the `load` template tag specifying "static" to add the template library, as shown in the code sample below. You can then use the `static` template tag and specify the relative URL to the required file. ```django <!-- Add additional CSS in static file --> {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}" /> ``` You can add an image into the page in a similar way, for example: ```django {% load static %} <img src="{% static 'catalog/images/local\_library\_model\_uml.png' %}" alt="UML diagram" style="width:555px;height:540px;" /> ``` **Note:** The samples above specify where the files are located, but Django does not serve them by default. We configured the development web server to serve files by modifying the global URL mapper (**/locallibrary/locallibrary/urls.py**) when we created the website skeleton, but still need to enable file serving in production. We'll look at this later. For more information on working with static files see Managing static files in the Django documentation. #### Linking to URLs The base template above introduced the `url` template tag. ```django <li><a href="{% url 'index' %}">Home</a></li> ``` This tag accepts the name of a `path()` function called in your **urls.py** and the values for any arguments that the associated view will receive from that function, and returns a URL that you can use to link to the resource. #### Configuring where to find the templates The location where Django searches for templates is specified in the `TEMPLATES` object in the **settings.py** file. The default **settings.py** (as created for this tutorial) looks something like this: ```python TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP\_DIRS': True, 'OPTIONS': { 'context\_processors': [ 'django.template.context\_processors.debug', 'django.template.context\_processors.request', 'django.contrib.auth.context\_processors.auth', 'django.contrib.messages.context\_processors.messages', ], }, }, ] ``` The setting of `'APP_DIRS': True`, is the most important, as it tells Django to search for templates in a subdirectory of each application in the project, named "templates" (this makes it easier to group templates with their associated application for easy re-use). We can also specify specific locations for Django to search for directories using `'DIRS': []` (but that isn't needed yet). **Note:** You can find out more about how Django finds templates and what template formats it supports in the Templates section of the Django documentation. What does it look like? ----------------------- At this point we have created all required resources to display the index page. Run the server (`python3 manage.py runserver`) and open `http://127.0.0.1:8000/` in your browser. If everything is configured correctly, your site should look like the following screenshot. ![Index page for LocalLibrary website](/en-US/docs/Learn/Server-side/Django/Home_page/index_page_ok.png) **Note:** The **All books** and **All authors** links will not work yet because the paths, views, and templates for those pages are not defined. We just inserted placeholders for those links in the `base_generic.html` template. Challenge yourself ------------------ Here are a couple of tasks to test your familiarity with model queries, views, and templates. 1. The LocalLibrary base template includes a `title` block. Override this block in the index template and create a new title for the page. **Note:** The section Extending templates explains how to create blocks and extend a block in another template. 2. Modify the view to generate counts for *genres* and *books* that contain a particular word (case insensitive), and pass the results to the `context`. You accomplish this in a similar way to creating and using `num_books` and `num_instances_available`. Then update the index template to include these variables. Summary ------- We just created the home page for our site — an HTML page that displays a number of records from the database and links to other yet-to-be-created pages. Along the way we learned fundamental information about URL mappers, views, querying the database with models, passing information to a template from a view, and creating and extending templates. In the next article we'll build upon this knowledge to create the remaining four pages of our website. See also -------- * Writing your first Django app, part 3: Views and Templates (Django docs) * URL dispatcher (Django docs) * View functions (DJango docs) * Templates (Django docs) * Managing static files (Django docs) * Django shortcut functions (Django docs) * Previous * Overview: Django * Next
Django web application security - Learn web development
Django web application security =============================== * Previous * Overview: Django * Next Protecting user data is an essential part of any website design. We previously explained some of the more common security threats in the article Web security — this article provides a practical demonstration of how Django's in-built protections handle such threats. | | | | --- | --- | | Prerequisites: | Read the Server-side programming "Website security" topic. Complete the Django tutorial topics up to (and including) at least Django Tutorial Part 9: Working with forms. | | Objective: | To understand the main things you need to do (or not do) to secure your Django web application. | Overview -------- The Website security topic provides an overview of what website security means for server-side design, and some of the more common threats that you should protect against. One of the key messages in that article is that almost all attacks are successful when the web application trusts data from the browser. **Warning:** The single most important lesson you can learn about website security is to **never trust data from the browser**. This includes `GET` request data in URL parameters, `POST` data, HTTP headers and cookies, user-uploaded files, etc. Always check and sanitize all incoming data. Always assume the worst. The good news for Django users is that many of the more common threats are handled by the framework! The Security in Django (Django docs) article explains Django's security features and how to secure a Django-powered website. Common threats/protections -------------------------- Rather than duplicate the Django documentation here, in this article we'll demonstrate just a few of the security features in the context of our Django LocalLibrary tutorial. ### Cross site scripting (XSS) XSS is a term used to describe a class of attacks that allow an attacker to inject client-side scripts *through* the website into the browsers of other users. This is usually achieved by storing malicious scripts in the database where they can be retrieved and displayed to other users, or by getting users to click a link that will cause the attacker's JavaScript to be executed by the user's browser. Django's template system protects you against the majority of XSS attacks by escaping specific characters that are "dangerous" in HTML. We can demonstrate this by attempting to inject some JavaScript into our LocalLibrary website using the Create-author form we set up in Django Tutorial Part 9: Working with forms. 1. Start the website using the development server (`python3 manage.py runserver`). 2. Open the site in your local browser and login to your superuser account. 3. Navigate to the author-creation page (which should be at URL: `http://127.0.0.1:8000/catalog/author/create/`). 4. Enter names and date details for a new user, and then append the following text to the Last Name field: `<script>alert('Test alert');</script>`. ![Author Form XSS test](/en-US/docs/Learn/Server-side/Django/web_application_security/author_create_form_alert_xss.png) **Note:** This is a harmless script that, if executed, will display an alert box in your browser. If the alert is displayed when you submit the record then the site is vulnerable to XSS threats. 5. Press **Submit** to save the record. 6. When you save the author it will be displayed as shown below. Because of the XSS protections the `alert()` should not be run. Instead the script is displayed as plain text. ![Author detail view XSS test](/en-US/docs/Learn/Server-side/Django/web_application_security/author_detail_alert_xss.png) If you view the page HTML source code, you can see that the dangerous characters for the script tags have been turned into their harmless escape code equivalents (for example, `>` is now `&gt;`) ```html <h1> Author: Boon&lt;script&gt;alert(&#39;Test alert&#39;);&lt;/script&gt;, David (Boonie) </h1> ``` Using Django templates protects you against the majority of XSS attacks. However it is possible to turn off this protection, and the protection isn't automatically applied to all tags that wouldn't normally be populated by user input (for example, the `help_text` in a form field is usually not user-supplied, so Django doesn't escape those values). It is also possible for XSS attacks to originate from other untrusted source of data, such as cookies, Web services or uploaded files (whenever the data is not sufficiently sanitized before including in a page). If you're displaying data from these sources, then you may need to add your own sanitization code. ### Cross site request forgery (CSRF) protection CSRF attacks allow a malicious user to execute actions using the credentials of another user without that user's knowledge or consent. For example consider the case where we have a hacker who wants to create additional authors for our LocalLibrary. **Note:** Obviously our hacker isn't in this for the money! A more ambitious hacker could use the same approach on other sites to perform much more harmful tasks (such as transferring money to their own accounts, and so on.) In order to do this, they might create an HTML file like the one below, which contains an author-creation form (like the one we used in the previous section) that is submitted as soon as the file is loaded. They would then send the file to all the Librarians and suggest that they open the file (it contains some harmless information, honest!). If the file is opened by any logged in librarian, then the form would be submitted with their credentials and a new author would be created. ```html <html lang="en"> <body onload="document.EvilForm.submit()"> <form action="http://127.0.0.1:8000/catalog/author/create/" method="post" name="EvilForm"> <table> <tr> <th><label for="id\_first\_name">First name:</label></th> <td> <input id="id\_first\_name" maxlength="100" name="first\_name" type="text" value="Mad" required /> </td> </tr> <tr> <th><label for="id\_last\_name">Last name:</label></th> <td> <input id="id\_last\_name" maxlength="100" name="last\_name" type="text" value="Man" required /> </td> </tr> <tr> <th><label for="id\_date\_of\_birth">Date of birth:</label></th> <td> <input id="id\_date\_of\_birth" name="date\_of\_birth" type="text" /> </td> </tr> <tr> <th><label for="id\_date\_of\_death">Died:</label></th> <td> <input id="id\_date\_of\_death" name="date\_of\_death" type="text" value="12/10/2016" /> </td> </tr> </table> <input type="submit" value="Submit" /> </form> </body> </html> ``` Run the development web server, and log in with your superuser account. Copy the text above into a file and then open it in the browser. You should get a CSRF error, because Django has protection against this kind of thing! The way the protection is enabled is that you include the `{% csrf_token %}` template tag in your form definition. This token is then rendered in your HTML as shown below, with a value that is specific to the user on the current browser. ```html <input type="hidden" name="csrfmiddlewaretoken" value="0QRWHnYVg776y2l66mcvZqp8alrv4lb8S8lZ4ZJUWGZFA5VHrVfL2mpH29YZ39PW" /> ``` Django generates a user/browser specific key and will reject forms that do not contain the field, or that contain an incorrect field value for the user/browser. To use this type of attack the hacker now has to discover and include the CSRF key for the specific target user. They also can't use the "scattergun" approach of sending a malicious file to all librarians and hoping that one of them will open it, since the CSRF key is browser specific. Django's CSRF protection is turned on by default. You should always use the `{% csrf_token %}` template tag in your forms and use `POST` for requests that might change or add data to the database. ### Other protections Django also provides other forms of protection (most of which would be hard or not particularly useful to demonstrate): SQL injection protection SQL injection vulnerabilities enable malicious users to execute arbitrary SQL code on a database, allowing data to be accessed, modified, or deleted irrespective of the user's permissions. In almost every case you'll be accessing the database using Django's querysets/models, so the resulting SQL will be properly escaped by the underlying database driver. If you do need to write raw queries or custom SQL then you'll need to explicitly think about preventing SQL injection. Clickjacking protection In this attack a malicious user hijacks clicks meant for a visible top level site and routes them to a hidden page beneath. This technique might be used, for example, to display a legitimate bank site but capture the login credentials in an invisible `<iframe>` controlled by the attacker. Django contains clickjacking protection in the form of the `X-Frame-Options middleware` which, in a supporting browser, can prevent a site from being rendered inside a frame. Enforcing TLS/HTTPS TLS/HTTPS can be enabled on the web server in order to encrypt all traffic between the site and browser, including authentication credentials that would otherwise be sent in plain text (enabling HTTPS is highly recommended). If HTTPS is enabled then Django provides a number of other protections you can use: * `SECURE_PROXY_SSL_HEADER` can be used to check whether content is secure, even if it is incoming from a non-HTTP proxy. * `SECURE_SSL_REDIRECT` is used to redirect all HTTP requests to HTTPS. * Use HTTP Strict Transport Security (HSTS). This is an HTTP header that informs a browser that all future connections to a particular site should always use HTTPS. Combined with redirecting HTTP requests to HTTPS, this setting ensures that HTTPS is always used after a successful connection has occurred. HSTS may either be configured with `SECURE_HSTS_SECONDS` and `SECURE_HSTS_INCLUDE_SUBDOMAINS` or on the Web server. * Use 'secure' cookies by setting `SESSION_COOKIE_SECURE` and `CSRF_COOKIE_SECURE` to `True`. This will ensure that cookies are only ever sent over HTTPS. Host header validation Use `ALLOWED_HOSTS` to only accept requests from trusted hosts. There are many other protections, and caveats to the usage of the above mechanisms. While we hope that this has given you an overview of what Django offers, you should still read the Django security documentation. Summary ------- Django has effective protections against a number of common threats, including XSS and CSRF attacks. In this article we've demonstrated how those particular threats are handled by Django in our *LocalLibrary* website. We've also provided a brief overview of some of the other protections. This has been a very brief foray into web security. We strongly recommend that you read Security in Django to gain a deeper understanding. The next and final step in this module about Django is to complete the assessment task. See also -------- * Security in Django (Django docs) * Server side website security (MDN) * Securing your site (MDN) * Previous * Overview: Django * Next
Django Tutorial Part 11: Deploying Django to production - Learn web development
Django Tutorial Part 11: Deploying Django to production ======================================================= * Previous * Overview: Django * Next Now you've created (and tested) an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production. | | | | --- | --- | | Prerequisites: | Complete all previous tutorial topics, including Django Tutorial Part 10: Testing a Django web application. | | Objective: | To learn where and how you can deploy a Django app to production. | Overview -------- Once your site is finished (or finished "enough" to start public testing) you're going to need to host it somewhere more public and accessible than your personal development computer. Up to now you've been working in a development environment, using the Django development web server to share your site to the local browser/network, and running your website with (insecure) development settings that expose debug and other private information. Before you can host a website externally you're first going to have to: * Make a few changes to your project settings. * Choose an environment for hosting the Django app. * Choose an environment for hosting any static files. * Set up a production-level infrastructure for serving your website. This tutorial provides some guidance on your options for choosing a hosting site, a brief overview of what you need to do in order to get your Django app ready for production, and a working example of how to install the LocalLibrary website onto the Railway cloud hosting service. What is a production environment? --------------------------------- The production environment is the environment provided by the server computer where you will run your website for external consumption. The environment includes: * Computer hardware on which the website runs. * Operating system (e.g. Linux, Windows). * Programming language runtime and framework libraries on top of which your website is written. * Web server used to serve pages and other content (e.g. Nginx, Apache). * Application server that passes "dynamic" requests between your Django website and the web server. * Databases on which your website is dependent. **Note:** Depending on how your production environment is configured you might also have a reverse proxy, load balancer, and so on. The server computer could be located on your premises and connected to the internet by a fast link, but it is far more common to use a computer that is hosted "in the cloud". What this actually means is that your code is run on some remote computer (or possibly a "virtual" computer) in your hosting company's data center(s). The remote server will usually offer some guaranteed level of computing resources (CPU, RAM, storage memory, etc.) and internet connectivity for a certain price. This sort of remotely accessible computing/networking hardware is referred to as *Infrastructure as a Service (IaaS)*. Many IaaS vendors provide options to preinstall a particular operating system, onto which you must install the other components of your production environment. Other vendors allow you to select more fully-featured environments, perhaps including a complete Django and web-server setup. **Note:** Pre-built environments can make setting up your website very easy because they reduce the configuration, but the available options may limit you to an unfamiliar server (or other components) and may be based on an older version of the OS. Often it is better to install components yourself, so that you get the ones that you want, and when you need to upgrade parts of the system, you have some idea of where to start! Other hosting providers support Django as part of a *Platform as a Service* (PaaS) offering. In this sort of hosting you don't need to worry about most of your production environment (web server, application server, load balancers) as the host platform takes care of those for you — along with most of what you need to do in order to scale your application. That makes deployment quite easy, because you just need to concentrate on your web application and not all the other server infrastructure. Some developers will choose the increased flexibility provided by IaaS over PaaS, while others will appreciate the reduced maintenance overhead and easier scaling of PaaS. When you're getting started, setting up your website on a PaaS system is much easier, and so that is what we'll do in this tutorial. **Note:** If you choose a Python/Django-friendly hosting provider they should provide instructions on how to set up a Django website using different configurations of web server, application server, reverse proxy, and so on. (this won't be relevant if you choose a PaaS). For example, there are many step-by-step guides for various configurations in the Digital Ocean Django community docs. Choosing a hosting provider --------------------------- There are well over 100 hosting providers that are known to either actively support or work well with Django (you can find a fairly large list at DjangoFriendly hosts). These vendors provide different types of environments (IaaS, PaaS), and different levels of computing and network resources at different prices. Some of the things to consider when choosing a host: * How busy your site is likely to be and the cost of data and computing resources required to meet that demand. * Level of support for scaling horizontally (adding more machines) and vertically (upgrading to more powerful machines) and the costs of doing so. * Where the supplier has data centres, and hence where access is likely to be fastest. * The host's historical uptime and downtime performance. * Tools provided for managing the site — are they easy to use and are they secure (e.g. SFTP vs. FTP). * Inbuilt frameworks for monitoring your server. * Known limitations. Some hosts will deliberately block certain services (e.g. email). Others offer only a certain number of hours of "live time" in some price tiers, or only offer a small amount of storage. * Additional benefits. Some providers will offer free domain names and support for TLS certificates that you would otherwise have to pay for. * Whether the "free" tier you're relying on expires over time, and whether the cost of migrating to a more expensive tier means you would have been better off using some other service in the first place! The good news when you're starting out is that there are quite a few sites that provide "free" computing environments that are intended for evaluation and testing. These are usually fairly resource constrained/limited environments, and you do need to be aware that they may expire after some introductory period or have other constraints. They are however great for testing low traffic sites in a hosted environment, and can provide an easy migration to paying for more resources when your site gets busier. Popular choices in this category include Railway, Python Anywhere, Amazon Web Services, Microsoft Azure, etc Most providers also offer a "basic" tier that is intended for small production sites, and which provide more useful levels of computing power and fewer limitations. Heroku, Digital Ocean and Python Anywhere are examples of popular hosting providers that have a relatively inexpensive basic computing tier (in the $5 to $10 USD per month range). **Note:** Remember that price is not the only selection criterion. If your website is successful, it may turn out that scalability is the most important consideration. Getting your website ready to publish ------------------------------------- The Django skeleton website created using the *django-admin* and *manage.py* tools are configured to make development easier. Many of the Django project settings (specified in **settings.py**) should be different for production, either for security or performance reasons. **Note:** It is common to have a separate **settings.py** file for production, and/or to conditionally import sensitive settings from a separate file or an environment variable. This file should then be protected, even if the rest of the source code is available on a public repository. The critical settings that you must check are: * `DEBUG`. This should be set as `False` in production (`DEBUG = False`). This stops the sensitive/confidential debug trace and variable information from being displayed. * `SECRET_KEY`. This is a large random value used for CSRF protection, etc. It is important that the key used in production is not in source control or accessible outside the production server. The Django documents suggest that this might best be loaded from an environment variable or read from a server-only file. ```python # Read SECRET\_KEY from an environment variable import os SECRET_KEY = os.environ['SECRET\_KEY'] # OR # Read secret key from a file with open('/etc/secret\_key.txt') as f: SECRET_KEY = f.read().strip() ``` Let's change the *LocalLibrary* application so that we read our `SECRET_KEY` and `DEBUG` variables from environment variables if they are defined, but otherwise use the default values in the configuration file. Open **/locallibrary/settings.py**, disable the original `SECRET_KEY` configuration and add the new lines as shown below. During development no environment variable will be specified for the key, so the default value will be used (it shouldn't matter what key you use here, or if the key "leaks", because you won't use it in production). ```python # SECURITY WARNING: keep the secret key used in production secret! # SECRET\_KEY = 'django-insecure-&psk#na5l=p3q8\_a+-$4w1f^lt3lx1c@d\*p4x$ymm\_rn7pwb87' import os SECRET_KEY = os.environ.get('DJANGO\_SECRET\_KEY', 'django-insecure-&psk#na5l=p3q8\_a+-$4w1f^lt3lx1c@d\*p4x$ymm\_rn7pwb87') ``` Then comment out the existing `DEBUG` setting and add the new line shown below. ```python # SECURITY WARNING: don't run with debug turned on in production! # DEBUG = True DEBUG = os.environ.get('DJANGO\_DEBUG', '') != 'False' ``` The value of the `DEBUG` will be `True` by default, but will only be `False` if the value of the `DJANGO_DEBUG` environment variable is set to `False`. Please note that environment variables are strings and not Python types. We therefore need to compare strings. The only way to set the `DEBUG` variable to `False` is to actually set it to the string `False`. You can set the environment variable to "False" on Linux by issuing the following command: ```bash export DJANGO\_DEBUG=False ``` A full checklist of settings you might want to change is provided in Deployment checklist (Django docs). You can also list a number of these using the terminal command below: ```python python3 manage.py check --deploy ``` Example: Installing LocalLibrary on Railway ------------------------------------------- This section provides a practical demonstration of how to install *LocalLibrary* on Railway. ### Why Railway? We are choosing to use Railway for several reasons: * Railway has a starter plan free tier that is *really* free, albeit with some limitations. The fact that it is affordable for all developers is really important to MDN! * Railway takes care of most of the infrastructure so you don't have to. Not having to worry about servers, load balancers, reverse proxies, and so on, makes it much easier to get started. * Railway has a focus on developer experience for development and deployment, which leads to a faster and softer learning curve than many other alternatives. * The skills and concepts you will learn when using Railway are transferrable. While Railway has some excellent new features, many of the same ideas and approaches are used by other popular hosting services. * The service and plan limitations do not really impact us using Railway for the tutorial. For example: + The starter plan only offers 500 hours of continuous deployment time each month, and $5 of credit that is consumed based on usage. At the end of each month the hours and credit are reset and any projects must be redeployed. These constraints mean that you could run this tutorial continuously for about 21 days, which is more than enough for development and testing. However you wouldn't be able to use this plan for a "real" production site. + The starter plan environment has only 512 MB of RAM and 1 GB of storage memory; more than enough for the tutorial. + At time of writing there is only one supported region, which is in the USA. The service outside this region might be slower, or blocked by local regulations. + Other limitations can be found in the Railway plan documentation. * The service appears to be very reliable, and if you end up loving it, the pricing is predictable, and scaling your app is very easy. While Railway is appropriate for hosting this demonstration, you should take the time to determine if it is suitable for your own website. ### How does Railway work? Web applications are each run in their own isolated and independent virtualized container. In order to execute your application, Railway needs to be able to set up the appropriate environment and dependencies, and also understand how it is launched. For Django apps we provide this information in a number of text files: * **runtime.txt**: states the programming language and version to use. * **requirements.txt**: lists the Python dependencies needed for your site, including Django. * **Procfile**: A list of processes to be executed to start the web application. For Django this will usually be the Gunicorn web application server (with a `.wsgi` script). * **wsgi.py**: WSGI configuration to call our Django application in the Railway environment. Once the application is running it can configure itself using information provided in environment variables. For example, an application that uses a database can get the address using the variable `DATABASE_URL`. The database service itself may be hosted by Railway or some other provider. Developers interact with Railway through the Railway site, and using a special Command Line Interface (CLI) tool. The CLI allows you to associate a local GitHub repository with a railway project, upload the repository from the local branch to the live site, inspect the logs of the running process, set and get configuration variables and much more. One of the most useful features is that you can use the CLI to run your local project with the same environment variables as the live project. In order to get our application to work on Railway, we'll need to put our Django web application into a git repository, add the files above, integrate with a database add-on, and make changes to properly handle static files. Once we've done all that, we can set up a Railway account, get the Railway client, and install our website. That's all the overview you need in order to get started. ### Creating an application repository in GitHub Railway is closely integrated with GitHub and the **git** source code version control system, and you can configure it to automatically deploy changes to a particular repository or branch on GitHub. Alternatively you can push your current local code branch direct to the railway deployment using the CLI. **Note:** Using a source code management system like GitHub is good software development practice. Skip this step if you're already using GitHub to manage your source. There are a lot of ways to work with git, but one of the easiest is to first set up an account on GitHub, create the repository there, and then sync to it locally: 1. Visit https://github.com/ and create an account. 2. Once you are logged in, click the **+** link in the top toolbar and select **New repository**. 3. Fill in all the fields on this form. While these are not compulsory, they are strongly recommended. * Enter a new repository name and description. For example, you might use the name "django\_local\_library" and description "Local Library website written in Django". * Choose **Python** in the *Add .gitignore* selection list. * Choose your preferred license in the *Add license* selection list. * Check **Initialize this repository with a README**. 4. Press **Create repository**. 5. Click the green **Clone or download** button on your new repo page. 6. Copy the URL value from the text field inside the dialog box that appears. If you used the repository name "django\_local\_library", the URL should be something like: `https://github.com/<your_git_user_id>/django_local_library.git`. Now that the repository ("repo") is created we are going to want to clone it on our local computer: 1. Install *git* for your local computer (you can find versions for different platforms here). 2. Open a command prompt/terminal and clone your repo using the URL you copied above: ```bash git clone https://github.com/<your_git_user_id>/django_local_library.git ``` This will create the repo in a new folder in the current working directory. 3. Navigate into the new repo. ```bash cd django_local_library ``` The final steps are to copy your application into this local project directory and then add (or "push", in git lingo) the local repo to your remote GitHub repo: 1. Copy your Django application into this folder (all the files at the same level as **manage.py** and below, **not** their containing locallibrary folder). 2. Open the **.gitignore** file, copy the following lines into the bottom of it, and then save (this file is used to identify files that should not be uploaded to git by default). ``` # Text backup files *.bak # Database *.sqlite3 ``` 3. Open a command prompt/terminal and use the `add` command to add all files to git. This adds the files which aren't ignored by the **.gitignore** file to the "staging area". ```bash git add -A ``` 4. Use the `status` command to check that all files you are about to `commit` are correct (you want to include source files, not binaries, temporary files etc.). It should look a bit like the listing below. ``` > git status On branch main Your branch is up-to-date with 'origin/main'. Changes to be committed: (use "git reset HEAD <file>..." to unstage) modified: .gitignore new file: catalog/__init__.py ... new file: catalog/migrations/0001_initial.py ... new file: templates/registration/password_reset_form.html ``` 5. When you're satisfied, `commit` the files to your local repo. This is essentially equivalent to signing off on the changes and making them an official part of the local repo. ```bash git commit -m "First version of application moved into GitHub" ``` 6. At this point, the remote repo has not been changed. The last step is to synchronize (`push`) your local repo up to the remote GitHub repo using the following command: ```bash git push origin main ``` When this operation completes, you should be able to go back to the page on GitHub where you created your repo, refresh the page, and see that your whole application has now been uploaded. You can continue to update your repo as files change using this add/commit/push cycle. **Note:** This is a good point to make a backup of your "vanilla" project — while some of the changes we're going to be making in the following sections might be useful for deployment on any platform (or development) others might not. The *best* way to do this is to use *git* to manage your revisions. With *git* you can not only go back to a particular old version, but you can maintain this in a separate "branch" from your production changes and cherry-pick any changes to move between production and development branches. Learning Git is well worth the effort, but is beyond the scope of this topic. The *easiest* way to do this is to just copy your files into another location. Use whichever approach best matches your knowledge of git! ### Update the app for Railway This section explains the changes you'll need to make to our *LocalLibrary* application to get it to work on Railway. Note that these changes will not prevent you using the local testing and workflows we've already learned. #### Procfile A *Procfile* is the web application "entry point". It lists the commands that will be executed by Railway to start your site. Create the file `Procfile` (with no file extension) in the root of your GitHub repo and copy/paste in the following text: ``` web: python manage.py migrate && python manage.py collectstatic --no-input && gunicorn locallibrary.wsgi ``` The `web:` prefix tells Railway that this is a web process and can be sent HTTP traffic. We then call the command Django migration command `python manage.py migrate` to set up the database tables. Next, we call the Django command `python manage.py collectstatic` to collect static files into the folder defined by the `STATIC_ROOT` project setting (see the section serving static files in production below). Finally, we start the *gunicorn* process, a popular web application server, passing it configuration information in the module `locallibrary.wsgi` (created with our application skeleton: **/locallibrary/wsgi.py**). Note that you can also use the Procfile to start worker processes or to run other non-interactive tasks before the release is deployed. #### Gunicorn Gunicorn is a pure-Python HTTP server that is commonly used for serving Django WSGI applications on Railway (as referenced in the Procfile above). While we don't need *Gunicorn* to serve our LocalLibrary application during development, we'll install it locally so that it becomes part of our requirements for Railway to set up on the remote server. First make sure that you're in the Python virtual environment that was created when you set up the development environment (use the `workon [name-of-virtual-environment]` command). Then install *Gunicorn* locally on the command line using *pip*: ```bash pip3 install gunicorn ``` #### Database configuration SQLite, the default Django database that you've been using for development, is a reasonable choice for small to medium websites. Unfortunately it cannot be used on some popular hosting services, such as Heroku, because they don't provide persistent data storage in the application environment (a requirement of SQLite). While that might not affect us on Railway, we'll show you another approach that will work on Railway, Heroku, and some other services. The approach is to use a database that runs in its own process somewhere on the Internet, and is accessed by the Django library application using an address passed as an environment variable. In this case we'll use a Postgres database that is also hosted on Railway, but you could use any database hosting service you like. The database connection information will be supplied to Django using an environment variable named `DATABASE_URL`. Rather than hard-coding this information into Django, we'll use the dj-database-url package to parse the `DATABASE_URL` environment variable and automatically convert it to Django's desired configuration format. In addition to installing the *dj-database-url* package we'll also need to install psycopg2, as Django needs this to interact with Postgres databases. ##### dj-database-url *dj-database-url* is used to extract the Django database configuration from an environment variable. Install it locally so that it becomes part of our requirements for Railway to set up on the remote server: ```bash pip3 install dj-database-url ``` ##### settings.py Open **/locallibrary/settings.py** and copy the following configuration into the bottom of the file: ```python # Update database configuration from $DATABASE\_URL environment variable (if defined) import dj_database_url if 'DATABASE\_URL' in os.environ: DATABASES['default'] = dj_database_url.config( conn_max_age=500, conn_health_checks=True, ) ``` Django will now use the database configuration in `DATABASE_URL` if the environment variable is set; otherwise it uses the default SQLite database. The value `conn_max_age=500` makes the connection persistent, which is far more efficient than recreating the connection on every request cycle (this is optional and can be removed if needed). ##### psycopg2 Django needs *psycopg2* to work with Postgres databases. Install it locally so that it becomes part of our requirements for Railway to set up on the remote server: ```bash pip3 install psycopg2-binary ``` Note that Django will use the SQLite database during development by default, unless `DATABASE_URL` is set. You can switch to Postgres completely and use the same hosted database for development and production by setting the same environment variable in your development environment (Railway makes it easy to use the same environment for production and development). Alternatively you can also install and use a self-hosted Postgres database on your local computer. #### Serving static files in production During development we use Django and the Django development web server to serve both our dynamic HTML and our static files (CSS, JavaScript, etc.). This is inefficient for static files, because the requests have to pass through Django even though Django doesn't do anything with them. While this doesn't matter during development, it would have a significant performance impact if we were to use the same approach in production. In the production environment we typically separate the static files from the Django web application, making it easier to serve them directly from the web server or from a content delivery network (CDN). The important setting variables are: * `STATIC_URL`: This is the base URL location from which static files will be served, for example on a CDN. * `STATIC_ROOT`: This is the absolute path to a directory where Django's *collectstatic* tool will gather any static files referenced in our templates. Once collected, these can then be uploaded as a group to wherever the files are to be hosted. * `STATICFILES_DIRS`: This lists additional directories that Django's *collectstatic* tool should search for static files. Django templates refer to static file locations relative to a `static` tag (you can see this in the base template defined in Django Tutorial Part 5: Creating our home page), which in turn maps to the `STATIC_URL` setting. Static files can therefore be uploaded to any host and you can update your application to find them using this setting. The *collectstatic* tool is used to collect static files into the folder defined by the `STATIC_ROOT` project setting. It is called with the following command: ```bash python3 manage.py collectstatic ``` For this tutorial, *collectstatic* is run by Railway before the application is uploaded, copying all the static files in the application to the location specified in `STATIC_ROOT`. `Whitenoise` then finds the files from the location defined by `STATIC_ROOT` (by default) and serves them at the base URL defined by `STATIC_URL`. ##### settings.py Open **/locallibrary/settings.py** and copy the following configuration into the bottom of the file. The `BASE_DIR` should already have been defined in your file (the `STATIC_URL` may already have been defined within the file when it was created. While it will cause no harm, you might as well delete the duplicate previous reference). ```python # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ # The absolute path to the directory where collectstatic will collect static files for deployment. STATIC_ROOT = BASE_DIR / 'staticfiles' # The URL to use when referring to static files (where they will be served from) STATIC_URL = '/static/' ``` We'll actually do the file serving using a library called WhiteNoise, which we install and configure in the next section. #### Whitenoise There are many ways to serve static files in production (we saw the relevant Django settings in the previous sections). The WhiteNoise project provides one of the easiest methods for serving static assets directly from Gunicorn in production. Railway calls *collectstatic* to prepare your static files for use by WhiteNoise after it uploads your application. Check out WhiteNoise documentation for an explanation of how it works and why the implementation is a relatively efficient method for serving these files. The steps to set up *WhiteNoise* to use with the project are given here (and reproduced below): ##### Install whitenoise Install whitenoise locally using the following command: ```bash pip3 install whitenoise ``` ##### settings.py To install *WhiteNoise* into your Django application, open **/locallibrary/settings.py**, find the `MIDDLEWARE` setting and add the `WhiteNoiseMiddleware` near the top of the list, just below the `SecurityMiddleware`: ```python MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ``` Optionally, you can reduce the size of the static files when they are served (this is more efficient). Just add the following to the bottom of **/locallibrary/settings.py**: ```python # Static file serving. # https://whitenoise.readthedocs.io/en/stable/django.html#add-compression-and-caching-support STORAGES = { # ... "staticfiles": { "BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage", }, } ``` You don't need to do anything else to configure *WhiteNoise* because it uses your project settings for `STATIC_ROOT` and `STATIC_URL` by default. #### Requirements The Python requirements of your web application must be stored in a file **requirements.txt** in the root of your repository. Railway will then install these automatically when it rebuilds your environment. You can create this file using *pip* on the command line (run the following in the repo root): ```bash pip3 freeze > requirements.txt ``` After installing all the different dependencies above, your **requirements.txt** file should have *at least* these items listed (though the version numbers may be different). Please delete any other dependencies not listed below, unless you've explicitly added them for this application. ``` Django==4.2.3 dj-database-url==2.0.0 gunicorn==21.2.3 psycopg2-binary==2.9.6 wheel==0.38.1 whitenoise==6.5.0 ``` #### Runtime The **runtime.txt** file, if defined, tells Railway which version of Python to use. Create the file in the root of the repo and add the following text: ``` python-3.10.2 ``` **Note:** Hosting providers do not necessarily support every Python runtime minor version. They will generally use the closest supported version to the value that you specify. #### Re-test and save changes to GitHub Before you proceed, first test the site again locally and make sure it wasn't broken by any of the changes above. Run the development web server as usual and then check the site still works as you expect on your browser. ```bash python3 manage.py runserver ``` Next, lets `push` the changes to GitHub. In the terminal (after having navigated to our local repository), enter the following commands: ```python git add -A git commit -m "Added files and changes required for deployment" git push origin main ``` We should now be ready to start deploying LocalLibrary on Railway. ### Get a Railway account To start using Railway you will first need to create an account: * Go to railway.app and click the **Login** link in the top toolbar. * Select GitHub in the popup to login using your GitHub credentials * You may then need to go to your email and verify your account. * You'll then be logged in to the Railway.app dashboard: https://railway.app/dashboard. ### Deploy on Railway from GitHub Next we'll set up Railway to deploy our library from GitHub. First choose the **Dashboard** option from the site top menu, then select the **New Project** button: ![Railway website dashboard with new project button](/en-US/docs/Learn/Server-side/Django/Deployment/railway_new_project_button.png) Railway will display a list of options for the new project, including the option to deploy a project from a template that is first created in your GitHub account, and a number of databases. Select **Deploy from GitHub repo**. ![Railway website screen - deploy](/en-US/docs/Learn/Server-side/Django/Deployment/railway_new_project_button_deploy_github_repo.png) All projects in the GitHub repos you shared with Railway during setup are displayed. Select your GitHub repository for the local library: `<user-name>/django-locallibrary-tutorial`. ![Railway website screen showing a dialog to choose an existing GitHub repository or choose a new one](/en-US/docs/Learn/Server-side/Django/Deployment/railway_new_project_button_deploy_github_selectrepo.png) Confirm your deployment by selecting **Deploy Now**. ![Confirmation screen - select deploy](/en-US/docs/Learn/Server-side/Django/Deployment/railway_new_project_deploy_confirm.png) Railway will then load and deploy your project, displaying progress on the deployments tab. When deployment successfully completes, you'll see a screen like the one below. ![Railway website screen - deployment](/en-US/docs/Learn/Server-side/Django/Deployment/railway_project_deploy.png) You can click the site URL (highlighted above) to open the site in a browser (it still won't work, because the setup is not complete). ### Set ALLOWED\_HOSTS and CSRF\_TRUSTED\_ORIGINS When the site is opened, at this point you'll see an error debug screen as shown below. This is a Django security error that is raised because our source code is not running on an "allowed host". ![A detailed error page with a full traceback of an invalid HTTP_HOST header](/en-US/docs/Learn/Server-side/Django/Deployment/site_error_dissallowed_host.png) **Note:** This kind of debug information is very useful when you're getting set up, but is a security risk in a deployed site. We'll show you how to disable it once the site is up and running. Open **/locallibrary/settings.py** in your GitHub project and change the ALLOWED\_HOSTS setting to include your Railway site URL: ```python ## For example, for a site URL at 'web-production-3640.up.railway.app' ## (replace the string below with your own site URL): ALLOWED_HOSTS = ['web-production-3640.up.railway.app', '127.0.0.1'] # During development, you can instead set just the base URL # (you might decide to change the site a few times). # ALLOWED\_HOSTS = ['.railway.com','127.0.0.1'] ``` Since the applications uses CSRF protection, you will also need to set the CSRF\_TRUSTED\_ORIGINS key. Open **/locallibrary/settings.py** and add a line like the one below: ```python ## For example, for a site URL is at 'web-production-3640.up.railway.app' ## (replace the string below with your own site URL): CSRF_TRUSTED_ORIGINS = ['https://web-production-3640.up.railway.app'] # During development/for this tutorial you can instead set just the base URL # CSRF\_TRUSTED\_ORIGINS = ['https://\*.railway.app'] ``` Then save your settings and commit them to your GitHub repo (Railway will automatically update and redeploy your application). ```bash git add -A git commit -m 'Update ALLOWED\_HOSTS and CSRF\_TRUSTED\_ORIGINS with site URL' git push origin main ``` ### Provision and connect a Postgres SQL database Next we need to create a Postgres database and connect it to the Django application that we just deployed. (If you open the site now you'll get a new error because the database cannot be accessed). We will create the database as part of the application project, although you can create the database in its own separate project. On Railway, choose the **Dashboard** option from the site top menu and then select your application project. At this stage it just contains a single service for your application (this can be selected to set variables and other details of the service). The **Settings** button can be selected to change project-wide settings. Select the **New** button, which is used to add services to the project. ![Railway project with new service button highlighted](/en-US/docs/Learn/Server-side/Django/Deployment/railway_project_open_no_database.png) Select **Database** when prompted about the type of service to add: ![Railway project - select database as new service](/en-US/docs/Learn/Server-side/Django/Deployment/railway_project_add_database.png) Then select **Add PostgreSQL** to start adding the database ![Railway project - select Postgres as new service](/en-US/docs/Learn/Server-side/Django/Deployment/railway_project_add_database_select_type.png) Railway will then provision a service containing an empty database in the same project. On completion you will now see both the application and database services in the project view. ![Railway project with application and Postgres database service](/en-US/docs/Learn/Server-side/Django/Deployment/railway_project_two_services.png) Select the PostgreSQL service to display information about the database. Open the *Connect* tab and copy the "Postgres Connection URL" (this is the address that we set up the locallibrary to read as an environment variable). ![Railway website screen with provision Postgres container command line text and connection URL](/en-US/docs/Learn/Server-side/Django/Deployment/railway_postgresql_connect.png) To make this accessible to the library application we need to add it to the application process using an environment variable. First open the application service. Then select the *Variables* tab and press the **New Variable** button. Enter the variable name `DATABASE_URL` and the connection URL you copied for the database. This will look something like the screen shown below. ![Railway website variables screen - add database url](/en-US/docs/Learn/Server-side/Django/Deployment/railway_variables_database_url.png) Select **Add** to add the variable; the project will then redeploy. If you open the project now it should display just as it did locally. Note however that there is no way to populate the library with data yet, because we have not yet created a superuser account. We'll do that using the CLI tool on our local computer. ### Install the client Download and install the Railway client for your local operating system by following the instructions here. After the client is installed you will be able to run commands. Some of the more important operations include deploying the current directory of your computer to an associated Railway project (without having to upload to GitHub), and running your Django project locally using the same settings as you have on the production server. We show these in the next sections. You can get a list of all the possible commands by entering the following in a terminal. ```bash railway help ``` **Note:** In the following section we use `railway login` and `railway link` to link the current project to a directory. If you are logged out by the system, you will need to call both commands again to re-link the project. ### Configure a superuser In order to create a superuser, we need to call the Django `createsuperuser` command against the production database (this is the same operation as we ran locally in Django Tutorial Part 4: Django admin site > Creating a superuser). Railway doesn't provide direct terminal access to the server, and we can't add this command to the Procfile because it is interactive. What we can do is call this command locally on our Django project when it is connected to the *production* database. The Railway client makes this easy by providing a mechanism to run commands locally using the same environment variables as the production server, including the database connection string. First open a terminal or command prompt in a git clone of your locallibrary project. Then login to your browser account using the `login` or `login --browserless` command (follow any resulting prompts and instructions from the client or website to complete the login): ```bash railway login ``` Once logged in, link your current locallibrary directory to the associated Railway project using the following command. Note that you will need to select/enter a particular project when prompted: ```bash railway link ``` Now that the local directory and project are *linked* you can run the local Django project with settings from the production environment. First ensure that your normal Django development environment is ready. Then call the following command, entering name, email, and password as required: ```bash railway run python manage.py createsuperuser ``` You should now be able to open your website admin area (`https://[your-url].railway.app/admin/`) and populate the database, just as shown in Django Tutorial Part 4: Django admin site). ### Setting configuration variables The final step is to make the site secure. Specifically, we need to disable debug logging and set a secret CSRF key. The work to read the needed values from environment variables was done in getting your website ready to publish (see `DJANGO_DEBUG` and `DJANGO_SECRET_KEY`). Open the information screen for the project and select the *Variables* tab. This should already have the `DATABASE_URL` as shown below. ![Railway - add a new variable screen](/en-US/docs/Learn/Server-side/Django/Deployment/railway_variable_new.png) There are many ways to generate a cryptographically secret key. A simple way is to run the following Python command on your development computer: ```bash python -c "import secrets; print(secrets.token\_urlsafe())" ``` Select the **New Variable** button and enter the key `DJANGO_SECRET_KEY` with your secret value (then select **Add**). Then enter the key `DJANGO_DEBUG` with the value `False`. The final set of variables should look like this: ![Railway screen showing all the project variables](/en-US/docs/Learn/Server-side/Django/Deployment/railway_variables_all.png) ### Debugging The Railway client provides the logs command to show the tail of logs (a more full log is available on the site for each project): ```bash railway logs ``` If you need more information than this can provide you will need to start looking into Django Logging. Summary ------- That's the end of this tutorial on setting up Django apps in production, and also the series of tutorials on working with Django. We hope you've found them useful. You can check out a fully worked-through version of the source code on GitHub here. The next step is to read our last few articles, and then complete the assessment task. See also -------- * Deploying Django (Django docs) + Deployment checklist (Django docs) + Deploying static files (Django docs) + How to deploy with WSGI (Django docs) + How to use Django with Apache and mod\_wsgi (Django docs) + How to use Django with Gunicorn (Django docs) * Railway Docs + CLI * Digital Ocean + How To Serve Django Applications with uWSGI and Nginx on Ubuntu 16.04 + Other Digital Ocean Django community docs * Heroku Docs (similar setup concepts) + Configuring Django apps for Heroku (Heroku docs) + Getting Started on Heroku with Django (Heroku docs) + Django and Static Assets (Heroku docs) + Concurrency and Database Connections in Django (Heroku docs) + How Heroku works (Heroku docs) + Dynos and the Dyno Manager (Heroku docs) + Configuration and Config Vars (Heroku docs) + Limits (Heroku docs) + Deploying Python applications with Gunicorn (Heroku docs) + Deploying Python and Django apps on Heroku (Heroku docs) * Previous * Overview: Django * Next
Django Tutorial Part 10: Testing a Django web application - Learn web development
Django Tutorial Part 10: Testing a Django web application ========================================================= * Previous * Overview: Django * Next As websites grow they become harder to test manually. Not only is there more to test, but, as interactions between components become more complex, a small change in one area can impact other areas, so more changes will be required to ensure everything keeps working and errors are not introduced as more changes are made. One way to mitigate these problems is to write automated tests, which can easily and reliably be run every time you make a change. This tutorial shows how to automate *unit testing* of your website using Django's test framework. | | | | --- | --- | | Prerequisites: | Complete all previous tutorial topics, including Django Tutorial Part 9: Working with forms. | | Objective: | To understand how to write unit tests for Django-based websites. | Overview -------- The Local Library currently has pages to display lists of all books and authors, detail views for `Book` and `Author` items, a page to renew `BookInstance` items, and pages to create, update, and delete `Author` items (and `Book` records too, if you completed the *challenge* in the forms tutorial). Even with this relatively small site, manually navigating to each page and *superficially* checking that everything works as expected can take several minutes. As we make changes and grow the site, the time required to manually check that everything works "properly" will only grow. If we were to continue as we are, eventually we'd be spending most of our time testing, and very little time improving our code. Automated tests can really help with this problem! The obvious benefits are that they can be run much faster than manual tests, can test to a much lower level of detail, and test exactly the same functionality every time (human testers are nowhere near as reliable!) Because they are fast, automated tests can be executed more regularly, and if a test fails, they point to exactly where code is not performing as expected. In addition, automated tests can act as the first real-world "user" of your code, forcing you to be rigorous about defining and documenting how your website should behave. Often they are the basis for your code examples and documentation. For these reasons, some software development processes start with test definition and implementation, after which the code is written to match the required behavior (e.g. test-driven and behavior-driven development). This tutorial shows how to write automated tests for Django, by adding a number of tests to the *LocalLibrary* website. ### Types of testing There are numerous types, levels, and classifications of tests and testing approaches. The most important automated tests are: Unit tests Verify functional behavior of individual components, often to class and function level. Regression tests Tests that reproduce historic bugs. Each test is initially run to verify that the bug has been fixed, and then re-run to ensure that it has not been reintroduced following later changes to the code. Integration tests Verify how groupings of components work when used together. Integration tests are aware of the required interactions between components, but not necessarily of the internal operations of each component. They may cover simple groupings of components through to the whole website. **Note:** Other common types of tests include black box, white box, manual, automated, canary, smoke, conformance, acceptance, functional, system, performance, load, and stress tests. Look them up for more information. ### What does Django provide for testing? Testing a website is a complex task, because it is made of several layers of logic – from HTTP-level request handling, to model queries, to form validation and processing, and template rendering. Django provides a test framework with a small hierarchy of classes that build on the Python standard `unittest` library. Despite the name, this test framework is suitable for both unit and integration tests. The Django framework adds API methods and tools to help test web and Django-specific behavior. These allow you to simulate requests, insert test data, and inspect your application's output. Django also provides an API (LiveServerTestCase) and tools for using different testing frameworks, for example you can integrate with the popular Selenium framework to simulate a user interacting with a live browser. To write a test you derive from any of the Django (or *unittest*) test base classes (SimpleTestCase, TransactionTestCase, TestCase, LiveServerTestCase) and then write separate methods to check that specific functionality works as expected (tests use "assert" methods to test that expressions result in `True` or `False` values, or that two values are equal, etc.) When you start a test run, the framework executes the chosen test methods in your derived classes. The test methods are run independently, with common setup and/or tear-down behavior defined in the class, as shown below. ```python class YourTestClass(TestCase): def setUp(self): # Setup run before every test method. pass def tearDown(self): # Clean up run after every test method. pass def test\_something\_that\_will\_pass(self): self.assertFalse(False) def test\_something\_that\_will\_fail(self): self.assertTrue(False) ``` The best base class for most tests is django.test.TestCase. This test class creates a clean database before its tests are run, and runs every test function in its own transaction. The class also owns a test Client that you can use to simulate a user interacting with the code at the view level. In the following sections we're going to concentrate on unit tests, created using this TestCase base class. **Note:** The django.test.TestCase class is very convenient, but may result in some tests being slower than they need to be (not every test will need to set up its own database or simulate the view interaction). Once you're familiar with what you can do with this class, you may want to replace some of your tests with the available simpler test classes. ### What should you test? You should test all aspects of your own code, but not any libraries or functionality provided as part of Python or Django. So for example, consider the `Author` model defined below. You don't need to explicitly test that `first_name` and `last_name` have been stored properly as `CharField` in the database because that is something defined by Django (though of course in practice you will inevitably test this functionality during development). Nor do you need to test that the `date_of_birth` has been validated to be a date field, because that is again something implemented in Django. However you should check the text used for the labels (*First name, Last name, Date of birth, Died*), and the size of the field allocated for the text (*100 chars*), because these are part of your design and something that could be broken/changed in future. ```python class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('Died', null=True, blank=True) def get\_absolute\_url(self): return reverse('author-detail', args=[str(self.id)]) def \_\_str\_\_(self): return '%s, %s' % (self.last_name, self.first_name) ``` Similarly, you should check that the custom methods `get_absolute_url()` and `__str__()` behave as required because they are your code/business logic. In the case of `get_absolute_url()` you can trust that the Django `reverse()` method has been implemented properly, so what you're testing is that the associated view has actually been defined. **Note:** Astute readers may note that we would also want to constrain the date of birth and death to sensible values, and check that death comes after birth. In Django this constraint would be added to your form classes (although you can define validators for model fields and model validators these are only used at the form level if they are called by the model's `clean()` method. This requires a `ModelForm`, or the model's `clean()` method needs to be specifically called.) With that in mind let's start looking at how to define and run tests. Test structure overview ----------------------- Before we go into the detail of "what to test", let's first briefly look at *where* and *how* tests are defined. Django uses the unittest module's built-in test discovery, which will discover tests under the current working directory in any file named with the pattern **test\*.py**. Provided you name the files appropriately, you can use any structure you like. We recommend that you create a module for your test code, and have separate files for models, views, forms, and any other types of code you need to test. For example: ``` catalog/ /tests/ __init__.py test_models.py test_forms.py test_views.py ``` Create a file structure as shown above in your *LocalLibrary* project. The **\_\_init\_\_.py** should be an empty file (this tells Python that the directory is a package). You can create the three test files by copying and renaming the skeleton test file **/catalog/tests.py**. **Note:** The skeleton test file **/catalog/tests.py** was created automatically when we built the Django skeleton website. It is perfectly "legal" to put all your tests inside it, but if you test properly, you'll quickly end up with a very large and unmanageable test file. Delete the skeleton file as we won't need it. Open **/catalog/tests/test\_models.py**. The file should import `django.test.TestCase`, as shown: ```python from django.test import TestCase # Create your tests here. ``` Often you will add a test class for each model/view/form you want to test, with individual methods for testing specific functionality. In other cases you may wish to have a separate class for testing a specific use case, with individual test functions that test aspects of that use-case (for example, a class to test that a model field is properly validated, with functions to test each of the possible failure cases). Again, the structure is very much up to you, but it is best if you are consistent. Add the test class below to the bottom of the file. The class demonstrates how to construct a test case class by deriving from `TestCase`. ```python class YourTestClass(TestCase): @classmethod def setUpTestData(cls): print("setUpTestData: Run once to set up non-modified data for all class methods.") pass def setUp(self): print("setUp: Run once for every test method to set up clean data.") pass def test\_false\_is\_false(self): print("Method: test\_false\_is\_false.") self.assertFalse(False) def test\_false\_is\_true(self): print("Method: test\_false\_is\_true.") self.assertTrue(False) def test\_one\_plus\_one\_equals\_two(self): print("Method: test\_one\_plus\_one\_equals\_two.") self.assertEqual(1 + 1, 2) ``` The new class defines two methods that you can use for pre-test configuration (for example, to create any models or other objects you will need for the test): * `setUpTestData()` is called once at the beginning of the test run for class-level setup. You'd use this to create objects that aren't going to be modified or changed in any of the test methods. * `setUp()` is called before every test function to set up any objects that may be modified by the test (every test function will get a "fresh" version of these objects). **Note:** The test classes also have a `tearDown()` method which we haven't used. This method isn't particularly useful for database tests, since the `TestCase` base class takes care of database teardown for you. Below those we have a number of test methods, which use `Assert` functions to test whether conditions are true, false or equal (`AssertTrue`, `AssertFalse`, `AssertEqual`). If the condition does not evaluate as expected then the test will fail and report the error to your console. The `AssertTrue`, `AssertFalse`, `AssertEqual` are standard assertions provided by **unittest**. There are other standard assertions in the framework, and also Django-specific assertions to test if a view redirects (`assertRedirects`), to test if a particular template has been used (`assertTemplateUsed`), etc. **Note:** You should **not** normally include **print()** functions in your tests as shown above. We do that here only so that you can see the order that the setup functions are called in the console (in the following section). How to run the tests -------------------- The easiest way to run all the tests is to use the command: ```bash python3 manage.py test ``` This will discover all files named with the pattern **test\*.py** under the current directory and run all tests defined using appropriate base classes (here we have a number of test files, but only **/catalog/tests/test\_models.py** currently contains any tests.) By default the tests will individually report only on test failures, followed by a test summary. **Note:** If you get errors similar to: `ValueError: Missing staticfiles manifest entry...` this may be because testing does not run *collectstatic* by default, and your app is using a storage class that requires it (see manifest\_strict for more information). There are a number of ways you can overcome this problem - the easiest is to run *collectstatic* before running the tests: ```bash python3 manage.py collectstatic ``` Run the tests in the root directory of *LocalLibrary*. You should see an output like the one below. ```bash > python3 manage.py test Creating test database for alias 'default'... setUpTestData: Run once to set up non-modified data for all class methods. setUp: Run once for every test method to set up clean data. Method: test_false_is_false. setUp: Run once for every test method to set up clean data. Method: test_false_is_true. setUp: Run once for every test method to set up clean data. Method: test_one_plus_one_equals_two. . ====================================================================== FAIL: test_false_is_true (catalog.tests.tests_models.YourTestClass) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\GitHub\django\_tmp\library\_w\_t\_2\locallibrary\catalog\tests\tests\_models.py", line 22, in test_false_is_true self.assertTrue(False) AssertionError: False is not true ---------------------------------------------------------------------- Ran 3 tests in 0.075s FAILED (failures=1) Destroying test database for alias 'default'... ``` Here we see that we had one test failure, and we can see exactly what function failed and why (this failure is expected, because `False` is not `True`!). **Note:** The most important thing to learn from the test output above is that it is much more valuable if you use descriptive/informative names for your objects and methods. The output of the `print()` functions shows how the `setUpTestData()` method is called once for the class and `setUp()` is called before each method. Again, remember that normally you would not add this kind of `print()` to your tests. The next sections show how you can run specific tests, and how to control how much information the tests display. ### Showing more test information If you want to get more information about the test run you can change the *verbosity*. For example, to list the test successes as well as failures (and a whole bunch of information about how the testing database is set up) you can set the verbosity to "2" as shown: ```bash python3 manage.py test --verbosity 2 ``` The allowed verbosity levels are 0, 1, 2, and 3, with the default being "1". ### Speeding things up If your tests are independent, on a multiprocessor machine you can significantly speed them up by running them in parallel. The use of `--parallel auto` below runs one test process per available core. The `auto` is optional, and you can also specify a particular number of cores to use. ```bash python3 manage.py test --parallel auto ``` For more information, including what to do if your tests are not independent, see DJANGO\_TEST\_PROCESSES. ### Running specific tests If you want to run a subset of your tests you can do so by specifying the full dot path to the package(s), module, `TestCase` subclass or method: ```bash # Run the specified module python3 manage.py test catalog.tests # Run the specified module python3 manage.py test catalog.tests.test_models # Run the specified class python3 manage.py test catalog.tests.test_models.YourTestClass # Run the specified method python3 manage.py test catalog.tests.test_models.YourTestClass.test_one_plus_one_equals_two ``` ### Other test runner options The test runner provides many other options, including the ability to shuffle tests (`--shuffle`), run them in debug mode (`--debug-mode`), and use the Python logger to capture the results. For more information see the Django test runner documentation. LocalLibrary tests ------------------ Now we know how to run our tests and what sort of things we need to test, let's look at some practical examples. **Note:** We won't write every possible test, but this should give you an idea of how tests work, and what more you can do. ### Models As discussed above, we should test anything that is part of our design or that is defined by code that we have written, but not libraries/code that is already tested by Django or the Python development team. For example, consider the `Author` model below. Here we should test the labels for all the fields, because even though we haven't explicitly specified most of them, we have a design that says what these values should be. If we don't test the values, then we don't know that the field labels have their intended values. Similarly while we trust that Django will create a field of the specified length, it is worthwhile to specify a test for this length to ensure that it was implemented as planned. ```python class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('Died', null=True, blank=True) def get\_absolute\_url(self): return reverse('author-detail', args=[str(self.id)]) def \_\_str\_\_(self): return f'{self.last\_name}, {self.first\_name}' ``` Open our **/catalog/tests/test\_models.py**, and replace any existing code with the following test code for the `Author` model. Here you'll see that we first import `TestCase` and derive our test class (`AuthorModelTest`) from it, using a descriptive name so we can easily identify any failing tests in the test output. We then call `setUpTestData()` to create an author object that we will use but not modify in any of the tests. ```python from django.test import TestCase from catalog.models import Author class AuthorModelTest(TestCase): @classmethod def setUpTestData(cls): # Set up non-modified objects used by all test methods Author.objects.create(first_name='Big', last_name='Bob') def test\_first\_name\_label(self): author = Author.objects.get(id=1) field_label = author._meta.get_field('first\_name').verbose_name self.assertEqual(field_label, 'first name') def test\_date\_of\_death\_label(self): author = Author.objects.get(id=1) field_label = author._meta.get_field('date\_of\_death').verbose_name self.assertEqual(field_label, 'died') def test\_first\_name\_max\_length(self): author = Author.objects.get(id=1) max_length = author._meta.get_field('first\_name').max_length self.assertEqual(max_length, 100) def test\_object\_name\_is\_last\_name\_comma\_first\_name(self): author = Author.objects.get(id=1) expected_object_name = f'{author.last\_name}, {author.first\_name}' self.assertEqual(str(author), expected_object_name) def test\_get\_absolute\_url(self): author = Author.objects.get(id=1) # This will also fail if the urlconf is not defined. self.assertEqual(author.get_absolute_url(), '/catalog/author/1') ``` The field tests check that the values of the field labels (`verbose_name`) and that the size of the character fields are as expected. These methods all have descriptive names, and follow the same pattern: ```python # Get an author object to test author = Author.objects.get(id=1) # Get the metadata for the required field and use it to query the required field data field_label = author._meta.get_field('first\_name').verbose_name # Compare the value to the expected result self.assertEqual(field_label, 'first name') ``` The interesting things to note are: * We can't get the `verbose_name` directly using `author.first_name.verbose_name`, because `author.first_name` is a *string* (not a handle to the `first_name` object that we can use to access its properties). Instead we need to use the author's `_meta` attribute to get an instance of the field and use that to query for the additional information. * We chose to use `assertEqual(field_label,'first name')` rather than `assertTrue(field_label == 'first name')`. The reason for this is that if the test fails the output for the former tells you what the label actually was, which makes debugging the problem just a little easier. **Note:** Tests for the `last_name` and `date_of_birth` labels, and also the test for the length of the `last_name` field have been omitted. Add your own versions now, following the naming conventions and approaches shown above. We also need to test our custom methods. These essentially just check that the object name was constructed as we expected using "Last Name", "First Name" format, and that the URL we get for an `Author` item is as we would expect. ```python def test\_object\_name\_is\_last\_name\_comma\_first\_name(self): author = Author.objects.get(id=1) expected_object_name = f'{author.last\_name}, {author.first\_name}' self.assertEqual(str(author), expected_object_name) def test\_get\_absolute\_url(self): author = Author.objects.get(id=1) # This will also fail if the urlconf is not defined. self.assertEqual(author.get_absolute_url(), '/catalog/author/1') ``` Run the tests now. If you created the Author model as we described in the models tutorial it is quite likely that you will get an error for the `date_of_death` label as shown below. The test is failing because it was written expecting the label definition to follow Django's convention of not capitalizing the first letter of the label (Django does this for you). ```bash ====================================================================== FAIL: test_date_of_death_label (catalog.tests.test_models.AuthorModelTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\...\locallibrary\catalog\tests\test\_models.py", line 32, in test_date_of_death_label self.assertEqual(field_label,'died') AssertionError: 'Died' != 'died' - Died ? ^ + died ? ^ ``` This is a very minor bug, but it does highlight how writing tests can more thoroughly check any assumptions you may have made. **Note:** Change the label for the `date_of_death` field (**/catalog/models.py**) to "died" and re-run the tests. The patterns for testing the other models are similar so we won't continue to discuss these further. Feel free to create your own tests for our other models. ### Forms The philosophy for testing your forms is the same as for testing your models; you need to test anything that you've coded or your design specifies, but not the behavior of the underlying framework and other third party libraries. Generally this means that you should test that the forms have the fields that you want, and that these are displayed with appropriate labels and help text. You don't need to verify that Django validates the field type correctly (unless you created your own custom field and validation) — i.e. you don't need to test that an email field only accepts emails. However you would need to test any additional validation that you expect to be performed on the fields and any messages that your code will generate for errors. Consider our form for renewing books. This has just one field for the renewal date, which will have a label and help text that we will need to verify. ```python class RenewBookForm(forms.Form): """Form for a librarian to renew books.""" renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).") def clean\_renewal\_date(self): data = self.cleaned_data['renewal\_date'] # Check if a date is not in the past. if data < datetime.date.today(): raise ValidationError(_('Invalid date - renewal in past')) # Check if date is in the allowed range (+4 weeks from today). if data > datetime.date.today() + datetime.timedelta(weeks=4): raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead')) # Remember to always return the cleaned data. return data ``` Open our **/catalog/tests/test\_forms.py** file and replace any existing code with the following test code for the `RenewBookForm` form. We start by importing our form and some Python and Django libraries to help test time-related functionality. We then declare our form test class in the same way as we did for models, using a descriptive name for our `TestCase`-derived test class. ```python import datetime from django.test import TestCase from django.utils import timezone from catalog.forms import RenewBookForm class RenewBookFormTest(TestCase): def test\_renew\_form\_date\_field\_label(self): form = RenewBookForm() self.assertTrue(form.fields['renewal\_date'].label is None or form.fields['renewal\_date'].label == 'renewal date') def test\_renew\_form\_date\_field\_help\_text(self): form = RenewBookForm() self.assertEqual(form.fields['renewal\_date'].help_text, 'Enter a date between now and 4 weeks (default 3).') def test\_renew\_form\_date\_in\_past(self): date = datetime.date.today() - datetime.timedelta(days=1) form = RenewBookForm(data={'renewal\_date': date}) self.assertFalse(form.is_valid()) def test\_renew\_form\_date\_too\_far\_in\_future(self): date = datetime.date.today() + datetime.timedelta(weeks=4) + datetime.timedelta(days=1) form = RenewBookForm(data={'renewal\_date': date}) self.assertFalse(form.is_valid()) def test\_renew\_form\_date\_today(self): date = datetime.date.today() form = RenewBookForm(data={'renewal\_date': date}) self.assertTrue(form.is_valid()) def test\_renew\_form\_date\_max(self): date = timezone.localtime() + datetime.timedelta(weeks=4) form = RenewBookForm(data={'renewal\_date': date}) self.assertTrue(form.is_valid()) ``` The first two functions test that the field's `label` and `help_text` are as expected. We have to access the field using the fields dictionary (e.g. `form.fields['renewal_date']`). Note here that we also have to test whether the label value is `None`, because even though Django will render the correct label it returns `None` if the value is not *explicitly* set. The rest of the functions test that the form is valid for renewal dates just inside the acceptable range and invalid for values outside the range. Note how we construct test date values around our current date (`datetime.date.today()`) using `datetime.timedelta()` (in this case specifying a number of days or weeks). We then just create the form, passing in our data, and test if it is valid. **Note:** Here we don't actually use the database or test client. Consider modifying these tests to use SimpleTestCase. We also need to validate that the correct errors are raised if the form is invalid, however this is usually done as part of view processing, so we'll take care of that in the next section. **Warning:** If you use the ModelForm class `RenewBookModelForm(forms.ModelForm)` instead of class `RenewBookForm(forms.Form)`, then the form field name would be **'due\_back'** instead of **'renewal\_date'**. That's all for forms; we do have some others, but they are automatically created by our generic class-based editing views, and should be tested there! Run the tests and confirm that our code still passes! ### Views To validate our view behavior we use the Django test Client. This class acts like a dummy web browser that we can use to simulate `GET` and `POST` requests on a URL and observe the response. We can see almost everything about the response, from low-level HTTP (result headers and status codes) through to the template we're using to render the HTML and the context data we're passing to it. We can also see the chain of redirects (if any) and check the URL and status code at each step. This allows us to verify that each view is doing what is expected. Let's start with one of our simplest views, which provides a list of all Authors. This is displayed at URL **/catalog/authors/** (a URL named 'authors' in the URL configuration). ```python class AuthorListView(generic.ListView): model = Author paginate_by = 10 ``` As this is a generic list view almost everything is done for us by Django. Arguably if you trust Django then the only thing you need to test is that the view is accessible at the correct URL and can be accessed using its name. However if you're using a test-driven development process you'll start by writing tests that confirm that the view displays all Authors, paginating them in lots of 10. Open the **/catalog/tests/test\_views.py** file and replace any existing text with the following test code for `AuthorListView`. As before we import our model and some useful classes. In the `setUpTestData()` method we set up a number of `Author` objects so that we can test our pagination. ```python from django.test import TestCase from django.urls import reverse from catalog.models import Author class AuthorListViewTest(TestCase): @classmethod def setUpTestData(cls): # Create 13 authors for pagination tests number_of_authors = 13 for author_id in range(number_of_authors): Author.objects.create( first_name=f'Dominique {author\_id}', last_name=f'Surname {author\_id}', ) def test\_view\_url\_exists\_at\_desired\_location(self): response = self.client.get('/catalog/authors/') self.assertEqual(response.status_code, 200) def test\_view\_url\_accessible\_by\_name(self): response = self.client.get(reverse('authors')) self.assertEqual(response.status_code, 200) def test\_view\_uses\_correct\_template(self): response = self.client.get(reverse('authors')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'catalog/author\_list.html') def test\_pagination\_is\_ten(self): response = self.client.get(reverse('authors')) self.assertEqual(response.status_code, 200) self.assertTrue('is\_paginated' in response.context) self.assertTrue(response.context['is\_paginated'] == True) self.assertEqual(len(response.context['author\_list']), 10) def test\_lists\_all\_authors(self): # Get second page and confirm it has (exactly) remaining 3 items response = self.client.get(reverse('authors')+'?page=2') self.assertEqual(response.status_code, 200) self.assertTrue('is\_paginated' in response.context) self.assertTrue(response.context['is\_paginated'] == True) self.assertEqual(len(response.context['author\_list']), 3) ``` All the tests use the client (belonging to our `TestCase`'s derived class) to simulate a `GET` request and get a response. The first version checks a specific URL (note, just the specific path without the domain) while the second generates the URL from its name in the URL configuration. ```python response = self.client.get('/catalog/authors/') response = self.client.get(reverse('authors')) ``` Once we have the response we query it for its status code, the template used, whether or not the response is paginated, the number of items returned, and the total number of items. **Note:** If you set the `paginate_by` variable in your **/catalog/views.py** file to a number other than 10, make sure to update the lines that test that the correct number of items are displayed in paginated templates above and in following sections. For example, if you set the variable for the author list page to 5, update the line above to: ```python self.assertTrue(len(response.context['author\_list']) == 5) ``` The most interesting variable we demonstrate above is `response.context`, which is the context variable passed to the template by the view. This is incredibly useful for testing, because it allows us to confirm that our template is getting all the data it needs. In other words we can check that we're using the intended template and what data the template is getting, which goes a long way to verifying that any rendering issues are solely due to template. #### Views that are restricted to logged in users In some cases you'll want to test a view that is restricted to just logged in users. For example our `LoanedBooksByUserListView` is very similar to our previous view but is only available to logged in users, and only displays `BookInstance` records that are borrowed by the current user, have the 'on loan' status, and are ordered "oldest first". ```python from django.contrib.auth.mixins import LoginRequiredMixin class LoanedBooksByUserListView(LoginRequiredMixin, generic.ListView): """Generic class-based view listing books on loan to current user.""" model = BookInstance template_name ='catalog/bookinstance\_list\_borrowed\_user.html' paginate_by = 10 def get\_queryset(self): return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due\_back') ``` Add the following test code to **/catalog/tests/test\_views.py**. Here we first use `SetUp()` to create some user login accounts and `BookInstance` objects (along with their associated books and other records) that we'll use later in the tests. Half of the books are borrowed by each test user, but we've initially set the status of all books to "maintenance". We've used `SetUp()` rather than `setUpTestData()` because we'll be modifying some of these objects later. **Note:** The `setUp()` code below creates a book with a specified `Language`, but *your* code may not include the `Language` model as this was created as a *challenge*. If this is the case, comment out the parts of the code that create or import Language objects. You should also do this in the `RenewBookInstancesViewTest` section that follows. ```python import datetime from django.utils import timezone # Get user model from settings from django.contrib.auth import get_user_model User = get_user_model() from catalog.models import BookInstance, Book, Genre, Language class LoanedBookInstancesByUserListViewTest(TestCase): def setUp(self): # Create two users test_user1 = User.objects.create_user(username='testuser1', password='1X<ISRUkw+tuK') test_user2 = User.objects.create_user(username='testuser2', password='2HJ1vRV0Z&3iD') test_user1.save() test_user2.save() # Create a book test_author = Author.objects.create(first_name='John', last_name='Smith') test_genre = Genre.objects.create(name='Fantasy') test_language = Language.objects.create(name='English') test_book = Book.objects.create( title='Book Title', summary='My book summary', isbn='ABCDEFG', author=test_author, language=test_language, ) # Create genre as a post-step genre_objects_for_book = Genre.objects.all() test_book.genre.set(genre_objects_for_book) # Direct assignment of many-to-many types not allowed. test_book.save() # Create 30 BookInstance objects number_of_book_copies = 30 for book_copy in range(number_of_book_copies): return_date = timezone.localtime() + datetime.timedelta(days=book_copy%5) the_borrower = test_user1 if book_copy % 2 else test_user2 status = 'm' BookInstance.objects.create( book=test_book, imprint='Unlikely Imprint, 2016', due_back=return_date, borrower=the_borrower, status=status, ) def test\_redirect\_if\_not\_logged\_in(self): response = self.client.get(reverse('my-borrowed')) self.assertRedirects(response, '/accounts/login/?next=/catalog/mybooks/') def test\_logged\_in\_uses\_correct\_template(self): login = self.client.login(username='testuser1', password='1X<ISRUkw+tuK') response = self.client.get(reverse('my-borrowed')) # Check our user is logged in self.assertEqual(str(response.context['user']), 'testuser1') # Check that we got a response "success" self.assertEqual(response.status_code, 200) # Check we used correct template self.assertTemplateUsed(response, 'catalog/bookinstance\_list\_borrowed\_user.html') ``` To verify that the view will redirect to a login page if the user is not logged in we use `assertRedirects`, as demonstrated in `test_redirect_if_not_logged_in()`. To verify that the page is displayed for a logged in user we first log in our test user, and then access the page again and check that we get a `status_code` of 200 (success). The rest of the tests verify that our view only returns books that are on loan to our current borrower. Copy the code below and paste it onto the end of the test class above. ```python def test\_only\_borrowed\_books\_in\_list(self): login = self.client.login(username='testuser1', password='1X<ISRUkw+tuK') response = self.client.get(reverse('my-borrowed')) # Check our user is logged in self.assertEqual(str(response.context['user']), 'testuser1') # Check that we got a response "success" self.assertEqual(response.status_code, 200) # Check that initially we don't have any books in list (none on loan) self.assertTrue('bookinstance\_list' in response.context) self.assertEqual(len(response.context['bookinstance\_list']), 0) # Now change all books to be on loan books = BookInstance.objects.all()[:10] for book in books: book.status = 'o' book.save() # Check that now we have borrowed books in the list response = self.client.get(reverse('my-borrowed')) # Check our user is logged in self.assertEqual(str(response.context['user']), 'testuser1') # Check that we got a response "success" self.assertEqual(response.status_code, 200) self.assertTrue('bookinstance\_list' in response.context) # Confirm all books belong to testuser1 and are on loan for bookitem in response.context['bookinstance\_list']: self.assertEqual(response.context['user'], bookitem.borrower) self.assertEqual(bookitem.status, 'o') def test\_pages\_ordered\_by\_due\_date(self): # Change all books to be on loan for book in BookInstance.objects.all(): book.status='o' book.save() login = self.client.login(username='testuser1', password='1X<ISRUkw+tuK') response = self.client.get(reverse('my-borrowed')) # Check our user is logged in self.assertEqual(str(response.context['user']), 'testuser1') # Check that we got a response "success" self.assertEqual(response.status_code, 200) # Confirm that of the items, only 10 are displayed due to pagination. self.assertEqual(len(response.context['bookinstance\_list']), 10) last_date = 0 for book in response.context['bookinstance\_list']: if last_date == 0: last_date = book.due_back else: self.assertTrue(last_date <= book.due_back) last_date = book.due_back ``` You could also add pagination tests, should you so wish! #### Testing views with forms Testing views with forms is a little more complicated than in the cases above, because you need to test more code paths: initial display, display after data validation has failed, and display after validation has succeeded. The good news is that we use the client for testing in almost exactly the same way as we did for display-only views. To demonstrate, let's write some tests for the view used to renew books (`renew_book_librarian()`): ```python from catalog.forms import RenewBookForm @permission\_required('catalog.can\_mark\_returned') def renew\_book\_librarian(request, pk): """View function for renewing a specific BookInstance by librarian.""" book_instance = get_object_or_404(BookInstance, pk=pk) # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): book_renewal_form = RenewBookForm(request.POST) # Check if the form is valid: if form.is_valid(): # process the data in form.cleaned\_data as required (here we just write it to the model due\_back field) book_instance.due_back = form.cleaned_data['renewal\_date'] book_instance.save() # redirect to a new URL: return HttpResponseRedirect(reverse('all-borrowed')) # If this is a GET (or any other method) create the default form else: proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3) book_renewal_form = RenewBookForm(initial={'renewal\_date': proposed_renewal_date}) context = { 'book\_renewal\_form': book_renewal_form, 'book\_instance': book_instance, } return render(request, 'catalog/book\_renew\_librarian.html', context) ``` We'll need to test that the view is only available to users who have the `can_mark_returned` permission, and that users are redirected to an HTTP 404 error page if they attempt to renew a `BookInstance` that does not exist. We should check that the initial value of the form is seeded with a date three weeks in the future, and that if validation succeeds we're redirected to the "all-borrowed books" view. As part of checking the validation-fail tests we'll also check that our form is sending the appropriate error messages. Add the first part of the test class (shown below) to the bottom of **/catalog/tests/test\_views.py**. This creates two users and two book instances, but only gives one user the permission required to access the view. ```python import uuid from django.contrib.auth.models import Permission # Required to grant the permission needed to set a book as returned. class RenewBookInstancesViewTest(TestCase): def setUp(self): # Create a user test_user1 = User.objects.create_user(username='testuser1', password='1X<ISRUkw+tuK') test_user2 = User.objects.create_user(username='testuser2', password='2HJ1vRV0Z&3iD') test_user1.save() test_user2.save() # Give test\_user2 permission to renew books. permission = Permission.objects.get(name='Set book as returned') test_user2.user_permissions.add(permission) test_user2.save() # Create a book test_author = Author.objects.create(first_name='John', last_name='Smith') test_genre = Genre.objects.create(name='Fantasy') test_language = Language.objects.create(name='English') test_book = Book.objects.create( title='Book Title', summary='My book summary', isbn='ABCDEFG', author=test_author, language=test_language, ) # Create genre as a post-step genre_objects_for_book = Genre.objects.all() test_book.genre.set(genre_objects_for_book) # Direct assignment of many-to-many types not allowed. test_book.save() # Create a BookInstance object for test\_user1 return_date = datetime.date.today() + datetime.timedelta(days=5) self.test_bookinstance1 = BookInstance.objects.create( book=test_book, imprint='Unlikely Imprint, 2016', due_back=return_date, borrower=test_user1, status='o', ) # Create a BookInstance object for test\_user2 return_date = datetime.date.today() + datetime.timedelta(days=5) self.test_bookinstance2 = BookInstance.objects.create( book=test_book, imprint='Unlikely Imprint, 2016', due_back=return_date, borrower=test_user2, status='o', ) ``` Add the following tests to the bottom of the test class. These check that only users with the correct permissions (*testuser2*) can access the view. We check all the cases: when the user is not logged in, when a user is logged in but does not have the correct permissions, when the user has permissions but is not the borrower (should succeed), and what happens when they try to access a `BookInstance` that doesn't exist. We also check that the correct template is used. ```python def test\_redirect\_if\_not\_logged\_in(self): response = self.client.get(reverse('renew-book-librarian', kwargs={'pk': self.test_bookinstance1.pk})) # Manually check redirect (Can't use assertRedirect, because the redirect URL is unpredictable) self.assertEqual(response.status_code, 302) self.assertTrue(response.url.startswith('/accounts/login/')) def test\_forbidden\_if\_logged\_in\_but\_not\_correct\_permission(self): login = self.client.login(username='testuser1', password='1X<ISRUkw+tuK') response = self.client.get(reverse('renew-book-librarian', kwargs={'pk': self.test_bookinstance1.pk})) self.assertEqual(response.status_code, 403) def test\_logged\_in\_with\_permission\_borrowed\_book(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') response = self.client.get(reverse('renew-book-librarian', kwargs={'pk': self.test_bookinstance2.pk})) # Check that it lets us login - this is our book and we have the right permissions. self.assertEqual(response.status_code, 200) def test\_logged\_in\_with\_permission\_another\_users\_borrowed\_book(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') response = self.client.get(reverse('renew-book-librarian', kwargs={'pk': self.test_bookinstance1.pk})) # Check that it lets us login. We're a librarian, so we can view any users book self.assertEqual(response.status_code, 200) def test\_HTTP404\_for\_invalid\_book\_if\_logged\_in(self): # unlikely UID to match our bookinstance! test_uid = uuid.uuid4() login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') response = self.client.get(reverse('renew-book-librarian', kwargs={'pk':test_uid})) self.assertEqual(response.status_code, 404) def test\_uses\_correct\_template(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') response = self.client.get(reverse('renew-book-librarian', kwargs={'pk': self.test_bookinstance1.pk})) self.assertEqual(response.status_code, 200) # Check we used correct template self.assertTemplateUsed(response, 'catalog/book\_renew\_librarian.html') ``` Add the next test method, as shown below. This checks that the initial date for the form is three weeks in the future. Note how we are able to access the value of the initial value of the form field (`response.context['form'].initial['renewal_date'])`. ```python def test\_form\_renewal\_date\_initially\_has\_date\_three\_weeks\_in\_future(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') response = self.client.get(reverse('renew-book-librarian', kwargs={'pk': self.test_bookinstance1.pk})) self.assertEqual(response.status_code, 200) date_3_weeks_in_future = datetime.date.today() + datetime.timedelta(weeks=3) self.assertEqual(response.context['form'].initial['renewal\_date'], date_3_weeks_in_future) ``` The next test (add this to the class too) checks that the view redirects to a list of all borrowed books if renewal succeeds. What differs here is that for the first time we show how you can `POST` data using the client. The post *data* is the second argument to the post function, and is specified as a dictionary of key/values. ```python def test\_redirects\_to\_all\_borrowed\_book\_list\_on\_success(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') valid_date_in_future = datetime.date.today() + datetime.timedelta(weeks=2) response = self.client.post(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}), {'renewal\_date':valid_date_in_future}) self.assertRedirects(response, reverse('all-borrowed')) ``` **Warning:** The *all-borrowed* view was added as a *challenge*, and your code may instead redirect to the home page '/'. If so, modify the last two lines of the test code to be like the code below. The `follow=True` in the request ensures that the request returns the final destination URL (hence checking `/catalog/` rather than `/`). ```python response = self.client.post(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}), {'renewal\_date':valid_date_in_future}, follow=True) self.assertRedirects(response, '/catalog/') ``` Copy the last two functions into the class, as seen below. These again test `POST` requests, but in this case with invalid renewal dates. We use `assertFormError()` to verify that the error messages are as expected. ```python def test\_form\_invalid\_renewal\_date\_past(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') date_in_past = datetime.date.today() - datetime.timedelta(weeks=1) response = self.client.post(reverse('renew-book-librarian', kwargs={'pk': self.test_bookinstance1.pk}), {'renewal\_date': date_in_past}) self.assertEqual(response.status_code, 200) self.assertFormError(response.context['form'], 'renewal\_date', 'Invalid date - renewal in past') def test\_form\_invalid\_renewal\_date\_future(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') invalid_date_in_future = datetime.date.today() + datetime.timedelta(weeks=5) response = self.client.post(reverse('renew-book-librarian', kwargs={'pk': self.test_bookinstance1.pk}), {'renewal\_date': invalid_date_in_future}) self.assertEqual(response.status_code, 200) self.assertFormError(response.context['form'], 'renewal\_date', 'Invalid date - renewal more than 4 weeks ahead') ``` The same sorts of techniques can be used to test the other view. ### Templates Django provides test APIs to check that the correct template is being called by your views, and to allow you to verify that the correct information is being sent. There is however no specific API support for testing in Django that your HTML output is rendered as expected. Other recommended test tools ---------------------------- Django's test framework can help you write effective unit and integration tests — we've only scratched the surface of what the underlying **unittest** framework can do, let alone Django's additions (for example, check out how you can use unittest.mock to patch third party libraries so you can more thoroughly test your own code). While there are numerous other test tools that you can use, we'll just highlight two: * Coverage: This Python tool reports on how much of your code is actually executed by your tests. It is particularly useful when you're getting started, and you are trying to work out exactly what you should test. * Selenium is a framework to automate testing in a real browser. It allows you to simulate a real user interacting with the site, and provides a great framework for system testing your site (the next step up from integration testing). Challenge yourself ------------------ There are a lot more models and views we can test. As a challenge, try to create a test case for the `AuthorCreate` view. ```python class AuthorCreate(PermissionRequiredMixin, CreateView): model = Author fields = ['first\_name', 'last\_name', 'date\_of\_birth', 'date\_of\_death'] initial = {'date\_of\_death': '11/11/2023'} permission_required = 'catalog.add\_author' ``` Remember that you need to check anything that you specify or that is part of the design. This will include who has access, the initial date, the template used, and where the view redirects on success. You might use the following code to set up your test and assign your user the appropriate permission ```python class AuthorCreateViewTest(TestCase): """Test case for the AuthorCreate view (Created as Challenge).""" def setUp(self): # Create a user test_user = User.objects.create_user( username='test\_user', password='some\_password') content_typeAuthor = ContentType.objects.get_for_model(Author) permAddAuthor = Permission.objects.get( codename="add\_author", content_type=content_typeAuthor, ) test_user.user_permissions.add(permAddAuthor) test_user.save() ``` Summary ------- Writing test code is neither fun nor glamorous, and is consequently often left to last (or not at all) when creating a website. It is however an essential part of making sure that your code is safe to release after making changes, and cost-effective to maintain. In this tutorial we've shown you how to write and run tests for your models, forms, and views. Most importantly we've provided a brief summary of what you should test, which is often the hardest thing to work out when you're getting started. There is a lot more to know, but even with what you've learned already you should be able to create effective unit tests for your websites. The next and final tutorial shows how you can deploy your wonderful (and fully tested!) Django website. See also -------- * Writing and running tests (Django docs) * Writing your first Django app, part 5 > Introducing automated testing (Django docs) * Testing tools reference (Django docs) * Advanced testing topics (Django docs) * A Guide to Testing in Django (Toast Driven Blog, 2011) * Workshop: Test-Driven Web Development with Django (San Diego Python, 2014) * Testing in Django (Part 1) - Best Practices and Examples (RealPython, 2013) * Previous * Overview: Django * Next
Assessment: DIY Django mini blog - Learn web development
Assessment: DIY Django mini blog ================================ * Previous * Overview: Django In this assessment you'll use the Django knowledge you've picked up in the Django Web Framework (Python) module to create a very basic blog. | | | | --- | --- | | Prerequisites: | Before attempting this assessment you should have already worked through all the articles in this module. | | Objective: | To test comprehension of Django fundamentals, including URL configurations, models, views, forms, and templates. | Project brief ------------- The pages that need to be displayed, their URLs, and other requirements, are listed below: | Page | URL | Requirements | | --- | --- | --- | | Home page | `/` and `/blog/` | An index page describing the site. | | List of all blog posts | `/blog/blogs/` | List of all blog posts:* Accessible to all users from a sidebar link. * List sorted by post date (newest to oldest). * List paginated in groups of 5 articles. * List items display the blog title, post date, and author. * Blog post names are linked to blog detail pages. * Blogger (author names) are linked to blog author detail pages. | | Blog author (blogger) detail page | `/blog/blogger/*<author-id>*` | Information for a specified author (by id) and list of their blog posts:* Accessible to all users from author links in blog posts etc. * Contains some biographical information about the blogger/author. * List sorted by post date (newest to oldest). * Not paginated. * List items display just the blog post name and post date. * Blog post names are linked to blog detail pages. | | Blog post detail page | `/blog/*<blog-id>*` | Blog post details.* Accessible to all users from blog post lists. * Page contains the blog post: name, author, post date, and content. * Comments for the blog post should be displayed at bottom. * Comments should be sorted in order: oldest to most recent. * Contains link to add comments at end for logged in users (see Comment form page) * Blog posts and comments need only display plain text. There is no need to support any sort of HTML markup (e.g. links, images, bold/italic, etc.). | | List of all bloggers | `/blog/bloggers/` | List of bloggers on system:* Accessible to all users from site sidebar * Blogger names are linked to Blog author detail pages. | | Comment form page | `/blog/*<blog-id>*/create` | Create comment for blog post:* Accessible to logged-in users (only) from link at bottom of blog post detail pages. * Displays form with description for entering comments (post date and blog is not editable). * After a comment has been posted, the page will redirect back to the associated blog post page. * Users cannot edit or delete their posts. * Logged out users will be directed to the login page to log in, before they can add comments. After logging in, they will be redirected back to the blog page they wanted to comment on. * Comment pages should include the name/link to the blog post being commented on. | | User authentication pages | `/accounts/*<standard urls>*` | Standard Django authentication pages for logging in, out and setting the password:* Login/out should be accessible via sidebar links. | | Admin site | `/admin/*<standard urls>*` | Admin site should be enabled to allow create/edit/delete of blog posts, blog authors and blog comments (this is the mechanism for bloggers to create new blog posts): * Admin site blog posts records should display the list of associated comments inline (below each blog post). * Comment names in the Admin site are created by truncating the comment description to 75 characters. * Other types of records can use basic registration. | In addition you should write some basic tests to verify: * All model fields have the correct label and length. * All models have the expected object name (e.g. `__str__()` returns the expected value). * Models have the expected URL for individual Blog and Comment records (e.g. `get_absolute_url()` returns the expected URL). * The BlogListView (all-blog page) is accessible at the expected location (e.g. /blog/blogs) * The BlogListView (all-blog page) is accessible at the expected named URL (e.g. 'blogs') * The BlogListView (all-blog page) uses the expected template (e.g. the default) * The BlogListView paginates records by 5 (at least on the first page) **Note:** There are of course many other tests you can run. Use your discretion, but we'll expect you to do at least the tests above. The following section shows screenshots of a site that implements the requirements above. Screenshots ----------- The following screenshots provide an example of what the finished program should output. ### List of all blog posts This displays the list of all blog posts (accessible from the "All blogs" link in the sidebar). Things to note: * The sidebar also lists the logged in user. * Individual blog posts and bloggers are accessible as links in the page. * Pagination is enabled (in groups of 5) * Ordering is newest to oldest. ![List of all blogs](/en-US/docs/Learn/Server-side/Django/django_assessment_blog/diyblog_allblogs.png) ### List of all bloggers This provides links to all bloggers, as linked from the "All bloggers" link in the sidebar. In this case we can see from the sidebar that no user is logged in. ![List of all bloggers](/en-US/docs/Learn/Server-side/Django/django_assessment_blog/diyblog_blog_allbloggers.png) ### Blog detail page This shows the detail page for a particular blog. ![Blog detail with add comment link](/en-US/docs/Learn/Server-side/Django/django_assessment_blog/diyblog_blog_detail_add_comment.png) Note that the comments have a date *and* time, and are ordered from oldest to newest (opposite of blog ordering). At the end we have a link for accessing the form to add a new comment. If a user is not logged in we'd instead see a suggestion to log in. ![Comment link when not logged in](/en-US/docs/Learn/Server-side/Django/django_assessment_blog/diyblog_blog_detail_not_logged_in.png) ### Add comment form This is the form to add comments. Note that we're logged in. When this succeeds we should be taken back to the associated blog post page. ![Add comment form](/en-US/docs/Learn/Server-side/Django/django_assessment_blog/diyblog_comment_form.png) ### Author bio This displays bio information for a blogger along with their blog posts list. ![Blogger detail page](/en-US/docs/Learn/Server-side/Django/django_assessment_blog/diyblog_blogger_detail.png) Steps to complete ----------------- The following sections describe what you need to do. 1. Create a skeleton project and web application for the site (as described in Django Tutorial Part 2: Creating a skeleton website). You might use 'diyblog' for the project name and 'blog' for the application name. 2. Create models for the Blog posts, Comments, and any other objects needed. When thinking about your design, remember: * Each comment will have only one blog, but a blog may have many comments. * Blog posts and comments must be sorted by post date. * Not every user will necessarily be a blog author though any user may be a commenter. * Blog authors must also include bio information. 3. Run migrations for your new models and create a superuser. 4. Use the admin site to create some example blog posts and blog comments. 5. Create views, templates, and URL configurations for blog post and blogger list pages. 6. Create views, templates, and URL configurations for blog post and blogger detail pages. 7. Create a page with a form for adding new comments (remember to make this only available to logged in users!) Hints and tips -------------- This project is very similar to the LocalLibrary tutorial. You will be able to set up the skeleton, user login/logout behavior, support for static files, views, URLs, forms, base templates and admin site configuration using almost all the same approaches. Some general hints: 1. The index page can be implemented as a basic function view and template (just like for the locallibrary). 2. The list view for blog posts and bloggers, and the detail view for blog posts can be created using the generic list and detail views. 3. The list of blog posts for a particular author can be created by using a generic blog list view and filtering for blog objects that match the specified author. * You will have to implement `get_queryset(self)` to do the filtering (much like in our library class `LoanedBooksAllListView`) and get the author information from the URL. * You will also need to pass the name of the author to the page in the context. To do this in a class-based view you need to implement `get_context_data()` (discussed below). 4. The *add comment* form can be created using a function-based view (and associated model and form) or using a generic `CreateView`. If you use a `CreateView` (recommended) then: * You will also need to pass the name of the blog post to the comment page in the context (implement `get_context_data()` as discussed below). * The form should only display the comment "description" for user entry (date and associated blog post should not be editable). Since they won't be in the form itself, your code will need to set the comment's author in the `form_valid()` function so it can be saved into the model (as described here — Django docs). In that same function we set the associated blog. A possible implementation is shown below (`pk` is a blog id passed in from the URL/URL configuration). python ```python def form\_valid(self, form): """ Add author and associated blog to form data before setting it as valid (so it is saved to model) """ #Add logged-in user as author of comment form.instance.author = self.request.user #Associate comment with blog based on passed id form.instance.blog=get_object_or_404(Blog, pk = self.kwargs['pk']) # Call super-class form validation behavior return super(BlogCommentCreate, self).form_valid(form) ``` * You will need to provide a success URL to redirect to after the form validates; this should be the original blog. To do this you will need to override `get_success_url()` and "reverse" the URL for the original blog. You can get the required blog ID using the `self.kwargs` attribute, as shown in the `form_valid()` method above. We briefly talked about passing a context to the template in a class-based view in the Django Tutorial Part 6: Generic list and detail views topic. To do this you need to override `get_context_data()` (first getting the existing context, updating it with whatever additional variables you want to pass to the template, and then returning the updated context). For example, the code fragment below shows how you can add a blogger object to the context based on their `BlogAuthor` id. ```python class SomeView(generic.ListView): # … def get\_context\_data(self, \*\*kwargs): # Call the base implementation first to get a context context = super(SomeView, self).get_context_data(\*\*kwargs) # Get the blogger object from the "pk" URL parameter and add it to the context context['blogger'] = get_object_or_404(BlogAuthor, pk = self.kwargs['pk']) return context ``` Assessment ---------- The assessment for this task is available on GitHub here. This assessment is primarily based on how well your application meets the requirements we listed above, though there are some parts of the assessment that check your code uses appropriate models, and that you have written at least some test code. When you're done, you can check out the finished example which reflects a "full marks" project. Once you've completed this module you've also finished all the MDN content for learning basic Django server-side website programming! We hope you enjoyed this module and feel you have a good grasp of the basics! * Previous * Overview: Django
Setting up a Django development environment - Learn web development
Setting up a Django development environment =========================================== * Previous * Overview: Django * Next Now that you know what Django is for, we'll show you how to set up and test a Django development environment on Windows, Linux (Ubuntu), and macOS — whatever common operating system you are using, this article should give you what you need to be able to start developing Django apps. | | | | --- | --- | | Prerequisites: | Basic knowledge of using a terminal/command line and how to install software packages on your development computer's operating system. | | Objective: | To have a development environment for Django (4.\*) running on your computer. | Django development environment overview --------------------------------------- Django makes it very easy to set up your own computer so that you can start developing web applications. This section explains what you get with the development environment, and provides an overview of some of your setup and configuration options. The remainder of the article explains the *recommended* method of installing the Django development environment on Ubuntu, macOS, and Windows, and how you can test it. ### What is the Django development environment? The development environment is an installation of Django on your local computer that you can use for developing and testing Django apps prior to deploying them to a production environment. The main tools that Django itself provides are a set of Python scripts for creating and working with Django projects, along with a simple *development web server* that you can use to test local (i.e. on your computer, not on an external web server) Django web applications on your computer's web browser. There are other peripheral tools, which form part of the development environment, that we won't be covering here. These include things like a text editor or IDE for editing code, and a source control management tool like Git for safely managing different versions of your code. We are assuming that you've already got a text editor installed. ### What are the Django setup options? Django is extremely flexible in terms of how and where it can be installed and configured. Django can be: * Installed on different operating systems. * Installed from source, from the Python Package Index (PyPi) and in many cases from the host computer's package manager application. * Configured to use one of several databases, which may also need to be separately installed and configured. * Run in the main system Python environment or within separate Python virtual environments. Each of these options requires a slightly different configuration and setup. The following subsections explain some of your choices. For the rest of the article, we'll show you how to set up Django on a small number of operating systems, and that setup will be assumed throughout the rest of this module. **Note:** Other possible installation options are covered in the official Django documentation. We link to the appropriate documents below. #### What operating systems are supported? Django web applications can be run on almost any machine that can run the Python 3 programming language: Windows, macOS, Linux/Unix, Solaris, to name just a few. Almost any computer should have the necessary performance to run Django during development. In this article, we'll provide instructions for Windows, macOS, and Linux/Unix. #### What version of Python should be used? You can use any Python version supported by your target Django release. For Django 4.2 the allowed versions are Python 3.8 to 3.11 (see FAQ:Installation). The Django project *recommends* (and "officially supports") using the newest available supported Python release. #### Where can we download Django? There are three places to download Django: * The Python Package Repository (PyPi), using the *pip* tool. This is the best way to get the latest stable version of Django. * Use a version from your computer's package manager. Distributions of Django that are bundled with operating systems offer a familiar installation mechanism. Note however that the packaged version may be quite old, and can only be installed into the system Python environment (which may not be what you want). * Install from source. You can get and install the latest bleeding-edge version of Django from the source. This is not recommended for beginners but is needed when you're ready to start contributing back to Django itself. This article shows how to install Django from PyPi, in order to get the latest stable version. #### Which database? Django officially supports the PostgreSQL, MariaDB, MySQL, Oracle, and SQLite databases, and there are community libraries that provide varying levels of support for other popular SQL and NoSQL databases. We recommend that you select the same database for both production and development (although Django abstracts many of the database differences using its Object-Relational Mapper (ORM), there are still potential issues that are better to avoid). For this article (and most of this module) we will be using the *SQLite* database, which stores its data in a file. SQLite is intended for use as a lightweight database and can't support a high level of concurrency. It is, however, an excellent choice for applications that are primarily read-only. **Note:** Django is configured to use SQLite by default when you start your website project using the standard tools (*django-admin*). It's a great choice when you're getting started because it requires no additional configuration or setup. #### Installing system-wide or in a Python virtual environment? When you install Python3 you get a single global environment that is shared by all Python3 code. While you can install whatever Python packages you like in the environment, you can only install one particular version of each package at a time. **Note:** Python applications installed into the global environment can potentially conflict with each other (i.e. if they depend on different versions of the same package). If you install Django into the default/global environment then you will only be able to target one version of Django on the computer. This can be a problem if you want to create new websites (using the latest version of Django) while still maintaining websites that rely on older versions. As a result, experienced Python/Django developers typically run Python apps within independent *Python virtual environments*. This enables multiple different Django environments on a single computer. The Django developer team itself recommends that you use Python virtual environments! This module assumes that you've installed Django into a virtual environment, and we'll show you how below. Installing Python 3 ------------------- In order to use Django you must have Python 3 on your operating system. You will also need the Python Package Index tool — *pip3* — which is used to manage (install, update, and remove) Python packages/libraries used by Django and your other Python apps. This section briefly explains how you can check what versions of Python are present, and install new versions as needed, for Ubuntu Linux 20.04, macOS, and Windows 10. **Note:** Depending on your platform, you may also be able to install Python/pip from the operating system's own package manager or via other mechanisms. For most platforms, you can download the required installation files from https://www.python.org/downloads/ and install them using the appropriate platform-specific method. ### Ubuntu 20.04 Ubuntu Linux 20.04 LTS includes Python 3.8.10 by default. You can confirm this by running the following command in the bash terminal: ```bash python3 -V # Output: Python 3.8.10 ``` However, the Python Package Index tool (*pip3*) you'll need to install packages for Python 3 (including Django) is **not** available by default. You can install *pip3* in the bash terminal using: ```bash sudo apt install python3-pip ``` **Note:** Python 3.8 is the oldest version supported by Django 4.2. While Django recommend you update to the latest version, you don't *need* to use the latest version for this tutorial. If you want to update Python, then there are instructions on the internet. ### macOS macOS does not include Python 3 by default (Python 2 is included on older versions). You can confirm this by running the following command in the terminal: ```bash python3 -V ``` This will either display the Python version number, which indicates that Python 3 is installed, or `python3: command not found`, which indicates Python 3 was not found. You can easily install Python 3 (along with the *pip3* tool) from python.org: 1. Download the required installer: 1. Go to https://www.python.org/downloads/macos/ 2. Download the most recent supported version that works with Django 4.2. (at time of writing this is Python 3.11.4). 2. Locate the file using *Finder*, and double-click the package file. Following the installation prompts. You can now confirm successful installation by running `python3 -V` again and checking for the Python version number. You can similarly check that *pip3* is installed by listing the available packages: ```bash pip3 list ``` ### Windows 10 or 11 Windows doesn't include Python by default, but you can easily install it (along with the *pip3* tool) from python.org: 1. Download the required installer: 1. Go to https://www.python.org/downloads/windows/ 2. Download the most recent supported version that works with Django 4.2. (at time of writing this is Python 3.11.4). 2. Install Python by double-clicking on the downloaded file and following the installation prompts 3. Be sure to check the box labeled "Add Python to PATH" You can then verify that Python 3 was installed by entering the following text into the command prompt: ```bash py -3 -V ``` The Windows installer incorporates *pip3* (the Python package manager) by default. You can list installed packages as shown: ```bash py -3 -m pip list ``` **Note:** The installer should set up everything you need for the above command to work. If however you get a message that Python cannot be found, you may have forgotten to add it to your system path. You can do this by running the installer again, selecting "Modify", and checking the box labeled "Add Python to environment variables" on the second page. Calling Python 3 and pip3 ------------------------- You will note that in the previous sections we use different commands to call Python 3 and pip on different operating systems. If you only have Python 3 installed (and not Python 2), the bare commands `python` and `pip` can generally be used to run Python and pip on any operating system. If this is allowed on your system you will get a version "3" string when you run `-V` with the bare commands, as shown: ```bash python -V pip -V ``` If Python 2 is installed then to use version 3 you should prefix commands with `python3` and `pip3` on Linux/macOS, and `py -3` and `py -3 -m pip` on Windows: ```bash # Linux/macOS python3 -V pip3 -V # Windows py -3 -V py -3 -m pip list ``` The instructions below show the platform specific commands as they work on more systems. Using Django inside a Python virtual environment ------------------------------------------------ The libraries we'll use for creating our virtual environments are virtualenvwrapper (Linux and macOS) and virtualenvwrapper-win (Windows), which in turn both use the virtualenv tool. The wrapper tools creates a consistent interface for managing interfaces on all platforms. ### Installing the virtual environment software #### Ubuntu virtual environment setup After installing Python and pip you can install *virtualenvwrapper* (which includes *virtualenv*). The official installation guide can be found here, or follow the instructions below. Install the tool using *pip3*: ```bash sudo pip3 install virtualenvwrapper ``` Then add the following lines to the end of your shell startup file (this is a hidden file name **.bashrc** in your home directory). These set the location where the virtual environments should live, the location of your development project directories, and the location of the script installed with this package: ```bash export WORKON\_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER\_PYTHON=/usr/bin/python3 export VIRTUALENVWRAPPER\_VIRTUALENV\_ARGS=' -p /usr/bin/python3 ' export PROJECT\_HOME=$HOME/Devel source /usr/local/bin/virtualenvwrapper.sh ``` **Note:** The `VIRTUALENVWRAPPER_PYTHON` and `VIRTUALENVWRAPPER_VIRTUALENV_ARGS` variables point to the normal installation location for Python 3, and `source /usr/local/bin/virtualenvwrapper.sh` points to the normal location of the `virtualenvwrapper.sh` script. If the *virtualenv* doesn't work when you test it, one thing to check is that Python and the script are in the expected location (and then change the startup file appropriately). You can find the correct locations for your system using the commands `which virtualenvwrapper.sh` and `which python3`. Then reload the startup file by running the following command in the terminal: ```bash source ~/.bashrc ``` At this point you should see a bunch of scripts being run as shown below: ```bash virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/premkproject virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/postmkproject # … virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/preactivate virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/postactivate virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/get_env_details ``` Now you can create a new virtual environment with the `mkvirtualenv` command. #### macOS virtual environment setup Setting up *virtualenvwrapper* on macOS is almost exactly the same as on Ubuntu (again, you can follow the instructions from either the official installation guide or below). Install *virtualenvwrapper* (and bundling *virtualenv*) using *pip* as shown. ```bash sudo pip3 install virtualenvwrapper ``` Then add the following lines to the end of your shell startup file (these are the same lines as for Ubuntu). If you're using the *zsh shell* then the startup file will be a hidden file named **.zshrc** in your home directory. If you're using the *bash shell* then it will be a hidden file named **.bash\_profile**. You may need to create the file if it does not yet exist. ```bash export WORKON\_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER\_PYTHON=/usr/bin/python3 export PROJECT\_HOME=$HOME/Devel source /usr/local/bin/virtualenvwrapper.sh ``` **Note:** The `VIRTUALENVWRAPPER_PYTHON` variable points to the normal installation location for Python 3, and `source /usr/local/bin/virtualenvwrapper.sh` points to the normal location of the `virtualenvwrapper.sh` script. If the *virtualenv* doesn't work when you test it, one thing to check is that Python and the script are in the expected location (and then change the startup file appropriately). For example, one installation test on macOS ended up with the following lines being necessary in the startup file: ```bash export WORKON\_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER\_PYTHON=/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 export PROJECT\_HOME=$HOME/Devel source /Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh ``` You can find the correct locations for your system using the commands `which virtualenvwrapper.sh` and `which python3`. Then reload the startup file by making the following call in the terminal: ```bash source ~/.bash_profile ``` At this point, you may see a bunch of scripts being run (the same scripts as for the Ubuntu installation). You should now be able to create a new virtual environment with the `mkvirtualenv` command. **Note:** If you can't find the startup file to edit in the finder, you can also open this in the terminal using nano. Assuming you're using bash, the commands look something like this: ```bash cd ~ # Navigate to my home directory ls -la #List the content of the directory. You should see .bash\_profile nano .bash_profile # Open the file in the nano text editor, within the terminal # Scroll to the end of the file, and copy in the lines above # Use Ctrl+X to exit nano, choose Y to save the file. ``` #### Windows virtual environment setup Installing virtualenvwrapper-win is even simpler than setting up *virtualenvwrapper* because you don't need to configure where the tool stores virtual environment information (there is a default value). All you need to do is run the following command in the command prompt: ```bash py -3 -m pip install virtualenvwrapper-win ``` Now you can create a new virtual environment with the `mkvirtualenv` command ### Creating a virtual environment Once you've installed *virtualenvwrapper* or *virtualenvwrapper-win* then working with virtual environments is very similar on all platforms. Now you can create a new virtual environment with the `mkvirtualenv` command. As this command runs you'll see the environment being set up (what you see is slightly platform-specific). When the command completes the new virtual environment will be active — you can see this because the start of the prompt will be the name of the environment in parentheses (below we show this for Ubuntu, but the final line is similar for Windows/macOS). ```bash mkvirtualenv my_django_environment ``` You should see output similar to the following: ``` Running virtualenv with interpreter /usr/bin/python3 # … virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/t_env7/bin/get_env_details (my_django_environment) ubuntu@ubuntu:~$ ``` Now you're inside the virtual environment you can install Django and start developing. **Note:** From now on in this article (and indeed the module) please assume that any commands are run within a Python virtual environment like the one we set up above. ### Using a virtual environment There are just a few other useful commands that you should know (there are more in the tool documentation, but these are the ones you'll use regularly): * `deactivate` — Exit out of the current Python virtual environment * `workon` — List available virtual environments * `workon name_of_environment` — Activate the specified Python virtual environment * `rmvirtualenv name_of_environment` — Remove the specified environment. Installing Django ----------------- Once you've created a virtual environment, and called `workon` to enter it, you can use *pip3* to install Django. ```bash # Linux/macOS python3 -m pip install django~=4.2 # Windows py -3 -m pip install django~=4.2 ``` You can test that Django is installed by running the following command (this just tests that Python can find the Django module): ```bash # Linux/macOS python3 -m django --version # Windows py -3 -m django --version ``` **Note:** If the above Windows command does not show a django module present, try: ```bash py -m django --version ``` In Windows *Python 3* scripts are launched by prefixing the command with `py -3`, although this can vary depending on your specific installation. Try omitting the `-3` modifier if you encounter any problems with commands. In Linux/macOS, the command is `python3.` **Warning:** The rest of this **module** uses the *Linux* command for invoking Python 3 (`python3`). If you're working on *Windows* replace this prefix with: `py -3` Other Python tools ------------------ Experienced Python developers may install additional tools, such as linters (which help detect common errors in code). Note that you should use a Django-aware linter such as pylint-django, because some common Python linters (such as `pylint`) incorrectly report errors in the standard files generated for Django. Testing your installation ------------------------- The above test works, but it isn't very much fun. A more interesting test is to create a skeleton project and see it working. To do this, first navigate in your command prompt/terminal to where you want to store your Django apps. Create a folder for your test site and navigate into it. ```bash mkdir django_test cd django_test ``` You can then create a new skeleton site called "*mytestsite*" using the **django-admin** tool as shown. After creating the site you can navigate into the folder where you will find the main script for managing projects, called **manage.py**. ```bash django-admin startproject mytestsite cd mytestsite ``` We can run the *development web server* from within this folder using **manage.py** and the `runserver` command, as shown. ```bash # Linux/macOS python3 manage.py runserver # Windows py -3 manage.py runserver ``` **Note:** You can ignore the warnings about "unapplied migration(s)" at this point! Once the server is running you can view the site by navigating to the following URL on your local web browser: `http://127.0.0.1:8000/`. You should see a site that looks like this: ![The home page of the skeleton Django app](/en-US/docs/Learn/Server-side/Django/development_environment/django_skeleton_app_homepage_django_4_0.png) Summary ------- You now have a Django development environment up and running on your computer. In the testing section you also briefly saw how we can create a new Django website using `django-admin startproject`, and run it in your browser using the development web server (`python3 manage.py runserver`). In the next article, we expand on this process, building a simple but complete web application. See also -------- * Quick Install Guide (Django docs) * How to install Django — Complete guide (Django docs) — also covers how to remove Django * How to install Django on Windows (Django docs) * Previous * Overview: Django * Next
Django Tutorial: The Local Library website - Learn web development
Django Tutorial: The Local Library website ========================================== * Previous * Overview: Django * Next The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" example website we'll be working through and evolving in subsequent articles. | | | | --- | --- | | Prerequisites: | Read the Django Introduction. For the following articles you'll also need to have set up a Django development environment. | | Objective: | To introduce the example application used in this tutorial, and allow readers to understand what topics will be covered. | Overview -------- Welcome to the MDN "Local Library" Django tutorial, in which we develop a website that might be used to manage the catalog for a local library. In this series of tutorial articles you will: * Use Django's tools to create a skeleton website and application. * Start and stop the development server. * Create models to represent your application's data. * Use the Django admin site to populate your site's data. * Create views to retrieve specific data in response to different requests, and templates to render the data as HTML to be displayed in the browser. * Create mappers to associate different URL patterns with specific views. * Add user authorization and sessions to control site behavior and access. * Work with forms. * Write test code for your app. * Use Django's security effectively. * Deploy your application to production. You have learned about some of these topics already, and touched briefly on others. By the end of the tutorial series you should know enough to develop simple Django apps by yourself. The LocalLibrary website ------------------------ *LocalLibrary* is the name of the website that we'll create and evolve over the course of this series of tutorials. As you'd expect, the purpose of the website is to provide an online catalog for a small local library, where users can browse available books and manage their accounts. This example has been carefully chosen because it can scale to show as much or as little detail as we need, and can be used to show off almost any Django feature. More importantly, it allows us to provide a *guided* path through the most important functionality in the Django web framework: * In the first few tutorial articles we will define a simple *browse-only* library that library members can use to find out what books are available. This allows us to explore the operations that are common to almost every website: reading and displaying content from a database. * As we progress, the library example naturally extends to demonstrate more advanced Django features. For example we can extend the library to allow users to reserve books, and use this to demonstrate how to use forms, and support user authentication. Even though this is a very extensible example, it's called ***Local**Library* for a reason — we're hoping to show the minimum information that will help you get up and running with Django quickly. As a result we'll store information about books, copies of books, authors and other key information. We won't however be storing information about other items a library might store, or provide the infrastructure needed to support multiple library sites or other "big library" features. I'm stuck, where can I get the source? -------------------------------------- As you work through the tutorial we'll provide the appropriate code snippets for you to copy and paste at each point, and there will be other code that we hope you'll extend yourself (with some guidance). If you get stuck, you can find the fully developed version of the website on GitHub here. Summary ------- Now that you know a bit more about the *LocalLibrary* website and what you're going to learn, it's time to start creating a skeleton project to contain our example. * Previous * Overview: Django * Next
Django Tutorial Part 7: Sessions framework - Learn web development
Django Tutorial Part 7: Sessions framework ========================================== * Previous * Overview: Django * Next This tutorial extends our LocalLibrary website, adding a session-based visit-counter to the home page. This is a relatively simple example, but it does show how you can use the session framework to provide persistent behavior for anonymous users in your own sites. | | | | --- | --- | | Prerequisites: | Complete all previous tutorial topics, including Django Tutorial Part 6: Generic list and detail views | | Objective: | To understand how sessions are used. | Overview -------- The LocalLibrary website we created in the previous tutorials allows users to browse books and authors in the catalog. While the content is dynamically generated from the database, every user will essentially have access to the same pages and types of information when they use the site. In a "real" library you may wish to provide individual users with a customized experience, based on their previous use of the site, preferences, etc. For example, you could hide warning messages that the user has previously acknowledged next time they visit the site, or store and respect their preferences (such as, the number of search results that they want to be displayed on each page). The session framework lets you implement this sort of behavior, allowing you to store and retrieve arbitrary data on a per-site-visitor basis. What are sessions? ------------------ All communication between web browsers and servers is via HTTP, which is *stateless*. The fact that the protocol is stateless means that messages between the client and server are completely independent of each other — there is no notion of "sequence" or behavior based on previous messages. As a result, if you want to have a site that keeps track of the ongoing relationships with a client, you need to implement that yourself. Sessions are the mechanism used by Django (and most of the Internet) for keeping track of the "state" between the site and a particular browser. Sessions allow you to store arbitrary data per browser, and have this data available to the site whenever the browser connects. Individual data items associated with the session are then referenced by a "key", which is used both to store and retrieve the data. Django uses a cookie containing a special *session id* to identify each browser and its associated session with the site. The actual session *data* is stored in the site database by default (this is more secure than storing the data in a cookie, where they are more vulnerable to malicious users). You can configure Django to store the session data in other places (cache, files, "secure" cookies), but the default location is a good and relatively secure option. Enabling sessions ----------------- Sessions were enabled automatically when we created the skeleton website (in tutorial 2). The configuration is set up in the `INSTALLED_APPS` and `MIDDLEWARE` sections of the project file (**locallibrary/locallibrary/settings.py**), as shown below: ```python INSTALLED_APPS = [ # … 'django.contrib.sessions', # … MIDDLEWARE = [ # … 'django.contrib.sessions.middleware.SessionMiddleware', # … ``` Using sessions -------------- You can access the `session` attribute within a view from the `request` parameter (an `HttpRequest` passed in as the first argument to the view). This session attribute represents the specific connection to the current user (or to be more precise, the connection to the current *browser*, as identified by the session id in the browser's cookie for this site). The `session` attribute is a dictionary-like object that you can read and write as many times as you like in your view, modifying it as wished. You can do all the normal dictionary operations, including clearing all data, testing if a key is present, looping through data, etc. Most of the time though, you'll just use the standard "dictionary" API to get and set values. The code fragments below show how you can get, set, and delete some data with the key "`my_car`", associated with the current session (browser). **Note:** One of the great things about Django is that you don't need to think about the mechanisms that tie the session to your current request in your view. If we were to use the fragments below in our view, we'd know that the information about `my_car` is associated only with the browser that sent the current request. ```python # Get a session value by its key (e.g. 'my\_car'), raising a KeyError if the key is not present my_car = request.session['my\_car'] # Get a session value, setting a default if it is not present ('mini') my_car = request.session.get('my\_car', 'mini') # Set a session value request.session['my\_car'] = 'mini' # Delete a session value del request.session['my\_car'] ``` The API also offers a number of other methods that are mostly used to manage the associated session cookie. For example, there are methods to test that cookies are supported in the client browser, to set and check cookie expiry dates, and to clear expired sessions from the data store. You can find out about the full API in How to use sessions (Django docs). Saving session data ------------------- By default, Django only saves to the session database and sends the session cookie to the client when the session has been *modified* (assigned) or *deleted*. If you're updating some data using its session key as shown in the previous section, then you don't need to worry about this! For example: ```python # This is detected as an update to the session, so session data is saved. request.session['my\_car'] = 'mini' ``` If you're updating some information *within* session data, then Django will not recognize that you've made a change to the session and save the data (for example, if you were to change "`wheels`" data inside your "`my_car`" data, as shown below). In this case you will need to explicitly mark the session as having been modified. ```python # Session object not directly modified, only data within the session. Session changes not saved! request.session['my\_car']['wheels'] = 'alloy' # Set session as modified to force data updates/cookie to be saved. request.session.modified = True ``` **Note:** You can change the behavior so the site will update the database/send cookie on every request by adding `SESSION_SAVE_EVERY_REQUEST = True` into your project settings (**locallibrary/locallibrary/settings.py**). Simple example — getting visit counts ------------------------------------- As a simple real-world example we'll update our library to tell the current user how many times they have visited the *LocalLibrary* home page. Open **/locallibrary/catalog/views.py**, and add the lines that contain `num_visits` into `index()` (as shown below). ```python def index(request): # … num_authors = Author.objects.count() # The 'all()' is implied by default. # Number of visits to this view, as counted in the session variable. num_visits = request.session.get('num\_visits', 0) request.session['num\_visits'] = num_visits + 1 context = { 'num\_books': num_books, 'num\_instances': num_instances, 'num\_instances\_available': num_instances_available, 'num\_authors': num_authors, 'num\_visits': num_visits, } # Render the HTML template index.html with the data in the context variable. return render(request, 'index.html', context=context) ``` Here we first get the value of the `'num_visits'` session key, setting the value to 0 if it has not previously been set. Each time a request is received, we then increment the value and store it back in the session (for the next time the user visits the page). The `num_visits` variable is then passed to the template in our context variable. **Note:** We might also test whether cookies are even supported in the browser here (see How to use sessions for examples) or design our UI so that it doesn't matter whether or not cookies are supported. Add the line shown at the bottom of the following block to your main HTML template (**/locallibrary/catalog/templates/index.html**) at the bottom of the "Dynamic content" section to display the `num_visits` context variable. ```django <h2>Dynamic content</h2> <p>The library has the following record counts:</p> <ul> <li><strong>Books:</strong> {{ num\_books }}</li> <li><strong>Copies:</strong> {{ num\_instances }}</li> <li><strong>Copies available:</strong> {{ num\_instances\_available }}</li> <li><strong>Authors:</strong> {{ num\_authors }}</li> </ul> <p> You have visited this page {{ num\_visits }} time{{ num\_visits|pluralize }}. </p> ``` Note that we use the Django built-in template tag pluralize to add an "s" when the page has been visited multiple time**s**. Save your changes and restart the test server. Every time you refresh the page, the number should update. Summary ------- You now know how easy it is to use sessions to improve your interaction with *anonymous* users. In our next articles we'll explain the authentication and authorization (permission) framework, and show you how to support user accounts. See also -------- * How to use sessions (Django docs) * Previous * Overview: Django * Next
Django Tutorial Part 3: Using models - Learn web development
Django Tutorial Part 3: Using models ==================================== * Previous * Overview: Django * Next This article shows how to define models for the LocalLibrary website. It explains what a model is, how it is declared, and some of the main field types. It also briefly shows a few of the main ways you can access model data. | | | | --- | --- | | Prerequisites: | Django Tutorial Part 2: Creating a skeleton website. | | Objective: | To be able to design and create your own models, choosing fields appropriately. | Overview -------- Django web applications access and manage data through Python objects referred to as models. Models define the *structure* of stored data, including the field *types* and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc. The definition of the model is independent of the underlying database — you can choose one of several as part of your project settings. Once you've chosen what database you want to use, you don't need to talk to it directly at all — you just write your model structure and other code, and Django handles all the dirty work of communicating with the database for you. This tutorial shows how to define and access the models for the LocalLibrary website example. Designing the LocalLibrary models --------------------------------- Before you jump in and start coding the models, it's worth taking a few minutes to think about what data we need to store and the relationships between the different objects. We know that we need to store information about books (title, summary, author, written language, category, ISBN) and that we might have multiple copies available (with globally unique id, availability status, etc.). We might need to store more information about the author than just their name, and there might be multiple authors with the same or similar names. We want to be able to sort information based on book title, author, written language, and category. When designing your models, it makes sense to have separate models for every "object" (a group of related information). In this case, the obvious objects are books, book instances, and authors. You might also want to use models to represent selection-list options (e.g. like a drop down list of choices), rather than hard coding the choices into the website itself — this is recommended when all the options aren't known up front or may change. Obvious candidates for models, in this case, include the book genre (e.g. Science Fiction, French Poetry, etc.) and language (English, French, Japanese). Once we've decided on our models and field, we need to think about the relationships. Django allows you to define relationships that are one to one (`OneToOneField`), one to many (`ForeignKey`) and many to many (`ManyToManyField`). With that in mind, the UML association diagram below shows the models we'll define in this case (as boxes). ![LocalLibrary Model UML with fixed Author multiplicity inside the Book class](/en-US/docs/Learn/Server-side/Django/Models/local_library_model_uml.svg) We've created models for the book (the generic details of the book), book instance (status of specific physical copies of the book available in the system), and author. We have also decided to have a model for the genre so that values can be created/selected through the admin interface. We've decided not to have a model for the `BookInstance:status` — we've hardcoded the values (`LOAN_STATUS`) because we don't expect these to change. Within each of the boxes, you can see the model name, the field names, and types, and also the methods and their return types. The diagram also shows the relationships between the models, including their *multiplicities*. The multiplicities are the numbers on the diagram showing the numbers (maximum and minimum) of each model that may be present in the relationship. For example, the connecting line between the boxes shows that Book and a Genre are related. The numbers close to the Genre model show that a book must have one or more Genres (as many as you like), while the numbers on the other end of the line next to the Book model show that a Genre can have zero or many associated books. **Note:** The next section provides a basic primer explaining how models are defined and used. As you read it, consider how we will construct each of the models in the diagram above. Model primer ------------ This section provides a brief overview of how a model is defined and some of the more important fields and field arguments. ### Model definition Models are usually defined in an application's **models.py** file. They are implemented as subclasses of `django.db.models.Model`, and can include fields, methods and metadata. The code fragment below shows a "typical" model, named `MyModelName`: ```python from django.db import models from django.urls import reverse class MyModelName(models.Model): """A typical class defining a model, derived from the Model class.""" # Fields my_field_name = models.CharField(max_length=20, help_text='Enter field documentation') # … # Metadata class Meta: ordering = ['-my\_field\_name'] # Methods def get\_absolute\_url(self): """Returns the URL to access a particular instance of MyModelName.""" return reverse('model-detail-view', args=[str(self.id)]) def \_\_str\_\_(self): """String for representing the MyModelName object (in Admin site etc.).""" return self.my_field_name ``` In the below sections we'll explore each of the features inside the model in detail: #### Fields A model can have an arbitrary number of fields, of any type — each one represents a column of data that we want to store in one of our database tables. Each database record (row) will consist of one of each field value. Let's look at the example seen below: ```python my_field_name = models.CharField(max_length=20, help_text='Enter field documentation') ``` Our above example has a single field called `my_field_name`, of type `models.CharField` — which means that this field will contain strings of alphanumeric characters. The field types are assigned using specific classes, which determine the type of record that is used to store the data in the database, along with validation criteria to be used when values are received from an HTML form (i.e. what constitutes a valid value). The field types can also take arguments that further specify how the field is stored or can be used. In this case we are giving our field two arguments: * `max_length=20` — States that the maximum length of a value in this field is 20 characters. * `help_text='Enter field documentation'` — helpful text that may be displayed in a form to help users understand how the field is used. The field name is used to refer to it in queries and templates. Fields also have a label, which is specified using the `verbose_name` argument (with a default value of `None`). If `verbose_name` is not set, the label is created from the field name by replacing any underscores with a space, and capitalizing the first letter (for example, the field `my_field_name` would have a default label of *My field name* when used in forms). The order that fields are declared will affect their default order if a model is rendered in a form (e.g. in the Admin site), though this may be overridden. ##### Common field arguments The following common arguments can be used when declaring many/most of the different field types: * help\_text: Provides a text label for HTML forms (e.g. in the admin site), as described above. * verbose\_name: A human-readable name for the field used in field labels. If not specified, Django will infer the default verbose name from the field name. * default: The default value for the field. This can be a value or a callable object, in which case the object will be called every time a new record is created. * null: If `True`, Django will store blank values as `NULL` in the database for fields where this is appropriate (a `CharField` will instead store an empty string). The default is `False`. * blank: If `True`, the field is allowed to be blank in your forms. The default is `False`, which means that Django's form validation will force you to enter a value. This is often used with `null=True`, because if you're going to allow blank values, you also want the database to be able to represent them appropriately. * choices: A group of choices for this field. If this is provided, the default corresponding form widget will be a select box with these choices instead of the standard text field. * unique: If `True`, ensures that the field value is unique across the database. This can be used to prevent duplication of fields that can't have the same values. The default is `False`. * primary\_key: If `True`, sets the current field as the primary key for the model (A primary key is a special database column designated to uniquely identify all the different table records). If no field is specified as the primary key, Django will automatically add a field for this purpose. The type of auto-created primary key fields can be specified for each app in `AppConfig.default_auto_field` or globally in the `DEFAULT_AUTO_FIELD` setting. **Note:** Apps created using **manage.py** set the type of the primary key to a BigAutoField. You can see this in the local library **catalog/apps.py** file: ```py class CatalogConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' ``` There are many other options — you can view the full list of field options here. ##### Common field types The following list describes some of the more commonly used types of fields. * CharField is used to define short-to-mid sized fixed-length strings. You must specify the `max_length` of the data to be stored. * TextField is used for large arbitrary-length strings. You may specify a `max_length` for the field, but this is used only when the field is displayed in forms (it is not enforced at the database level). * IntegerField is a field for storing integer (whole number) values, and for validating entered values as integers in forms. * DateField and DateTimeField are used for storing/representing dates and date/time information (as Python `datetime.date` and `datetime.datetime` objects, respectively). These fields can additionally declare the (mutually exclusive) parameters `auto_now=True` (to set the field to the current date every time the model is saved), `auto_now_add` (to only set the date when the model is first created), and `default` (to set a default date that can be overridden by the user). * EmailField is used to store and validate email addresses. * FileField and ImageField are used to upload files and images respectively (the `ImageField` adds additional validation that the uploaded file is an image). These have parameters to define how and where the uploaded files are stored. * AutoField is a special type of `IntegerField` that automatically increments. A primary key of this type is automatically added to your model if you don't explicitly specify one. * ForeignKey is used to specify a one-to-many relationship to another database model (e.g. a car has one manufacturer, but a manufacturer can make many cars). The "one" side of the relationship is the model that contains the "key" (models containing a "foreign key" referring to that "key", are on the "many" side of such a relationship). * ManyToManyField is used to specify a many-to-many relationship (e.g. a book can have several genres, and each genre can contain several books). In our library app we will use these very similarly to `ForeignKeys`, but they can be used in more complicated ways to describe the relationships between groups. These have the parameter `on_delete` to define what happens when the associated record is deleted (e.g. a value of `models.SET_NULL` would set the value to `NULL`). There are many other types of fields, including fields for different types of numbers (big integers, small integers, floats), booleans, URLs, slugs, unique ids, and other "time-related" information (duration, time, etc.). You can view the full list here. #### Metadata You can declare model-level metadata for your Model by declaring `class Meta`, as shown. ```python class Meta: ordering = ['-my\_field\_name'] ``` One of the most useful features of this metadata is to control the *default ordering* of records returned when you query the model type. You do this by specifying the match order in a list of field names to the `ordering` attribute, as shown above. The ordering will depend on the type of field (character fields are sorted alphabetically, while date fields are sorted in chronological order). As shown above, you can prefix the field name with a minus symbol (-) to reverse the sorting order. So as an example, if we chose to sort books like this by default: ```python ordering = ['title', '-pubdate'] ``` the books would be sorted alphabetically by title, from A-Z, and then by publication date inside each title, from newest to oldest. Another common attribute is `verbose_name`, a verbose name for the class in singular and plural form: ```python verbose_name = 'BetterName' ``` Other useful attributes allow you to create and apply new "access permissions" for the model (default permissions are applied automatically), allow ordering based on another field, or to declare that the class is "abstract" (a base class that you cannot create records for, and will instead be derived from to create other models). Many of the other metadata options control what database must be used for the model and how the data is stored (these are really only useful if you need to map a model to an existing database). The full list of metadata options are available here: Model metadata options (Django docs). #### Methods A model can also have methods. **Minimally, in every model you should define the standard Python class method `__str__()` to return a human-readable string for each object.** This string is used to represent individual records in the administration site (and anywhere else you need to refer to a model instance). Often this will return a title or name field from the model. ```python def \_\_str\_\_(self): return self.my_field_name ``` Another common method to include in Django models is `get_absolute_url()`, which returns a URL for displaying individual model records on the website (if you define this method then Django will automatically add a "View on Site" button to the model's record editing screens in the Admin site). A typical pattern for `get_absolute_url()` is shown below. ```python def get\_absolute\_url(self): """Returns the URL to access a particular instance of the model.""" return reverse('model-detail-view', args=[str(self.id)]) ``` **Note:** Assuming you will use URLs like `/myapplication/mymodelname/2` to display individual records for your model (where "2" is the `id` for a particular record), you will need to create a URL mapper to pass the response and id to a "model detail view" (which will do the work required to display the record). The `reverse()` function above is able to "reverse" your URL mapper (in the above case named *'model-detail-view'*) in order to create a URL of the right format. Of course to make this work you still have to write the URL mapping, view, and template! You can also define any other methods you like, and call them from your code or templates (provided that they don't take any parameters). ### Model management Once you've defined your model classes you can use them to create, update, or delete records, and to run queries to get all records or particular subsets of records. We'll show you how to do that in the tutorial when we define our views, but here is a brief summary. #### Creating and modifying records To create a record you can define an instance of the model and then call `save()`. ```python # Create a new record using the model's constructor. record = MyModelName(my_field_name="Instance #1") # Save the object into the database. record.save() ``` **Note:** If you haven't declared any field as a `primary_key`, the new record will be given one automatically, with the field name `id`. You could query this field after saving the above record, and it would have a value of 1. You can access the fields in this new record using the dot syntax, and change the values. You have to call `save()` to store modified values to the database. ```python # Access model field values using Python attributes. print(record.id) # should return 1 for the first record. print(record.my_field_name) # should print 'Instance #1' # Change record by modifying the fields, then calling save(). record.my_field_name = "New Instance Name" record.save() ``` #### Searching for records You can search for records that match certain criteria using the model's `objects` attribute (provided by the base class). **Note:** Explaining how to search for records using "abstract" model and field names can be a little confusing. In the discussion below, we'll refer to a `Book` model with `title` and `genre` fields, where genre is also a model with a single field `name`. We can get all records for a model as a `QuerySet`, using `objects.all()`. The `QuerySet` is an iterable object, meaning that it contains a number of objects that we can iterate/loop through. ```python all_books = Book.objects.all() ``` Django's `filter()` method allows us to filter the returned `QuerySet` to match a specified **text** or **numeric** field against particular criteria. For example, to filter for books that contain "wild" in the title and then count them, we could do the following. ```python wild_books = Book.objects.filter(title__contains='wild') number_wild_books = wild_books.count() ``` The fields to match and the type of match are defined in the filter parameter name, using the format: `field_name__match_type` (note the *double underscore* between `title` and `contains` above). Above we're filtering `title` with a case-sensitive match. There are many other types of matches you can do: `icontains` (case insensitive), `iexact` (case-insensitive exact match), `exact` (case-sensitive exact match) and `in`, `gt` (greater than), `startswith`, etc. The full list is here. In some cases, you'll need to filter on a field that defines a one-to-many relationship to another model (e.g. a `ForeignKey`). In this case, you can "index" to fields within the related model with additional double underscores. So for example to filter for books with a specific genre pattern, you will have to index to the `name` through the `genre` field, as shown below: ```python # Will match on: Fiction, Science fiction, non-fiction etc. books_containing_genre = Book.objects.filter(genre__name__icontains='fiction') ``` **Note:** You can use underscores (`__`) to navigate as many levels of relationships (`ForeignKey`/`ManyToManyField`) as you like. For example, a `Book` that had different types, defined using a further "cover" relationship might have a parameter name: `type__cover__name__exact='hard'.` There is a lot more you can do with queries, including backwards searches from related models, chaining filters, returning a smaller set of values, etc. For more information, see Making queries (Django Docs). Defining the LocalLibrary Models -------------------------------- In this section we will start defining the models for the library. Open `models.py` (in /locallibrary/catalog/). The boilerplate at the top of the page imports the *models* module, which contains the model base class `models.Model` that our models will inherit from. ```python from django.db import models # Create your models here. ``` ### Genre model Copy the `Genre` model code shown below and paste it into the bottom of your `models.py` file. This model is used to store information about the book category — for example whether it is fiction or non-fiction, romance or military history, etc. As mentioned above, we've created the genre as a model rather than as free text or a selection list so that the possible values can be managed through the database rather than being hard coded. ```python from django.urls import reverse # Used to generate URLs by reversing the URL patterns class Genre(models.Model): """Model representing a book genre.""" name = models.CharField( max_length=200, unique=True, help_text="Enter a book genre (e.g. Science Fiction, French Poetry etc.)" ) def \_\_str\_\_(self): """String for representing the Model object.""" return self.name def get\_absolute\_url(self): """Returns the url to access a particular genre instance.""" return reverse('genre-detail', args=[str(self.id)]) ``` The model has a single `CharField` field (`name`), which is used to describe the genre (this is limited to 200 characters and has some `help_text`). We've set this field to be unique (`unique=True`) because there should only be one record for each genre. After the field, we declare a `__str__()` method, which returns the name of the genre defined by a particular record. No verbose name has been defined, so the field will be called `Name` in forms. The final method, `get_absolute_url()` returns a URL that can be used to access a detail record for this model (for this to work, we will have to define a URL mapping that has the name `genre-detail`, and define an associated view and template). ### Book model Copy the `Book` model below and again paste it into the bottom of your file. The `Book` model represents all information about an available book in a general sense, but not a particular physical "instance" or "copy" available for loan. The model uses a `CharField` to represent the book's `title` and `isbn`. For `isbn`, note how the first unnamed parameter explicitly sets the label as "ISBN" (otherwise, it would default to "Isbn"). We also set the parameter `unique` as `true` to ensure all books have a unique ISBN (the unique parameter makes the field value globally unique in a table). Unlike for the `isbn` (and the genre name), the `title` is not set to be unique, because it is possible for different books to have the same name. The model uses `TextField` for the `summary`, because this text may need to be quite long. ```python class Book(models.Model): """Model representing a book (but not a specific copy of a book).""" title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.RESTRICT, null=True) # Foreign Key used because book can only have one author, but authors can have multiple books. # Author as a string rather than object because it hasn't been declared yet in file. summary = models.TextField( max_length=1000, help_text="Enter a brief description of the book") isbn = models.CharField('ISBN', max_length=13, unique=True, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn' '">ISBN number</a>') # ManyToManyField used because genre can contain many books. Books can cover many genres. # Genre class has already been defined so we can specify the object above. genre = models.ManyToManyField( Genre, help_text="Select a genre for this book") def \_\_str\_\_(self): """String for representing the Model object.""" return self.title def get\_absolute\_url(self): """Returns the URL to access a detail record for this book.""" return reverse('book-detail', args=[str(self.id)]) ``` The genre is a `ManyToManyField`, so that a book can have multiple genres and a genre can have many books. The author is declared as `ForeignKey`, so each book will only have one author, but an author may have many books (in practice a book might have multiple authors, but not in this implementation!) In both field types the related model class is declared as the first unnamed parameter using either the model class or a string containing the name of the related model. You must use the name of the model as a string if the associated class has not yet been defined in this file before it is referenced! The other parameters of interest in the `author` field are `null=True`, which allows the database to store a `Null` value if no author is selected, and `on_delete=models.RESTRICT`, which will prevent the book's associated author being deleted if it is referenced by any book. **Warning:** By default `on_delete=models.CASCADE`, which means that if the author was deleted, this book would be deleted too! We use `RESTRICT` here, but we could also use `PROTECT` to prevent the author being deleted while any book uses it or `SET_NULL` to set the book's author to `Null` if the record is deleted. The model also defines `__str__()`, using the book's `title` field to represent a `Book` record. The final method, `get_absolute_url()` returns a URL that can be used to access a detail record for this model (we will have to define a URL mapping that has the name `book-detail`, and define an associated view and template). ### BookInstance model Next, copy the `BookInstance` model (shown below) under the other models. The `BookInstance` represents a specific copy of a book that someone might borrow, and includes information about whether the copy is available or on what date it is expected back, "imprint" or version details, and a unique id for the book in the library. Some of the fields and methods will now be familiar. The model uses: * `ForeignKey` to identify the associated `Book` (each book can have many copies, but a copy can only have one `Book`). The key specifies `on_delete=models.RESTRICT` to ensure that the `Book` cannot be deleted while referenced by a `BookInstance`. * `CharField` to represent the imprint (specific release) of the book. ```python import uuid # Required for unique book instances class BookInstance(models.Model): """Model representing a specific copy of a book (i.e. that can be borrowed from the library).""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular book across whole library") book = models.ForeignKey('Book', on_delete=models.RESTRICT, null=True) imprint = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) status = models.CharField( max_length=1, choices=LOAN_STATUS, blank=True, default='m', help_text='Book availability', ) class Meta: ordering = ['due\_back'] def \_\_str\_\_(self): """String for representing the Model object.""" return f'{self.id} ({self.book.title})' ``` We additionally declare a few new types of field: * `UUIDField` is used for the `id` field to set it as the `primary_key` for this model. This type of field allocates a globally unique value for each instance (one for every book you can find in the library). * `DateField` is used for the `due_back` date (at which the book is expected to become available after being borrowed or in maintenance). This value can be `blank` or `null` (needed for when the book is available). The model metadata (`Class Meta`) uses this field to order records when they are returned in a query. * `status` is a `CharField` that defines a choice/selection list. As you can see, we define a tuple containing tuples of key-value pairs and pass it to the choices argument. The value in a key/value pair is a display value that a user can select, while the keys are the values that are actually saved if the option is selected. We've also set a default value of 'm' (maintenance) as books will initially be created unavailable before they are stocked on the shelves. The method `__str__()` represents the `BookInstance` object using a combination of its unique id and the associated `Book`'s title. **Note:** A little Python: * Starting with Python 3.6, you can use the string interpolation syntax (also known as f-strings): `f'{self.id} ({self.book.title})'`. * In older versions of this tutorial, we were using a formatted string syntax, which is also a valid way of formatting strings in Python (e.g. `'{0} ({1})'.format(self.id,self.book.title)`). ### Author model Copy the `Author` model (shown below) underneath the existing code in **models.py**. ```python class Author(models.Model): """Model representing an author.""" first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('Died', null=True, blank=True) class Meta: ordering = ['last\_name', 'first\_name'] def get\_absolute\_url(self): """Returns the URL to access a particular author instance.""" return reverse('author-detail', args=[str(self.id)]) def \_\_str\_\_(self): """String for representing the Model object.""" return f'{self.last\_name}, {self.first\_name}' ``` All of the fields/methods should now be familiar. The model defines an author as having a first name, last name, and dates of birth and death (both optional). It specifies that by default the `__str__()` returns the name in *last name*, *firstname* order. The `get_absolute_url()` method reverses the `author-detail` URL mapping to get the URL for displaying an individual author. Re-run the database migrations ------------------------------ All your models have now been created. Now re-run your database migrations to add them to your database. ```bash python3 manage.py makemigrations python3 manage.py migrate ``` Language model — challenge -------------------------- Imagine a local benefactor donates a number of new books written in another language (say, Farsi). The challenge is to work out how these would be best represented in our library website, and then to add them to the models. Some things to consider: * Should "language" be associated with a `Book`, `BookInstance`, or some other object? * Should the different languages be represented using model, a free text field, or a hard-coded selection list? After you've decided, add the field. You can see what we decided on GitHub here. Don't forget that after a change to your model, you should again re-run your database migrations to add the changes. ```bash python3 manage.py makemigrations python3 manage.py migrate ``` Summary ------- In this article we've learned how models are defined, and then used this information to design and implement appropriate models for the *LocalLibrary* website. At this point we'll divert briefly from creating the site, and check out the *Django Administration site*. This site will allow us to add some data to the library, which we can then display using our (yet to be created) views and templates. See also -------- * Writing your first Django app, part 2 (Django docs) * Making queries (Django Docs) * QuerySet API Reference (Django Docs) * Previous * Overview: Django * Next
Django Tutorial Part 6: Generic list and detail views - Learn web development
Django Tutorial Part 6: Generic list and detail views ===================================================== * Previous * Overview: Django * Next This tutorial extends our LocalLibrary website, adding list and detail pages for books and authors. Here we'll learn about generic class-based views, and show how they can reduce the amount of code you have to write for common use cases. We'll also go into URL handling in greater detail, showing how to perform basic pattern matching. | | | | --- | --- | | Prerequisites: | Complete all previous tutorial topics, including Django Tutorial Part 5: Creating our home page. | | Objective: | To understand where and how to use generic class-based views, and how to extract patterns from URLs and pass the information to views. | Overview -------- In this tutorial we're going to complete the first version of the LocalLibrary website by adding list and detail pages for books and authors (or to be more precise, we'll show you how to implement the book pages, and get you to create the author pages yourself!) The process is similar to creating the index page, which we showed in the previous tutorial. We'll still need to create URL maps, views, and templates. The main difference is that for the detail pages, we'll have the additional challenge of extracting information from patterns in the URL and passing it to the view. For these pages, we're going to demonstrate a completely different type of view: generic class-based list and detail views. These can significantly reduce the amount of view code needed, making them easier to write and maintain. The final part of the tutorial will demonstrate how to paginate your data when using generic class-based list views. Book list page -------------- The book list page will display a list of all the available book records in the page, accessed using the URL: `catalog/books/`. The page will display a title and author for each record, with the title being a hyperlink to the associated book detail page. The page will have the same structure and navigation as all other pages in the site, and we can, therefore, extend the base template (**base\_generic.html**) we created in the previous tutorial. ### URL mapping Open **/catalog/urls.py** and copy in the line setting the path for `'books/'`, as shown below. Just as for the index page, this `path()` function defines a pattern to match against the URL (**'books/'**), a view function that will be called if the URL matches (`views.BookListView.as_view()`), and a name for this particular mapping. ```python urlpatterns = [ path('', views.index, name='index'), path('books/', views.BookListView.as_view(), name='books'), ] ``` As discussed in the previous tutorial the URL must already have matched `/catalog`, so the view will actually be called for the URL: `/catalog/books/`. The view function has a different format than before — that's because this view will actually be implemented as a class. We will be inheriting from an existing generic view function that already does most of what we want this view function to do, rather than writing our own from scratch. For Django class-based views we access an appropriate view function by calling the class method `as_view()`. This does all the work of creating an instance of the class, and making sure that the right handler methods are called for incoming HTTP requests. ### View (class-based) We could quite easily write the book list view as a regular function (just like our previous index view), which would query the database for all books, and then call `render()` to pass the list to a specified template. Instead, however, we're going to use a class-based generic list view (`ListView`) — a class that inherits from an existing view. Because the generic view already implements most of the functionality we need and follows Django best-practice, we will be able to create a more robust list view with less code, less repetition, and ultimately less maintenance. Open **catalog/views.py**, and copy the following code into the bottom of the file: ```python from django.views import generic class BookListView(generic.ListView): model = Book ``` That's it! The generic view will query the database to get all records for the specified model (`Book`) then render a template located at **/locallibrary/catalog/templates/catalog/book\_list.html** (which we will create below). Within the template you can access the list of books with the template variable named `object_list` OR `book_list` (i.e. generically "`<the model name>_list`"). **Note:** This awkward path for the template location isn't a misprint — the generic views look for templates in `/application_name/the_model_name_list.html` (`catalog/book_list.html` in this case) inside the application's `/application_name/templates/` directory (`/catalog/templates/)`. You can add attributes to change the default behavior above. For example, you can specify another template file if you need to have multiple views that use this same model, or you might want to use a different template variable name if `book_list` is not intuitive for your particular template use-case. Possibly the most useful variation is to change/filter the subset of results that are returned — so instead of listing all books you might list top 5 books that were read by other users. ```python class BookListView(generic.ListView): model = Book context_object_name = 'book\_list' # your own name for the list as a template variable queryset = Book.objects.filter(title__icontains='war')[:5] # Get 5 books containing the title war template_name = 'books/my\_arbitrary\_template\_name\_list.html' # Specify your own template name/location ``` #### Overriding methods in class-based views While we don't need to do so here, you can also override some of the class methods. For example, we can override the `get_queryset()` method to change the list of records returned. This is more flexible than just setting the `queryset` attribute as we did in the preceding code fragment (though there is no real benefit in this case): ```python class BookListView(generic.ListView): model = Book def get\_queryset(self): return Book.objects.filter(title__icontains='war')[:5] # Get 5 books containing the title war ``` We might also override `get_context_data()` in order to pass additional context variables to the template (e.g. the list of books is passed by default). The fragment below shows how to add a variable named "`some_data`" to the context (it would then be available as a template variable). ```python class BookListView(generic.ListView): model = Book def get\_context\_data(self, \*\*kwargs): # Call the base implementation first to get the context context = super(BookListView, self).get_context_data(\*\*kwargs) # Create any data and add it to the context context['some\_data'] = 'This is just some data' return context ``` When doing this it is important to follow the pattern used above: * First get the existing context from our superclass. * Then add your new context information. * Then return the new (updated) context. **Note:** Check out Built-in class-based generic views (Django docs) for many more examples of what you can do. ### Creating the List View template Create the HTML file **/locallibrary/catalog/templates/catalog/book\_list.html** and copy in the text below. As discussed above, this is the default template file expected by the generic class-based list view (for a model named `Book` in an application named `catalog`). Templates for generic views are just like any other templates (although of course the context/information passed to the template may differ). As with our *index* template, we extend our base template in the first line and then replace the block named `content`. ```django {% extends "base\_generic.html" %} {% block content %} <h1>Book List</h1> {% if book\_list %} <ul> {% for book in book\_list %} <li> <a href="{{ book.get\_absolute\_url }}">{{ book.title }}</a> ({{book.author}}) </li> {% endfor %} </ul> {% else %} <p>There are no books in the library.</p> {% endif %} {% endblock %} ``` The view passes the context (list of books) by default as `object_list` and `book_list` aliases; either will work. #### Conditional execution We use the `if`, `else`, and `endif` template tags to check whether the `book_list` has been defined and is not empty. If `book_list` is empty, then the `else` clause displays text explaining that there are no books to list. If `book_list` is not empty, then we iterate through the list of books. ```django {% if book\_list %} <!-- code here to list the books --> {% else %} <p>There are no books in the library.</p> {% endif %} ``` The condition above only checks for one case, but you can test on additional conditions using the `elif` template tag (e.g. `{% elif var2 %}`). For more information about conditional operators see: if, ifequal/ifnotequal, and ifchanged in Built-in template tags and filters (Django Docs). #### For loops The template uses the for and `endfor` template tags to loop through the book list, as shown below. Each iteration populates the `book` template variable with information for the current list item. ```django {% for book in book\_list %} <li><!-- code here get information from each book item --></li> {% endfor %} ``` You might also use the `{% empty %}` template tag to define what happens if the book list is empty (although our template chooses to use a conditional instead): ```django <ul> {% for book in book\_list %} <li><!-- code here get information from each book item --></li> {% empty %} <p>There are no books in the library.</p> {% endfor %} </ul> ``` While not used here, within the loop Django will also create other variables that you can use to track the iteration. For example, you can test the `forloop.last` variable to perform conditional processing the last time that the loop is run. #### Accessing variables The code inside the loop creates a list item for each book that shows both the title (as a link to the yet-to-be-created detail view) and the author. ```django <a href="{{ book.get\_absolute\_url }}">{{ book.title }}</a> ({{book.author}}) ``` We access the *fields* of the associated book record using the "dot notation" (e.g. `book.title` and `book.author`), where the text following the `book` item is the field name (as defined in the model). We can also call *functions* in the model from within our template — in this case we call `Book.get_absolute_url()` to get a URL you could use to display the associated detail record. This works provided the function does not have any arguments (there is no way to pass arguments!) **Note:** We have to be a little careful of "side effects" when calling functions in templates. Here we just get a URL to display, but a function can do pretty much anything — we wouldn't want to delete our database (for example) just by rendering our template! #### Update the base template Open the base template (**/locallibrary/catalog/templates/*base\_generic.html***) and insert **{% url 'books' %}** into the URL link for **All books**, as shown below. This will enable the link in all pages (we can successfully put this in place now that we've created the "books" URL mapper). ```django <li><a href="{% url 'index' %}">Home</a></li> <li><a href="{% url 'books' %}">All books</a></li> <li><a href="">All authors</a></li> ``` ### What does it look like? You won't be able to build the book list yet, because we're still missing a dependency — the URL map for the book detail pages, which is needed to create hyperlinks to individual books. We'll show both list and detail views after the next section. Book detail page ---------------- The book detail page will display information about a specific book, accessed using the URL `catalog/book/<id>` (where `<id>` is the primary key for the book). In addition to fields in the `Book` model (author, summary, ISBN, language, and genre), we'll also list the details of the available copies (`BookInstances`) including the status, expected return date, imprint, and id. This will allow our readers to not only learn about the book, but also to confirm whether/when it is available. ### URL mapping Open **/catalog/urls.py** and add the path named '**book-detail**' shown below. This `path()` function defines a pattern, associated generic class-based detail view, and a name. ```python urlpatterns = [ path('', views.index, name='index'), path('books/', views.BookListView.as_view(), name='books'), path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'), ] ``` For the *book-detail* path the URL pattern uses a special syntax to capture the specific id of the book that we want to see. The syntax is very simple: angle brackets define the part of the URL to be captured, enclosing the name of the variable that the view can use to access the captured data. For example, **<something>**, will capture the marked pattern and pass the value to the view as a variable "something". You can optionally precede the variable name with a converter specification that defines the type of data (int, str, slug, uuid, path). In this case we use `'<int:pk>'` to capture the book id, which must be a specially formatted string and pass it to the view as a parameter named `pk` (short for primary key). This is the id that is being used to store the book uniquely in the database, as defined in the Book Model. **Note:** As discussed previously, our matched URL is actually `catalog/book/<digits>` (because we are in the **catalog** application, `/catalog/` is assumed). **Warning:** The generic class-based detail view *expects* to be passed a parameter named **pk**. If you're writing your own function view you can use whatever parameter name you like, or indeed pass the information in an unnamed argument. #### Advanced path matching/regular expression primer **Note:** You won't need this section to complete the tutorial! We provide it because knowing this option is likely to be useful in your Django-centric future. The pattern matching provided by `path()` is simple and useful for the (very common) cases where you just want to capture *any* string or integer. If you need more refined filtering (for example, to filter only strings that have a certain number of characters) then you can use the re\_path() method. This method is used just like `path()` except that it allows you to specify a pattern using a Regular expression. For example, the previous path could have been written as shown below: ```python re_path(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'), ``` *Regular expressions* are an incredibly powerful pattern mapping tool. They are, frankly, quite unintuitive and can be intimidating for beginners. Below is a very short primer! The first thing to know is that regular expressions should usually be declared using the raw string literal syntax (i.e. they are enclosed as shown: **r'<your regular expression text goes here>'**). The main parts of the syntax you will need to know for declaring the pattern matches are: | Symbol | Meaning | | --- | --- | | ^ | Match the beginning of the text | | $ | Match the end of the text | | \d | Match a digit (0, 1, 2, … 9) | | \w | Match a word character, e.g. any upper- or lower-case character in the alphabet, digit or the underscore character (\_) | | + | Match one or more of the preceding character. For example, to match one or more digits you would use `\d+`. To match one or more "a" characters, you could use `a+` | | \* | Match zero or more of the preceding character. For example, to match nothing or a word you could use `\w*` | | ( ) | Capture the part of the pattern inside the parentheses. Any captured values will be passed to the view as unnamed parameters (if multiple patterns are captured, the associated parameters will be supplied in the order that the captures were declared). | | (?P<*name*>...) | Capture the pattern (indicated by ...) as a named variable (in this case "name"). The captured values are passed to the view with the name specified. Your view must therefore declare a parameter with the same name! | | [ ] | Match against one character in the set. For example, [abc] will match on 'a' or 'b' or 'c'. [-\w] will match on the '-' character or any word character. | Most other characters can be taken literally! Let's consider a few real examples of patterns: | Pattern | Description | | --- | --- | | **r'^book/(?P<pk>\d+)$'** | This is the RE used in our URL mapper. It matches a string that has `book/` at the start of the line (**^book/**), then has one or more digits (`\d+`), and then ends (with no non-digit characters before the end of line marker). It also captures all the digits **(?P<pk>\d+)** and passes them to the view in a parameter named 'pk'. **The captured values are always passed as a string!** For example, this would match `book/1234`, and send a variable `pk='1234'` to the view. | | **r'^book/(\d+)$'** | This matches the same URLs as the preceding case. The captured information would be sent as an unnamed argument to the view. | | **r'^book/(?P<stub>[-\w]+)$'** | This matches a string that has `book/` at the start of the line (**^book/**), then has one or more characters that are *either* a '-' or a word character (**[-\w]+**), and then ends. It also captures this set of characters and passes them to the view in a parameter named 'stub'. This is a fairly typical pattern for a "stub". Stubs are URL-friendly word-based primary keys for data. You might use a stub if you wanted your book URL to be more informative. For example `/catalog/book/the-secret-garden` rather than `/catalog/book/33`. | You can capture multiple patterns in the one match, and hence encode lots of different information in a URL. **Note:** As a challenge, consider how you might encode a URL to list all books released in a particular year, month, day, and the RE that could be used to match it. #### Passing additional options in your URL maps One feature that we haven't used here, but which you may find valuable, is that you can pass a dictionary containing additional options to the view (using the third un-named argument to the `path()` function). This approach can be useful if you want to use the same view for multiple resources, and pass data to configure its behavior in each case. For example, given the path shown below, for a request to `/myurl/halibut/` Django will call `views.my_view(request, fish='halibut', my_template_name='some_path')`. ```python path('myurl/<fish>', views.my_view, {'my\_template\_name': 'some\_path'}, name='aurl'), ``` **Note:** Both named captured patterns and dictionary options are passed to the view as *named* arguments. If you use the **same name** for both a capture pattern and a dictionary key, then the dictionary option will be used. ### View (class-based) Open **catalog/views.py**, and copy the following code into the bottom of the file: ```python class BookDetailView(generic.DetailView): model = Book ``` That's it! All you need to do now is create a template called **/locallibrary/catalog/templates/catalog/book\_detail.html**, and the view will pass it the database information for the specific `Book` record extracted by the URL mapper. Within the template you can access the book's details with the template variable named `object` OR `book` (i.e. generically "`the_model_name`"). If you need to, you can change the template used and the name of the context object used to reference the book in the template. You can also override methods to, for example, add additional information to the context. #### What happens if the record doesn't exist? If a requested record does not exist then the generic class-based detail view will raise an `Http404` exception for you automatically — in production, this will automatically display an appropriate "resource not found" page, which you can customize if desired. Just to give you some idea of how this works, the code fragment below demonstrates how you would implement the class-based view as a function if you were **not** using the generic class-based detail view. ```python def book\_detail\_view(request, primary_key): try: book = Book.objects.get(pk=primary_key) except Book.DoesNotExist: raise Http404('Book does not exist') return render(request, 'catalog/book\_detail.html', context={'book': book}) ``` The view first tries to get the specific book record from the model. If this fails the view should raise an `Http404` exception to indicate that the book is "not found". The final step is then, as usual, to call `render()` with the template name and the book data in the `context` parameter (as a dictionary). Another way you could do this if you were not using a generic view would be to call the `get_object_or_404()` function. This is a shortcut to raise an `Http404` exception if the record is not found. ```python from django.shortcuts import get_object_or_404 def book\_detail\_view(request, primary_key): book = get_object_or_404(Book, pk=primary_key) return render(request, 'catalog/book\_detail.html', context={'book': book}) ``` ### Creating the Detail View template Create the HTML file **/locallibrary/catalog/templates/catalog/book\_detail.html** and give it the below content. As discussed above, this is the default template file name expected by the generic class-based *detail* view (for a model named `Book` in an application named `catalog`). ```django {% extends "base\_generic.html" %} {% block content %} <h1>Title: {{ book.title }}</h1> <p><strong>Author:</strong> <a href="">{{ book.author }}</a></p> <!-- author detail link not yet defined --> <p><strong>Summary:</strong> {{ book.summary }}</p> <p><strong>ISBN:</strong> {{ book.isbn }}</p> <p><strong>Language:</strong> {{ book.language }}</p> <p><strong>Genre:</strong> {{ book.genre.all|join:", " }}</p> <div style="margin-left:20px;margin-top:20px"> <h4>Copies</h4> {% for copy in book.bookinstance\_set.all %} <hr /> <p class="{% if copy.status == 'a' %}text-success{% elif copy.status == 'm' %}text-danger{% else %}text-warning{% endif %}"> {{ copy.get\_status\_display }} </p> {% if copy.status != 'a' %} <p><strong>Due to be returned:</strong> {{ copy.due\_back }}</p> {% endif %} <p><strong>Imprint:</strong> {{ copy.imprint }}</p> <p class="text-muted"><strong>Id:</strong> {{ copy.id }}</p> {% endfor %} </div> {% endblock %} ``` **Note:** The author link in the template above has an empty URL because we've not yet created an author detail page to link to. Once the detail page exists we can get its URL with either of these two approaches: * Use the `url` template tag to reverse the 'author-detail' URL (defined in the URL mapper), passing it the author instance for the book: ```django <a href="{% url 'author-detail' book.author.pk %}">{{ book.author }}</a> ``` * Call the author model's `get_absolute_url()` method (this performs the same reversing operation): ```django <a href="{{ book.author.get\_absolute\_url }}">{{ book.author }}</a> ``` While both methods effectively do the same thing, `get_absolute_url()` is preferred because it helps you write more consistent and maintainable code (any changes only need to be done in one place: the author model). Though a little larger, almost everything in this template has been described previously: * We extend our base template and override the "content" block. * We use conditional processing to determine whether or not to display specific content. * We use `for` loops to loop through lists of objects. * We access the context fields using the dot notation (because we've used the detail generic view, the context is named `book`; we could also use "`object`") The first interesting thing we haven't seen before is the function `book.bookinstance_set.all()`. This method is "automagically" constructed by Django in order to return the set of `BookInstance` records associated with a particular `Book`. ```django {% for copy in book.bookinstance\_set.all %} <!-- code to iterate across each copy/instance of a book --> {% endfor %} ``` This method is needed because you declare a `ForeignKey` (one-to many) field only in the "many" side of the relationship (the `BookInstance`). Since you don't do anything to declare the relationship in the other ("one") model, it (the `Book`) doesn't have any field to get the set of associated records. To overcome this problem, Django constructs an appropriately named "reverse lookup" function that you can use. The name of the function is constructed by lower-casing the model name where the `ForeignKey` was declared, followed by `_set` (i.e. so the function created in `Book` is `bookinstance_set()`). **Note:** Here we use `all()` to get all records (the default). While you can use the `filter()` method to get a subset of records in code, you can't do this directly in templates because you can't specify arguments to functions. Beware also that if you don't define an order (on your class-based view or model), you will also see errors from the development server like this one: ``` [29/May/2017 18:37:53] "GET /catalog/books/?page=1 HTTP/1.1" 200 1637 /foo/local_library/venv/lib/python3.5/site-packages/django/views/generic/list.py:99: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <QuerySet [<Author: Ortiz, David>, <Author: H. McRaven, William>, <Author: Leigh, Melinda>]> allow_empty_first_page=allow_empty_first_page, **kwargs) ``` That happens because the paginator object expects to see some ORDER BY being executed on your underlying database. Without it, it can't be sure the records being returned are actually in the right order! This tutorial hasn't covered **Pagination** (yet!), but since you can't use `sort_by()` and pass a parameter (the same with `filter()` described above) you will have to choose between three choices: 1. Add a `ordering` inside a `class Meta` declaration on your model. 2. Add a `queryset` attribute in your custom class-based view, specifying an `order_by()`. 3. Adding a `get_queryset` method to your custom class-based view and also specify the `order_by()`. If you decide to go with a `class Meta` for the `Author` model (probably not as flexible as customizing the class-based view, but easy enough), you will end up with something like this: ```python class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('Died', null=True, blank=True) def get\_absolute\_url(self): return reverse('author-detail', args=[str(self.id)]) def \_\_str\_\_(self): return f'{self.last\_name}, {self.first\_name}' class Meta: ordering = ['last\_name'] ``` Of course, the field doesn't need to be `last_name`: it could be any other. Last but not least, you should sort by an attribute/column that actually has an index (unique or not) on your database to avoid performance issues. Of course, this will not be necessary here (we are probably getting ahead of ourselves with so few books and users), but it is something worth keeping in mind for future projects. The second interesting (and non-obvious) thing in the template is where we display the status text for each book instance ("available", "maintenance", etc.). Astute readers will note that the method `BookInstance.get_status_display()` that we use to get the status text does not appear elsewhere in the code. ```django <p class="{% if copy.status == 'a' %}text-success{% elif copy.status == 'm' %}text-danger{% else %}text-warning{% endif %}"> {{ copy.get\_status\_display }} </p> ``` This function is automatically created because `BookInstance.status` is a choices field. Django automatically creates a method `get_FOO_display()` for every choices field "`Foo`" in a model, which can be used to get the current value of the field. What does it look like? ----------------------- At this point, we should have created everything needed to display both the book list and book detail pages. Run the server (`python3 manage.py runserver`) and open your browser to `http://127.0.0.1:8000/`. **Warning:** Don't click any author or author detail links yet — you'll create those in the challenge! Click the **All books** link to display the list of books. ![Book List Page](/en-US/docs/Learn/Server-side/Django/Generic_views/book_list_page_no_pagination.png) Then click a link to one of your books. If everything is set up correctly, you should see something like the following screenshot. ![Book Detail Page](/en-US/docs/Learn/Server-side/Django/Generic_views/book_detail_page_no_pagination.png) Pagination ---------- If you've just got a few records, our book list page will look fine. However, as you get into the tens or hundreds of records the page will take progressively longer to load (and have far too much content to browse sensibly). The solution to this problem is to add pagination to your list views, reducing the number of items displayed on each page. Django has excellent inbuilt support for pagination. Even better, this is built into the generic class-based list views so you don't have to do very much to enable it! ### Views Open **catalog/views.py**, and add the `paginate_by` line shown below. ```python class BookListView(generic.ListView): model = Book paginate_by = 10 ``` With this addition, as soon as you have more than 10 records the view will start paginating the data it sends to the template. The different pages are accessed using GET parameters — to access page 2 you would use the URL `/catalog/books/?page=2`. ### Templates Now that the data is paginated, we need to add support to the template to scroll through the results set. Because we might want paginate all list views, we'll add this to the base template. Open **/locallibrary/catalog/templates/*base\_generic.html*** and find the "content block" (as shown below). ```django {% block content %}{% endblock %} ``` Copy in the following pagination block immediately following the `{% endblock %}`. The code first checks if pagination is enabled on the current page. If so, it adds *next* and *previous* links as appropriate (and the current page number). ```django {% block pagination %} {% if is\_paginated %} <div class="pagination"> <span class="page-links"> {% if page\_obj.has\_previous %} <a href="{{ request.path }}?page={{ page\_obj.previous\_page\_number }}">previous</a> {% endif %} <span class="page-current"> Page {{ page\_obj.number }} of {{ page\_obj.paginator.num\_pages }}. </span> {% if page\_obj.has\_next %} <a href="{{ request.path }}?page={{ page\_obj.next\_page\_number }}">next</a> {% endif %} </span> </div> {% endif %} {% endblock %} ``` The `page_obj` is a Paginator object that will exist if pagination is being used on the current page. It allows you to get all the information about the current page, previous pages, how many pages there are, etc. We use `{{ request.path }}` to get the current page URL for creating the pagination links. This is useful because it is independent of the object that we're paginating. That's it! ### What does it look like? The screenshot below shows what the pagination looks like — if you haven't entered more than 10 titles into your database, then you can test it more easily by lowering the number specified in the `paginate_by` line in your **catalog/views.py** file. To get the below result we changed it to `paginate_by = 2`. The pagination links are displayed on the bottom, with next/previous links being displayed depending on which page you're on. ![Book List Page - paginated](/en-US/docs/Learn/Server-side/Django/Generic_views/book_list_paginated.png) Challenge yourself ------------------ The challenge in this article is to create the author detail and list views required to complete the project. These should be made available at the following URLs: * `catalog/authors/` — The list of all authors. * `catalog/author/<id>` — The detail view for the specific author with a primary key field named `<id>` The code required for the URL mappers and the views should be virtually identical to the `Book` list and detail views we created above. The templates will be different but will share similar behavior. **Note:** * Once you've created the URL mapper for the author list page you will also need to update the **All authors** link in the base template. Follow the same process as we did when we updated the **All books** link. * Once you've created the URL mapper for the author detail page, you should also update the book detail view template (**/locallibrary/catalog/templates/catalog/book\_detail.html**) so that the author link points to your new author detail page (rather than being an empty URL). The recommended way to do this is to call `get_absolute_url()` on the author model as shown below. ```django <p> <strong>Author:</strong> <a href="{{ book.author.get\_absolute\_url }}">{{ book.author }}</a> </p> ``` When you are finished, your pages should look something like the screenshots below. ![Author List Page](/en-US/docs/Learn/Server-side/Django/Generic_views/author_list_page_no_pagination.png) ![Author Detail Page](/en-US/docs/Learn/Server-side/Django/Generic_views/author_detail_page_no_pagination.png) Summary ------- Congratulations, our basic library functionality is now complete! In this article, we've learned how to use the generic class-based list and detail views and used them to create pages to view our books and authors. Along the way we've learned about pattern matching with regular expressions, and how you can pass data from URLs to your views. We've also learned a few more tricks for using templates. Last of all we've shown how to paginate list views so that our lists are manageable even when we have many records. In our next articles, we'll extend this library to support user accounts, and thereby demonstrate user authentication, permissions, sessions, and forms. See also -------- * Built-in class-based generic views (Django docs) * Generic display views (Django docs) * Introduction to class-based views (Django docs) * Built-in template tags and filters (Django docs) * Pagination (Django docs) * Making queries > Related objects (Django docs) * Previous * Overview: Django * Next
Django Tutorial Part 9: Working with forms - Learn web development
Django Tutorial Part 9: Working with forms ========================================== * Previous * Overview: Django * Next In this tutorial, we'll show you how to work with HTML Forms in Django, and, in particular, the easiest way to write forms to create, update, and delete model instances. As part of this demonstration, we'll extend the LocalLibrary website so that librarians can renew books, and create, update, and delete authors using our own forms (rather than using the admin application). | | | | --- | --- | | Prerequisites: | Complete all previous tutorial topics, including Django Tutorial Part 8: User authentication and permissions. | | Objective: | To understand how to write forms to get information from users and update the database. To understand how the generic class-based editing views can vastly simplify creating forms for working with a single model. | Overview -------- An HTML Form is a group of one or more fields/widgets on a web page, which can be used to collect information from users for submission to a server. Forms are a flexible mechanism for collecting user input because there are suitable widgets for entering many different types of data, including text boxes, checkboxes, radio buttons, date pickers and so on. Forms are also a relatively secure way of sharing data with the server, as they allow us to send data in `POST` requests with cross-site request forgery protection. While we haven't created any forms in this tutorial so far, we've already encountered them in the Django Admin site — for example, the screenshot below shows a form for editing one of our Book models, comprised of a number of selection lists and text editors. ![Admin Site - Book Add](/en-US/docs/Learn/Server-side/Django/Forms/admin_book_add.png) Working with forms can be complicated! Developers need to write HTML for the form, validate and properly sanitize entered data on the server (and possibly also in the browser), repost the form with error messages to inform users of any invalid fields, handle the data when it has successfully been submitted, and finally respond to the user in some way to indicate success. *Django Forms* take a lot of the work out of all these steps, by providing a framework that lets you define forms and their fields programmatically, and then use these objects to both generate the form HTML code and handle much of the validation and user interaction. In this tutorial, we're going to show you a few of the ways you can create and work with forms, and in particular, how the generic editing views can significantly reduce the amount of work you need to do to create forms to manipulate your models. Along the way, we'll extend our *LocalLibrary* application by adding a form to allow librarians to renew library books, and we'll create pages to create, edit and delete books and authors (reproducing a basic version of the form shown above for editing books). HTML Forms ---------- First, a brief overview of HTML Forms. Consider a simple HTML form, with a single text field for entering the name of some "team", and its associated label: ![Simple name field example in HTML form](/en-US/docs/Learn/Server-side/Django/Forms/form_example_name_field.png) The form is defined in HTML as a collection of elements inside `<form>…</form>` tags, containing at least one `input` element of `type="submit"`. ```html <form action="/team\_name\_url/" method="post"> <label for="team\_name">Enter name: </label> <input id="team\_name" type="text" name="name\_field" value="Default name for team." /> <input type="submit" value="OK" /> </form> ``` While here we just have one text field for entering the team name, a form *may* have any number of other input elements and their associated labels. The field's `type` attribute defines what sort of widget will be displayed. The `name` and `id` of the field are used to identify the field in JavaScript/CSS/HTML, while `value` defines the initial value for the field when it is first displayed. The matching team label is specified using the `label` tag (see "Enter name" above), with a `for` field containing the `id` value of the associated `input`. The `submit` input will be displayed as a button by default. This can be pressed to upload the data in all the other input elements in the form to the server (in this case, just the `team_name` field). The form attributes define the HTTP `method` used to send the data and the destination of the data on the server (`action`): * `action`: The resource/URL where data is to be sent for processing when the form is submitted. If this is not set (or set to an empty string), then the form will be submitted back to the current page URL. * `method`: The HTTP method used to send the data: *post* or *get*. + The `POST` method should always be used if the data is going to result in a change to the server's database, because it can be made more resistant to cross-site forgery request attacks. + The `GET` method should only be used for forms that don't change user data (for example, a search form). It is recommended for when you want to be able to bookmark or share the URL. The role of the server is first to render the initial form state — either containing blank fields or pre-populated with initial values. After the user presses the submit button, the server will receive the form data with values from the web browser and must validate the information. If the form contains invalid data, the server should display the form again, this time with user-entered data in "valid" fields and messages to describe the problem for the invalid fields. Once the server gets a request with all valid form data, it can perform an appropriate action (such as: saving the data, returning the result of a search, uploading a file, etc.) and then notify the user. As you can imagine, creating the HTML, validating the returned data, re-displaying the entered data with error reports if needed, and performing the desired operation on valid data can all take quite a lot of effort to "get right". Django makes this a lot easier by taking away some of the heavy lifting and repetitive code! Django form handling process ---------------------------- Django's form handling uses all of the same techniques that we learned about in previous tutorials (for displaying information about our models): the view gets a request, performs any actions required including reading data from the models, then generates and returns an HTML page (from a template, into which we pass a *context* containing the data to be displayed). What makes things more complicated is that the server also needs to be able to process data provided by the user, and redisplay the page if there are any errors. A process flowchart of how Django handles form requests is shown below, starting with a request for a page containing a form (shown in green). ![Updated form handling process doc.](/en-US/docs/Learn/Server-side/Django/Forms/form_handling_-_standard.png) Based on the diagram above, the main things that Django's form handling does are: 1. Display the default form the first time it is requested by the user. * The form may contain blank fields if you're creating a new record, or it may be pre-populated with initial values (for example, if you are changing a record, or have useful default initial values). * The form is referred to as *unbound* at this point, because it isn't associated with any user-entered data (though it may have initial values). 2. Receive data from a submit request and bind it to the form. * Binding data to the form means that the user-entered data and any errors are available when we need to redisplay the form. 3. Clean and validate the data. * Cleaning the data performs sanitization of the input fields, such as removing invalid characters that might be used to send malicious content to the server, and converts them into consistent Python types. * Validation checks that the values are appropriate for the field (for example, that they are in the right date range, aren't too short or too long, etc.) 4. If any data is invalid, re-display the form, this time with any user populated values and error messages for the problem fields. 5. If all data is valid, perform required actions (such as save the data, send an email, return the result of a search, upload a file, and so on). 6. Once all actions are complete, redirect the user to another page. Django provides a number of tools and approaches to help you with the tasks detailed above. The most fundamental is the `Form` class, which simplifies both generation of form HTML and data cleaning/validation. In the next section, we describe how forms work using the practical example of a page to allow librarians to renew books. **Note:** Understanding how `Form` is used will help you when we discuss Django's more "high level" form framework classes. Renew-book form using a Form and function view ---------------------------------------------- Next, we're going to add a page to allow librarians to renew borrowed books. To do this we'll create a form that allows users to enter a date value. We'll seed the field with an initial value 3 weeks from the current date (the normal borrowing period), and add some validation to ensure that the librarian can't enter a date in the past or a date too far in the future. When a valid date has been entered, we'll write it to the current record's `BookInstance.due_back` field. The example will use a function-based view and a `Form` class. The following sections explain how forms work, and the changes you need to make to our ongoing *LocalLibrary* project. ### Form The `Form` class is the heart of Django's form handling system. It specifies the fields in the form, their layout, display widgets, labels, initial values, valid values, and (once validated) the error messages associated with invalid fields. The class also provides methods for rendering itself in templates using predefined formats (tables, lists, etc.) or for getting the value of any element (enabling fine-grained manual rendering). #### Declaring a Form The declaration syntax for a `Form` is very similar to that for declaring a `Model`, and shares the same field types (and some similar parameters). This makes sense because in both cases we need to ensure that each field handles the right types of data, is constrained to valid data, and has a description for display/documentation. Form data is stored in an application's forms.py file, inside the application directory. Create and open the file **locallibrary/catalog/forms.py**. To create a `Form`, we import the `forms` library, derive from the `Form` class, and declare the form's fields. A very basic form class for our library book renewal form is shown below — add this to your new file: ```python from django import forms class RenewBookForm(forms.Form): renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).") ``` #### Form fields In this case, we have a single `DateField` for entering the renewal date that will render in HTML with a blank value, the default label "*Renewal date:*", and some helpful usage text: "*Enter a date between now and 4 weeks (default 3 weeks).*" As none of the other optional arguments are specified the field will accept dates using the input\_formats: YYYY-MM-DD (2016-11-06), MM/DD/YYYY (02/26/2016), MM/DD/YY (10/25/16), and will be rendered using the default widget: DateInput. There are many other types of form fields, which you will largely recognize from their similarity to the equivalent model field classes: * `BooleanField` * `CharField` * `ChoiceField` * `TypedChoiceField` * `DateField` * `DateTimeField` * `DecimalField` * `DurationField` * `EmailField` * `FileField` * `FilePathField` * `FloatField` * `ImageField` * `IntegerField` * `GenericIPAddressField` * `MultipleChoiceField` * `TypedMultipleChoiceField` * `NullBooleanField` * `RegexField` * `SlugField` * `TimeField` * `URLField` * `UUIDField` * `ComboField` * `MultiValueField` * `SplitDateTimeField` * `ModelMultipleChoiceField` * `ModelChoiceField` The arguments that are common to most fields are listed below (these have sensible default values): * `required`: If `True`, the field may not be left blank or given a `None` value. Fields are required by default, so you would set `required=False` to allow blank values in the form. * `label`: The label to use when rendering the field in HTML. If a label is not specified, Django will create one from the field name by capitalizing the first letter and replacing underscores with spaces (e.g. *Renewal date*). * `label_suffix`: By default, a colon is displayed after the label (e.g. Renewal date​**:**). This argument allows you to specify a different suffix containing other character(s). * `initial`: The initial value for the field when the form is displayed. * `widget`: The display widget to use. * `help_text` (as seen in the example above): Additional text that can be displayed in forms to explain how to use the field. * `error_messages`: A list of error messages for the field. You can override these with your own messages if needed. * `validators`: A list of functions that will be called on the field when it is validated. * `localize`: Enables the localization of form data input (see link for more information). * `disabled`: The field is displayed but its value cannot be edited if this is `True`. The default is `False`. #### Validation Django provides numerous places where you can validate your data. The easiest way to validate a single field is to override the method `clean_<fieldname>()` for the field you want to check. So for example, we can validate that entered `renewal_date` values are between now and 4 weeks by implementing `clean_renewal_date()` as shown below. Update your forms.py file so it looks like this: ```python import datetime from django import forms from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ class RenewBookForm(forms.Form): renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).") def clean\_renewal\_date(self): data = self.cleaned_data['renewal\_date'] # Check if a date is not in the past. if data < datetime.date.today(): raise ValidationError(_('Invalid date - renewal in past')) # Check if a date is in the allowed range (+4 weeks from today). if data > datetime.date.today() + datetime.timedelta(weeks=4): raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead')) # Remember to always return the cleaned data. return data ``` There are two important things to note. The first is that we get our data using `self.cleaned_data['renewal_date']` and that we return this data whether or not we change it at the end of the function. This step gets us the data "cleaned" and sanitized of potentially unsafe input using the default validators, and converted into the correct standard type for the data (in this case a Python `datetime.datetime` object). The second point is that if a value falls outside our range we raise a `ValidationError`, specifying the error text that we want to display in the form if an invalid value is entered. The example above also wraps this text in one of Django's translation functions, `gettext_lazy()` (imported as `_()`), which is good practice if you want to translate your site later. **Note:** There are numerous other methods and examples for validating forms in Form and field validation (Django docs). For example, in cases where you have multiple fields that depend on each other, you can override the Form.clean() function and again raise a `ValidationError`. That's all we need for the form in this example! ### URL configuration Before we create our view, let's add a URL configuration for the *renew-books* page. Copy the following configuration to the bottom of **locallibrary/catalog/urls.py**: ```python urlpatterns += [ path('book/<uuid:pk>/renew/', views.renew_book_librarian, name='renew-book-librarian'), ] ``` The URL configuration will redirect URLs with the format **/catalog/book/*<bookinstance\_id>*/renew/** to the function named `renew_book_librarian()` in **views.py**, and send the `BookInstance` id as the parameter named `pk`. The pattern only matches if `pk` is a correctly formatted `uuid`. **Note:** We can name our captured URL data "`pk`" anything we like, because we have complete control over the view function (we're not using a generic detail view class that expects parameters with a certain name). However, `pk` short for "primary key", is a reasonable convention to use! ### View As discussed in the Django form handling process above, the view has to render the default form when it is first called and then either re-render it with error messages if the data is invalid, or process the data and redirect to a new page if the data is valid. In order to perform these different actions, the view has to be able to know whether it is being called for the first time to render the default form, or a subsequent time to validate data. For forms that use a `POST` request to submit information to the server, the most common pattern is for the view to test against the `POST` request type (`if request.method == 'POST':`) to identify form validation requests and `GET` (using an `else` condition) to identify the initial form creation request. If you want to submit your data using a `GET` request, then a typical approach for identifying whether this is the first or subsequent view invocation is to read the form data (e.g. to read a hidden value in the form). The book renewal process will be writing to our database, so, by convention, we use the `POST` request approach. The code fragment below shows the (very standard) pattern for this sort of function view. ```python import datetime from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from django.urls import reverse from catalog.forms import RenewBookForm def renew\_book\_librarian(request, pk): book_instance = get_object_or_404(BookInstance, pk=pk) # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = RenewBookForm(request.POST) # Check if the form is valid: if form.is_valid(): # process the data in form.cleaned\_data as required (here we just write it to the model due\_back field) book_instance.due_back = form.cleaned_data['renewal\_date'] book_instance.save() # redirect to a new URL: return HttpResponseRedirect(reverse('all-borrowed')) # If this is a GET (or any other method) create the default form. else: proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3) form = RenewBookForm(initial={'renewal\_date': proposed_renewal_date}) context = { 'form': form, 'book\_instance': book_instance, } return render(request, 'catalog/book\_renew\_librarian.html', context) ``` First, we import our form (`RenewBookForm`) and a number of other useful objects/methods used in the body of the view function: * `get_object_or_404()`: Returns a specified object from a model based on its primary key value, and raises an `Http404` exception (not found) if the record does not exist. * `HttpResponseRedirect`: This creates a redirect to a specified URL (HTTP status code 302). * `reverse()`: This generates a URL from a URL configuration name and a set of arguments. It is the Python equivalent of the `url` tag that we've been using in our templates. * `datetime`: A Python library for manipulating dates and times. In the view, we first use the `pk` argument in `get_object_or_404()` to get the current `BookInstance` (if this does not exist, the view will immediately exit and the page will display a "not found" error). If this is *not* a `POST` request (handled by the `else` clause) then we create the default form passing in an `initial` value for the `renewal_date` field, 3 weeks from the current date. ```python book_instance = get_object_or_404(BookInstance, pk=pk) # If this is a GET (or any other method) create the default form else: proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3) form = RenewBookForm(initial={'renewal\_date': proposed_renewal_date}) context = { 'form': form, 'book\_instance': book_instance, } return render(request, 'catalog/book\_renew\_librarian.html', context) ``` After creating the form, we call `render()` to create the HTML page, specifying the template and a context that contains our form. In this case, the context also contains our `BookInstance`, which we'll use in the template to provide information about the book we're renewing. However, if this is a `POST` request, then we create our `form` object and populate it with data from the request. This process is called "binding" and allows us to validate the form. We then check if the form is valid, which runs all the validation code on all of the fields — including both the generic code to check that our date field is actually a valid date and our specific form's `clean_renewal_date()` function to check the date is in the right range. ```python book_instance = get_object_or_404(BookInstance, pk=pk) # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = RenewBookForm(request.POST) # Check if the form is valid: if form.is_valid(): # process the data in form.cleaned\_data as required (here we just write it to the model due\_back field) book_instance.due_back = form.cleaned_data['renewal\_date'] book_instance.save() # redirect to a new URL: return HttpResponseRedirect(reverse('all-borrowed')) context = { 'form': form, 'book\_instance': book_instance, } return render(request, 'catalog/book\_renew\_librarian.html', context) ``` If the form is not valid we call `render()` again, but this time the form value passed in the context will include error messages. If the form is valid, then we can start to use the data, accessing it through the `form.cleaned_data` attribute (e.g. `data = form.cleaned_data['renewal_date']`). Here, we just save the data into the `due_back` value of the associated `BookInstance` object. **Warning:** While you can also access the form data directly through the request (for example, `request.POST['renewal_date']` or `request.GET['renewal_date']` if using a GET request), this is NOT recommended. The cleaned data is sanitized, validated, and converted into Python-friendly types. The final step in the form-handling part of the view is to redirect to another page, usually a "success" page. In this case, we use `HttpResponseRedirect` and `reverse()` to redirect to the view named `'all-borrowed'` (this was created as the "challenge" in Django Tutorial Part 8: User authentication and permissions). If you didn't create that page consider redirecting to the home page at URL '`/`'). That's everything needed for the form handling itself, but we still need to restrict access to the view to just logged-in librarians who have permission to renew books. We use `@login_required` to require that the user is logged in, and the `@permission_required` function decorator with our existing `can_mark_returned` permission to allow access (decorators are processed in order). Note that we probably should have created a new permission setting in `BookInstance` ("`can_renew`"), but we will reuse the existing one to keep the example simple. The final view is therefore as shown below. Please copy this into the bottom of **locallibrary/catalog/views.py**. ```python import datetime from django.contrib.auth.decorators import login_required, permission_required from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect from django.urls import reverse from catalog.forms import RenewBookForm @login\_required @permission\_required('catalog.can\_mark\_returned', raise_exception=True) def renew\_book\_librarian(request, pk): """View function for renewing a specific BookInstance by librarian.""" book_instance = get_object_or_404(BookInstance, pk=pk) # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = RenewBookForm(request.POST) # Check if the form is valid: if form.is_valid(): # process the data in form.cleaned\_data as required (here we just write it to the model due\_back field) book_instance.due_back = form.cleaned_data['renewal\_date'] book_instance.save() # redirect to a new URL: return HttpResponseRedirect(reverse('all-borrowed')) # If this is a GET (or any other method) create the default form. else: proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3) form = RenewBookForm(initial={'renewal\_date': proposed_renewal_date}) context = { 'form': form, 'book\_instance': book_instance, } return render(request, 'catalog/book\_renew\_librarian.html', context) ``` ### The template Create the template referenced in the view (**/catalog/templates/catalog/book\_renew\_librarian.html**) and copy the code below into it: ```django {% extends "base\_generic.html" %} {% block content %} <h1>Renew: {{ book\_instance.book.title }}</h1> <p>Borrower: {{ book\_instance.borrower }}</p> <p {% if book\_instance.is\_overdue %} class="text-danger"{% endif %} >Due date: {{ book\_instance.due\_back }}</p> <form action="" method="post"> {% csrf\_token %} <table> {{ form.as\_table }} </table> <input type="submit" value="Submit"> </form> {% endblock %} ``` Most of this will be completely familiar from previous tutorials. We extend the base template and then redefine the content block. We are able to reference `{{ book_instance }}` (and its variables) because it was passed into the context object in the `render()` function, and we use these to list the book title, borrower, and the original due date. The form code is relatively simple. First, we declare the `form` tags, specifying where the form is to be submitted (`action`) and the `method` for submitting the data (in this case an "HTTP `POST`") — if you recall the HTML Forms overview at the top of the page, an empty `action` as shown, means that the form data will be posted back to the current URL of the page (which is what we want). Inside the tags, we define the `submit` input, which a user can press to submit the data. The `{% csrf_token %}` added just inside the form tags is part of Django's cross-site forgery protection. **Note:** Add the `{% csrf_token %}` to every Django template you create that uses `POST` to submit data. This will reduce the chance of forms being hijacked by malicious users. All that's left is the `{{ form }}` template variable, which we passed to the template in the context dictionary. Perhaps unsurprisingly, when used as shown this provides the default rendering of all the form fields, including their labels, widgets, and help text — the rendering is as shown below: ```html <tr> <th><label for="id\_renewal\_date">Renewal date:</label></th> <td> <input id="id\_renewal\_date" name="renewal\_date" type="text" value="2023-11-08" required /> <br /> <span class="helptext"> Enter date between now and 4 weeks (default 3 weeks). </span> </td> </tr> ``` **Note:** It is perhaps not obvious because we only have one field, but, by default, every field is defined in its own table row. This same rendering is provided if you reference the template variable `{{ form.as_table }}`. If you were to enter an invalid date, you'd additionally get a list of the errors rendered on the page (see `errorlist` below). ```html <tr> <th><label for="id\_renewal\_date">Renewal date:</label></th> <td> <ul class="errorlist"> <li>Invalid date - renewal in past</li> </ul> <input id="id\_renewal\_date" name="renewal\_date" type="text" value="2023-11-08" required /> <br /> <span class="helptext"> Enter date between now and 4 weeks (default 3 weeks). </span> </td> </tr> ``` #### Other ways of using form template variable Using `{{ form.as_table }}` as shown above, each field is rendered as a table row. You can also render each field as a list item (using `{{ form.as_ul }}`) or as a paragraph (using `{{ form.as_p }}`). It is also possible to have complete control over the rendering of each part of the form, by indexing its properties using dot notation. So, for example, we can access a number of separate items for our `renewal_date` field: * `{{ form.renewal_date }}:` The whole field. * `{{ form.renewal_date.errors }}`: The list of errors. * `{{ form.renewal_date.id_for_label }}`: The id of the label. * `{{ form.renewal_date.help_text }}`: The field help text. For more examples of how to manually render forms in templates and dynamically loop over template fields, see Working with forms > Rendering fields manually (Django docs). ### Testing the page If you accepted the "challenge" in Django Tutorial Part 8: User authentication and permissions you'll have a view showing all books on loan in the library, which is only visible to library staff. The view might look similar to this: ```django {% extends "base\_generic.html" %} {% block content %} <h1>All Borrowed Books</h1> {% if bookinstance\_list %} <ul> {% for bookinst in bookinstance\_list %} <li class="{% if bookinst.is\_overdue %}text-danger{% endif %}"> <a href="{% url 'book-detail' bookinst.book.pk %}">{{ bookinst.book.title }}</a> ({{ bookinst.due\_back }}) {% if user.is\_staff %}- {{ bookinst.borrower }}{% endif %} </li> {% endfor %} </ul> {% else %} <p>There are no books borrowed.</p> {% endif %} {% endblock %} ``` We can add a link to the book renew page next to each item by appending the following template code to the list item text above. Note that this template code can only run inside the `{% for %}` loop, because that is where the `bookinst` value is defined. ```django {% if perms.catalog.can\_mark\_returned %}- <a href="{% url 'renew-book-librarian' bookinst.id %}">Renew</a>{% endif %} ``` **Note:** Remember that your test login will need to have the permission "`catalog.can_mark_returned`" in order to see the new "Renew" link added above, and to access the linked page (perhaps use your superuser account). You can alternatively manually construct a test URL like this — `http://127.0.0.1:8000/catalog/book/<bookinstance_id>/renew/` (a valid `bookinstance_id` can be obtained by navigating to a book detail page in your library, and copying the `id` field). ### What does it look like? If you are successful, the default form will look like this: ![Default form which displays the book details, due date, renewal date and a submit button appears in case the link works successfully](/en-US/docs/Learn/Server-side/Django/Forms/forms_example_renew_default.png) The form with an invalid value entered will look like this: ![Same form as above with an error message: invalid date - renewal in the past](/en-US/docs/Learn/Server-side/Django/Forms/forms_example_renew_invalid.png) The list of all books with renew links will look like this: ![Displays list of all renewed books along with their details. Past due is in red.](/en-US/docs/Learn/Server-side/Django/Forms/forms_example_renew_allbooks.png) ModelForms ---------- Creating a `Form` class using the approach described above is very flexible, allowing you to create whatever sort of form page you like and associate it with any model or models. However, if you just need a form to map the fields of a *single* model then your model will already define most of the information that you need in your form: fields, labels, help text and so on. Rather than recreating the model definitions in your form, it is easier to use the ModelForm helper class to create the form from your model. This `ModelForm` can then be used within your views in exactly the same way as an ordinary `Form`. A basic `ModelForm` containing the same field as our original `RenewBookForm` is shown below. All you need to do to create the form is add `class Meta` with the associated `model` (`BookInstance`) and a list of the model `fields` to include in the form. ```python from django.forms import ModelForm from catalog.models import BookInstance class RenewBookModelForm(ModelForm): class Meta: model = BookInstance fields = ['due\_back'] ``` **Note:** You can also include all fields in the form using `fields = '__all__'`, or you can use `exclude` (instead of `fields`) to specify the fields *not* to include from the model). Neither approach is recommended because new fields added to the model are then automatically included in the form (without the developer necessarily considering possible security implications). **Note:** This might not look all that much simpler than just using a `Form` (and it isn't in this case, because we just have one field). However, if you have a lot of fields, it can reduce the amount of code quite significantly! The rest of the information comes from the model field definitions (e.g. labels, widgets, help text, error messages). If these aren't quite right, then we can override them in our `class Meta`, specifying a dictionary containing the field to change and its new value. For example, in this form, we might want a label for our field of "*Renewal date*" (rather than the default based on the field name: *Due Back*), and we also want our help text to be specific to this use case. The `Meta` below shows you how to override these fields, and you can similarly set `widgets` and `error_messages` if the defaults aren't sufficient. ```python class Meta: model = BookInstance fields = ['due\_back'] labels = {'due\_back': _('New renewal date')} help_texts = {'due\_back': _('Enter a date between now and 4 weeks (default 3).')} ``` To add validation you can use the same approach as for a normal `Form` — you define a function named `clean_<field_name>()` and raise `ValidationError` exceptions for invalid values. The only difference with respect to our original form is that the model field is named `due_back` and not "`renewal_date`". This change is necessary since the corresponding field in `BookInstance` is called `due_back`. ```python from django.forms import ModelForm from catalog.models import BookInstance class RenewBookModelForm(ModelForm): def clean\_due\_back(self): data = self.cleaned_data['due\_back'] # Check if a date is not in the past. if data < datetime.date.today(): raise ValidationError(_('Invalid date - renewal in past')) # Check if a date is in the allowed range (+4 weeks from today). if data > datetime.date.today() + datetime.timedelta(weeks=4): raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead')) # Remember to always return the cleaned data. return data class Meta: model = BookInstance fields = ['due\_back'] labels = {'due\_back': _('Renewal date')} help_texts = {'due\_back': _('Enter a date between now and 4 weeks (default 3).')} ``` The class `RenewBookModelForm` above is now functionally equivalent to our original `RenewBookForm`. You could import and use it wherever you currently use `RenewBookForm` as long as you also update the corresponding form variable name from `renewal_date` to `due_back` as in the second form declaration: `RenewBookModelForm(initial={'due_back': proposed_renewal_date}`. Generic editing views --------------------- The form handling algorithm we used in our function view example above represents an extremely common pattern in form editing views. Django abstracts much of this "boilerplate" for you, by creating generic editing views for creating, editing, and deleting views based on models. Not only do these handle the "view" behavior, but they automatically create the form class (a `ModelForm`) for you from the model. **Note:** In addition to the editing views described here, there is also a FormView class, which lies somewhere between our function view and the other generic views in terms of "flexibility" vs. "coding effort". Using `FormView`, you still need to create your `Form`, but you don't have to implement all of the standard form-handling patterns. Instead, you just have to provide an implementation of the function that will be called once the submission is known to be valid. In this section, we're going to use generic editing views to create pages to add functionality to create, edit, and delete `Author` records from our library — effectively providing a basic reimplementation of parts of the Admin site (this could be useful if you need to offer admin functionality in a more flexible way than can be provided by the admin site). ### Views Open the views file (**locallibrary/catalog/views.py**) and append the following code block to the bottom of it: ```python from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Author class AuthorCreate(PermissionRequiredMixin, CreateView): model = Author fields = ['first\_name', 'last\_name', 'date\_of\_birth', 'date\_of\_death'] initial = {'date\_of\_death': '11/11/2023'} permission_required = 'catalog.add\_author' class AuthorUpdate(PermissionRequiredMixin, UpdateView): model = Author # Not recommended (potential security issue if more fields added) fields = '\_\_all\_\_' permission_required = 'catalog.change\_author' class AuthorDelete(PermissionRequiredMixin, DeleteView): model = Author success_url = reverse_lazy('authors') permission_required = 'catalog.delete\_author' def form\_valid(self, form): try: self.object.delete() return HttpResponseRedirect(self.success_url) except Exception as e: return HttpResponseRedirect( reverse("author-delete", kwargs={"pk": self.object.pk}) ) ``` As you can see, to create, update, or delete the views you need to derive from `CreateView`, `UpdateView`, and `DeleteView` (respectively) and then define the associated model. We also restrict calling these views to only logged in users with the `add_author`, `change_author`, and `delete_author` permissions, respectively. For the "create" and "update" cases you also need to specify the fields to display in the form (using the same syntax as for `ModelForm`). In this case, we show how to list them individually and the syntax to list "all" fields. You can also specify initial values for each of the fields using a dictionary of *field\_name*/*value* pairs (here we arbitrarily set the date of death for demonstration purposes — you might want to remove that). By default, these views will redirect on success to a page displaying the newly created/edited model item, which in our case will be the author detail view we created in a previous tutorial. You can specify an alternative redirect location by explicitly declaring parameter `success_url`. The `AuthorDelete` class doesn't need to display any of the fields, so these don't need to be specified. We so set a `success_url` (as shown above), because there is no obvious default URL for Django to navigate to after successfully deleting the `Author`. Above we use the `reverse_lazy()` function to redirect to our author list after an author has been deleted — `reverse_lazy()` is a lazily executed version of `reverse()`, used here because we're providing a URL to a class-based view attribute. If deletion of authors should always succeed that would be it. Unfortunately deleting an `Author` will cause an exception if the author has an associated book, because our `Book` model specifies `on_delete=models.RESTRICT` for the author `ForeignKey` field. To handle this case the view overrides the `form_valid()` method so that if deleting the `Author` succeeds it redirects to the `success_url`, but if not, it just redirects back to the same form. We'll update the template below to make clear that you can't delete an `Author` instance that is used in any `Book`. ### URL configurations Open your URL configuration file (**locallibrary/catalog/urls.py**) and add the following configuration to the bottom of the file: ```python urlpatterns += [ path('author/create/', views.AuthorCreate.as_view(), name='author-create'), path('author/<int:pk>/update/', views.AuthorUpdate.as_view(), name='author-update'), path('author/<int:pk>/delete/', views.AuthorDelete.as_view(), name='author-delete'), ] ``` There is nothing particularly new here! You can see that the views are classes, and must hence be called via `.as_view()`, and you should be able to recognize the URL patterns in each case. We must use `pk` as the name for our captured primary key value, as this is the parameter name expected by the view classes. ### Templates The "create" and "update" views use the same template by default, which will be named after your model: `model_name_form.html` (you can change the suffix to something other than **\_form** using the `template_name_suffix` field in your view, for example, `template_name_suffix = '_other_suffix'`) Create the template file `locallibrary/catalog/templates/catalog/author_form.html` and copy the text below. ```django {% extends "base\_generic.html" %} {% block content %} <form action="" method="post"> {% csrf\_token %} <table> {{ form.as\_table }} </table> <input type="submit" value="Submit" /> </form> {% endblock %} ``` This is similar to our previous forms and renders the fields using a table. Note also how again we declare the `{% csrf_token %}` to ensure that our forms are resistant to CSRF attacks. The "delete" view expects to find a template named with the format \_`model_name_confirm_delete.html` (again, you can change the suffix using `template_name_suffix` in your view). Create the template file `locallibrary/catalog/templates/catalog/author_confirm_delete.html` and copy the text below. ```django {% extends "base\_generic.html" %} {% block content %} <h1>Delete Author: {{ author }}</h1> {% if author.book\_set.all %} <p>You can't delete this author until all their books have been deleted:</p> <ul> {% for book in author.book\_set.all %} <li><a href="{% url 'book-detail' book.pk %}">{{book}}</a> ({{book.bookinstance\_set.all.count}})</li> {% endfor %} </ul> {% else %} <p>Are you sure you want to delete the author?</p> <form action="" method="POST"> {% csrf\_token %} <input type="submit" action="" value="Yes, delete."> </form> {% endif %} {% endblock %} ``` The template should be familiar. It first checks if the author is used in any books, and if so displays the list of books that must be deleted before the author record can be deleted. If not, it displays a form asking the user to confirm they want to delete the author record. The final step is to hook the pages into the sidebar. First we'll add a link for creating the author into the *base template*, so that it is visible in all pages for logged in users who are considered "staff" and who have permission to create authors (`catalog.add_author`). Open **/locallibrary/catalog/templates/base\_generic.html** and add the lines that allow users with the permission to create the author (in the same block as the link that shows "All Borrowed" books). Remember to reference the URL using it's name `'author-create'` as shown below. ```django {% if user.is\_staff %} <hr> <ul class="sidebar-nav"> <li>Staff</li> <li><a href="{% url 'all-borrowed' %}">All borrowed</a></li> {% if perms.catalog.add\_author %} <li><a href="{% url 'author-create' %}">Create author</a></li> {% endif %} </ul> {% endif %} ``` We'll add the links to update and delete authors to the author detail page. Open **catalog/templates/catalog/author\_detail.html** and append the following code: ```django {% block sidebar %} {{ block.super }} {% if perms.catalog.change\_author or perms.catalog.delete\_author %} <hr> <ul class="sidebar-nav"> {% if perms.catalog.change\_author %} <li><a href="{% url 'author-update' author.id %}">Update author</a></li> {% endif %} {% if not author.book\_set.all and perms.catalog.delete\_author %} <li><a href="{% url 'author-delete' author.id %}">Delete author</a></li> {% endif %} </ul> {% endif %} {% endblock %} ``` This block overrides the `sidebar` block in the base template and then pulls in the original content using `{{ block.super }}`. It then appends links to update or delete the author, but when the user has the correct permissions and the author record isn't associated with any books. The pages are now ready to test! ### Testing the page First, log in to the site with an account that has author add, change and delete permissions. Navigate to any page, and select "Create author" in the sidebar (with URL `http://127.0.0.1:8000/catalog/author/create/`). The page should look like the screenshot below. ![Form Example: Create Author](/en-US/docs/Learn/Server-side/Django/Forms/forms_example_create_author.png) Enter values for the fields and then press **Submit** to save the author record. You should now be taken to a detail view for your new author, with a URL of something like `http://127.0.0.1:8000/catalog/author/10`. ![Form Example: Author Detail showing Update and Delete links](/en-US/docs/Learn/Server-side/Django/Forms/forms_example_detail_author_update.png) You can test editing the record by selecting the "Update author" link (with URL something like `http://127.0.0.1:8000/catalog/author/10/update/`) — we don't show a screenshot because it looks just like the "create" page! Finally, we can delete the page by selecting "Delete author" from the sidebar on the detail page. Django should display the delete page shown below if the author record isn't used in any books. Press "**Yes, delete.**" to remove the record and be taken to the list of all authors. ![Form with option to delete author](/en-US/docs/Learn/Server-side/Django/Forms/forms_example_delete_author.png) Challenge yourself ------------------ Create some forms to create, edit, and delete `Book` records. You can use exactly the same structure as for `Authors` (for the deletion, remember that you can't delete a `Book` until all its associated `BookInstance` records are deleted) and you must use the correct permissions. If your **book\_form.html** template is just a copy-renamed version of the **author\_form.html** template, then the new "create book" page will look like the screenshot below: ![Screenshot displaying various fields in the form like title, author, summary, ISBN, genre and language](/en-US/docs/Learn/Server-side/Django/Forms/forms_example_create_book.png) Summary ------- Creating and handling forms can be a complicated process! Django makes it much easier by providing programmatic mechanisms to declare, render, and validate forms. Furthermore, Django provides generic form editing views that can do *almost all* the work to define pages that can create, edit, and delete records associated with a single model instance. There is a lot more that can be done with forms (check out our See also list below), but you should now understand how to add basic forms and form-handling code to your own websites. See also -------- * Working with forms (Django docs) * Writing your first Django app, part 4 > Writing a simple form (Django docs) * The Forms API (Django docs) * Form fields (Django docs) * Form and field validation (Django docs) * Form handling with class-based views (Django docs) * Creating forms from models (Django docs) * Generic editing views (Django docs) * Previous * Overview: Django * Next
Django introduction - Learn web development
Django introduction =================== * Overview: Django * Next In this first Django article, we answer the question "What is Django?" and give you an overview of what makes this web framework special. We'll outline the main features, including some of the advanced functionality that we won't have time to cover in detail in this module. We'll also show you some of the main building blocks of a Django application (although at this point you won't yet have a development environment in which to test it). | | | | --- | --- | | Prerequisites: | A general understanding of server-side website programming, and in particular the mechanics of client-server interactions in websites. | | Objective: | To gain familiarity with what Django is, what functionality it provides, and the main building blocks of a Django application. | What is Django? --------------- Django is a high-level Python web framework that enables rapid development of secure and maintainable websites. Built by experienced developers, Django takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. It is free and open source, has a thriving and active community, great documentation, and many options for free and paid-for support. Django helps you write software that is: Complete Django follows the "Batteries included" philosophy and provides almost everything developers might want to do "out of the box". Because everything you need is part of the one "product", it all works seamlessly together, follows consistent design principles, and has extensive and up-to-date documentation. Versatile Django can be (and has been) used to build almost any type of website — from content management systems and wikis, through to social networks and news sites. It can work with any client-side framework, and can deliver content in almost any format (including HTML, RSS feeds, JSON, and XML). Internally, while it provides choices for almost any functionality you might want (e.g. several popular databases, templating engines, etc.), it can also be extended to use other components if needed. Secure Django helps developers avoid many common security mistakes by providing a framework that has been engineered to "do the right things" to protect the website automatically. For example, Django provides a secure way to manage user accounts and passwords, avoiding common mistakes like putting session information in cookies where it is vulnerable (instead cookies just contain a key, and the actual data is stored in the database) or directly storing passwords rather than a password hash. *A password hash is a fixed-length value created by sending the password through a cryptographic hash function. Django can check if an entered password is correct by running it through the hash function and comparing the output to the stored hash value. However due to the "one-way" nature of the function, even if a stored hash value is compromised it is hard for an attacker to work out the original password.* Django enables protection against many vulnerabilities by default, including SQL injection, cross-site scripting, cross-site request forgery and clickjacking (see Website security for more details of such attacks). Scalable Django uses a component-based "shared-nothing" architecture (each part of the architecture is independent of the others, and can hence be replaced or changed if needed). Having a clear separation between the different parts means that it can scale for increased traffic by adding hardware at any level: caching servers, database servers, or application servers. Some of the busiest sites have successfully scaled Django to meet their demands (e.g. Instagram and Disqus, to name just two). Maintainable Django code is written using design principles and patterns that encourage the creation of maintainable and reusable code. In particular, it makes use of the Don't Repeat Yourself (DRY) principle so there is no unnecessary duplication, reducing the amount of code. Django also promotes the grouping of related functionality into reusable "applications" and, at a lower level, groups related code into modules (along the lines of the Model View Controller (MVC) pattern). Portable Django is written in Python, which runs on many platforms. That means that you are not tied to any particular server platform, and can run your applications on many flavors of Linux, Windows, and macOS. Furthermore, Django is well-supported by many web hosting providers, who often provide specific infrastructure and documentation for hosting Django sites. Where did it come from? ----------------------- Django was initially developed between 2003 and 2005 by a web team who were responsible for creating and maintaining newspaper websites. After creating a number of sites, the team began to factor out and reuse lots of common code and design patterns. This common code evolved into a generic web development framework, which was open-sourced as the "Django" project in July 2005. Django has continued to grow and improve, from its first milestone release (1.0) in September 2008 through to the version 4.0 in 2022. Each release has added new functionality and bug fixes, ranging from support for new types of databases, template engines, and caching, through to the addition of "generic" view functions and classes (which reduce the amount of code that developers have to write for a number of programming tasks). **Note:** Check out the release notes on the Django website to see what has changed in recent versions, and how much work is going into making Django better. Django is now a thriving, collaborative open source project, with many thousands of users and contributors. While it does still have some features that reflect its origin, Django has evolved into a versatile framework that is capable of developing any type of website. How popular is Django? ---------------------- There isn't any readily-available and definitive measurement of popularity of server-side frameworks (although you can estimate popularity using mechanisms like counting the number of GitHub projects and StackOverflow questions for each platform). A better question is whether Django is "popular enough" to avoid the problems of unpopular platforms. Is it continuing to evolve? Can you get help if you need it? Is there an opportunity for you to get paid work if you learn Django? Based on the number of high profile sites that use Django, the number of people contributing to the codebase, and the number of people providing both free and paid for support, then yes, Django is a popular framework! High-profile sites that use Django include: Disqus, Instagram, Knight Foundation, MacArthur Foundation, Mozilla, National Geographic, Open Knowledge Foundation, Pinterest, and Open Stack (source: Django overview page). Is Django opinionated? ---------------------- Web frameworks often refer to themselves as "opinionated" or "unopinionated". Opinionated frameworks are those with opinions about the "right way" to handle any particular task. They often support rapid development *in a particular domain* (solving problems of a particular type) because the right way to do anything is usually well-understood and well-documented. However they can be less flexible at solving problems outside their main domain, and tend to offer fewer choices for what components and approaches they can use. Unopinionated frameworks, by contrast, have far fewer restrictions on the best way to glue components together to achieve a goal, or even what components should be used. They make it easier for developers to use the most suitable tools to complete a particular task, albeit at the cost that you need to find those components yourself. Django is "somewhat opinionated", and hence delivers the "best of both worlds". It provides a set of components to handle most web development tasks and one (or two) preferred ways to use them. However, Django's decoupled architecture means that you can usually pick and choose from a number of different options, or add support for completely new ones if desired. What does Django code look like? -------------------------------- In a traditional data-driven website, a web application waits for HTTP requests from the web browser (or other client). When a request is received the application works out what is needed based on the URL and possibly information in `POST` data or `GET` data. Depending on what is required it may then read or write information from a database or perform other tasks required to satisfy the request. The application will then return a response to the web browser, often dynamically creating an HTML page for the browser to display by inserting the retrieved data into placeholders in an HTML template. Django web applications typically group the code that handles each of these steps into separate files: ![Django - files for views, model, URLs, template](/en-US/docs/Learn/Server-side/Django/Introduction/basic-django.png) * **URLs:** While it is possible to process requests from every single URL via a single function, it is much more maintainable to write a separate view function to handle each resource. A URL mapper is used to redirect HTTP requests to the appropriate view based on the request URL. The URL mapper can also match particular patterns of strings or digits that appear in a URL and pass these to a view function as data. * **View:** A view is a request handler function, which receives HTTP requests and returns HTTP responses. Views access the data needed to satisfy requests via *models*, and delegate the formatting of the response to *templates*. * **Models:** Models are Python objects that define the structure of an application's data, and provide mechanisms to manage (add, modify, delete) and query records in the database. * **Templates:** A template is a text file defining the structure or layout of a file (such as an HTML page), with placeholders used to represent actual content. A *view* can dynamically create an HTML page using an HTML template, populating it with data from a *model*. A template can be used to define the structure of any type of file; it doesn't have to be HTML! **Note:** Django refers to this organization as the "Model View Template (MVT)" architecture. It has many similarities to the more familiar Model View Controller architecture. The sections below will give you an idea of what these main parts of a Django app look like (we'll go into more detail later on in the course, once we've set up a development environment). ### Sending the request to the right view (urls.py) A URL mapper is typically stored in a file named **urls.py**. In the example below, the mapper (`urlpatterns`) defines a list of mappings between *routes* (specific URL *patterns)* and corresponding view functions. If an HTTP Request is received that has a URL matching a specified pattern, then the associated view function will be called and passed the request. ```python urlpatterns = [ path('admin/', admin.site.urls), path('book/<int:id>/', views.book_detail, name='book\_detail'), path('catalog/', include('catalog.urls')), re_path(r'^([0-9]+)/$', views.best), ] ``` The `urlpatterns` object is a list of `path()` and/or `re_path()` functions (Python lists are defined using square brackets, where items are separated by commas and may have an optional trailing comma. For example: `[item1, item2, item3,]`). The first argument to both methods is a route (pattern) that will be matched. The `path()` method uses angle brackets to define parts of a URL that will be captured and passed through to the view function as named arguments. The `re_path()` function uses a flexible pattern matching approach known as a regular expression. We'll talk about these in a later article! The second argument is another function that will be called when the pattern is matched. The notation `views.book_detail` indicates that the function is called `book_detail()` and can be found in a module called `views` (i.e. inside a file named `views.py`) ### Handling the request (views.py) Views are the heart of the web application, receiving HTTP requests from web clients and returning HTTP responses. In between, they marshal the other resources of the framework to access databases, render templates, etc. The example below shows a minimal view function `index()`, which could have been called by our URL mapper in the previous section. Like all view functions it receives an `HttpRequest` object as a parameter (`request`) and returns an `HttpResponse` object. In this case we don't do anything with the request, and our response returns a hard-coded string. We'll show you a request that does something more interesting in a later section. ```python # filename: views.py (Django view functions) from django.http import HttpResponse def index(request): # Get an HttpRequest - the request parameter # perform operations using information from the request. # Return HttpResponse return HttpResponse('Hello from Django!') ``` **Note:** A little bit of Python: * Python modules are "libraries" of functions, stored in separate files, that we might want to use in our code. Here we import just the `HttpResponse` object from the `django.http` module so that we can use it in our view: `from django.http import HttpResponse`. There are other ways of importing some or all objects from a module. * Functions are declared using the `def` keyword as shown above, with named parameters listed in parentheses after the name of the function; the whole line ends in a colon. Note how the next lines are all **indented**. The indentation is important, as it specifies that the lines of code are inside that particular block (mandatory indentation is a key feature of Python, and is one reason that Python code is so easy to read). Views are usually stored in a file called **views.py**. ### Defining data models (models.py) Django web applications manage and query data through Python objects referred to as models. Models define the structure of stored data, including the field *types* and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc. The definition of the model is independent of the underlying database — you can choose one of several as part of your project settings. Once you've chosen what database you want to use, you don't need to talk to it directly at all — you just write your model structure and other code, and Django handles all the "dirty work" of communicating with the database for you. The code snippet below shows a very simple Django model for a `Team` object. The `Team` class is derived from the Django class `models.Model`. It defines the team name and team level as character fields and specifies a maximum number of characters to be stored for each record. The `team_level` can be one of several values, so we define it as a choice field and provide a mapping between choices to be displayed and data to be stored, along with a default value. ```python # filename: models.py from django.db import models class Team(models.Model): team_name = models.CharField(max_length=40) TEAM_LEVELS = ( ('U09', 'Under 09s'), ('U10', 'Under 10s'), ('U11', 'Under 11s'), # … # list other team levels ) team_level = models.CharField(max_length=3, choices=TEAM_LEVELS, default='U11') ``` **Note:** A little bit of Python: Python supports "object-oriented programming", a style of programming where we organize our code into objects, which include related data and functions for operating on that data. Objects can also inherit/extend/derive from other objects, allowing common behavior between related objects to be shared. In Python we use the keyword `class` to define the "blueprint" for an object. We can create multiple specific *instances* of the type of object based on the model in the class. So for example, here we have a `Team` class, which derives from the `Model` class. This means it is a model, and will contain all the methods of a model, but we can also give it specialized features of its own too. In our model we define the fields our database will need to store our data, giving them specific names. Django uses these definitions, including the field names, to create the underlying database. ### Querying data (views.py) The Django model provides a simple query API for searching the associated database. This can match against a number of fields at a time using different criteria (e.g. exact, case-insensitive, greater than, etc.), and can support complex statements (for example, you can specify a search on U11 teams that have a team name that starts with "Fr" or ends with "al"). The code snippet shows a view function (resource handler) for displaying all of our U09 teams. The `list_teams = Team.objects.filter(team_level__exact="U09")` line shows how we can use the model query API to filter for all records where the `team_level` field has exactly the text '`U09`' (note how this criteria is passed to the `filter()` function as an argument, with the field name and match type separated by a double underscore: **`team_level__exact`**). ```python ## filename: views.py from django.shortcuts import render from .models import Team def index(request): list_teams = Team.objects.filter(team_level__exact="U09") context = {'youngest\_teams': list_teams} return render(request, '/best/index.html', context) ``` This function uses the `render()` function to create the `HttpResponse` that is sent back to the browser. This function is a *shortcut*; it creates an HTML file by combining a specified HTML template and some data to insert in the template (provided in the variable named "`context`"). In the next section we show how the template has the data inserted in it to create the HTML. ### Rendering data (HTML templates) Template systems allow you to specify the structure of an output document, using placeholders for data that will be filled in when a page is generated. Templates are often used to create HTML, but can also create other types of document. Django supports both its native templating system and another popular Python library called Jinja2 out of the box (it can also be made to support other systems if needed). The code snippet shows what the HTML template called by the `render()` function in the previous section might look like. This template has been written under the assumption that it will have access to a list variable called `youngest_teams` when it is rendered (this is contained in the `context` variable inside the `render()` function above). Inside the HTML skeleton we have an expression that first checks if the `youngest_teams` variable exists, and then iterates it in a `for` loop. On each iteration the template displays each team's `team_name` value in an ``<li>`` element. ```python ## filename: best/templates/best/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Home page</title> </head> <body> {% if youngest_teams %} <ul> {% for team in youngest_teams %} <li>{{ team.team_name }}</li> {% endfor %} </ul> {% else %} <p>No teams are available.</p> {% endif %} </body> </html> ``` What else can you do? --------------------- The preceding sections show the main features that you'll use in almost every web application: URL mapping, views, models and templates. Just a few of the other things provided by Django include: * **Forms**: HTML Forms are used to collect user data for processing on the server. Django simplifies form creation, validation, and processing. * **User authentication and permissions**: Django includes a robust user authentication and permission system that has been built with security in mind. * **Caching**: Creating content dynamically is much more computationally intensive (and slow) than serving static content. Django provides flexible caching so that you can store all or part of a rendered page so that it doesn't get re-rendered except when necessary. * **Administration site**: The Django administration site is included by default when you create an app using the basic skeleton. It makes it trivially easy to provide an admin page for site administrators to create, edit, and view any data models in your site. * **Serializing data**: Django makes it easy to serialize and serve your data as XML or JSON. This can be useful when creating a web service (a website that purely serves data to be consumed by other applications or sites, and doesn't display anything itself), or when creating a website in which the client-side code handles all the rendering of data. Summary ------- Congratulations, you've completed the first step in your Django journey! You should now understand Django's main benefits, a little about its history, and roughly what each of the main parts of a Django app might look like. You should have also learned a few things about the Python programming language, including the syntax for lists, functions, and classes. You've already seen some real Django code above, but unlike with client-side code, you need to set up a development environment to run it. That's our next step. * Overview: Django * Next
Django Tutorial Part 8: User authentication and permissions - Learn web development
Django Tutorial Part 8: User authentication and permissions =========================================================== * Previous * Overview: Django * Next In this tutorial, we'll show you how to allow users to log in to your site with their own accounts, and how to control what they can do and see based on whether or not they are logged in and their *permissions*. As part of this demonstration, we'll extend the LocalLibrary website, adding login and logout pages, and user- and staff-specific pages for viewing books that have been borrowed. | | | | --- | --- | | Prerequisites: | Complete all previous tutorial topics, up to and including Django Tutorial Part 7: Sessions framework. | | Objective: | To understand how to set up and use user authentication and permissions. | Overview -------- Django provides an authentication and authorization ("permission") system, built on top of the session framework discussed in the previous tutorial, that allows you to verify user credentials and define what actions each user is allowed to perform. The framework includes built-in models for `Users` and `Groups` (a generic way of applying permissions to more than one user at a time), permissions/flags that designate whether a user may perform a task, forms and views for logging in users, and view tools for restricting content. **Note:** According to Django the authentication system aims to be very generic, and so does not provide some features provided in other web authentication systems. Solutions for some common problems are available as third-party packages. For example, throttling of login attempts and authentication against third parties (e.g. OAuth). In this tutorial, we'll show you how to enable user authentication in the LocalLibrary website, create your own login and logout pages, add permissions to your models, and control access to pages. We'll use the authentication/permissions to display lists of books that have been borrowed for both users and librarians. The authentication system is very flexible, and you can build up your URLs, forms, views, and templates from scratch if you like, just calling the provided API to log in the user. However, in this article, we're going to use Django's "stock" authentication views and forms for our login and logout pages. We'll still need to create some templates, but that's pretty easy. We'll also show you how to create permissions, and check on login status and permissions in both views and templates. Enabling authentication ----------------------- The authentication was enabled automatically when we created the skeleton website (in tutorial 2) so you don't need to do anything more at this point. **Note:** The necessary configuration was all done for us when we created the app using the `django-admin startproject` command. The database tables for users and model permissions were created when we first called `python manage.py migrate`. The configuration is set up in the `INSTALLED_APPS` and `MIDDLEWARE` sections of the project file (**locallibrary/locallibrary/settings.py**), as shown below: ```python INSTALLED_APPS = [ # … 'django.contrib.auth', # Core authentication framework and its default models. 'django.contrib.contenttypes', # Django content type system (allows permissions to be associated with models). # … MIDDLEWARE = [ # … 'django.contrib.sessions.middleware.SessionMiddleware', # Manages sessions across requests # … 'django.contrib.auth.middleware.AuthenticationMiddleware', # Associates users with requests using sessions. # … ``` Creating users and groups ------------------------- You already created your first user when we looked at the Django admin site in tutorial 4 (this was a superuser, created with the command `python manage.py createsuperuser`). Our superuser is already authenticated and has all permissions, so we'll need to create a test user to represent a normal site user. We'll be using the admin site to create our *locallibrary* groups and website logins, as it is one of the quickest ways to do so. **Note:** You can also create users programmatically as shown below. You would have to do this, for example, if developing an interface to allow "ordinary" users to create their own logins (you shouldn't give most users access to the admin site). ```python from django.contrib.auth.models import User # Create user and save to the database user = User.objects.create_user('myusername', '[email protected]', 'mypassword') # Update fields and then save again user.first_name = 'Tyrone' user.last_name = 'Citizen' user.save() ``` Note however that it is highly recommended to set up a *custom user model* when starting a project, as you'll be able to easily customize it in the future if the need arises. If using a custom user model the code to create the same user would look like this: ```python # Get current user model from settings from django.contrib.auth import get_user_model User = get_user_model() # Create user from model and save to the database user = User.objects.create_user('myusername', '[email protected]', 'mypassword') # Update fields and then save again user.first_name = 'Tyrone' user.last_name = 'Citizen' user.save() ``` For more information, see Using a custom user model when starting a project (Django docs). Below we'll first create a group and then a user. Even though we don't have any permissions to add for our library members yet, if we need to later, it will be much easier to add them once to the group than individually to each member. Start the development server and navigate to the admin site in your local web browser (`http://127.0.0.1:8000/admin/`). Login to the site using the credentials for your superuser account. The top level of the Admin site displays all of your models, sorted by "Django application". From the **Authentication and Authorization** section, you can click the **Users** or **Groups** links to see their existing records. ![Admin site - add groups or users](/en-US/docs/Learn/Server-side/Django/Authentication/admin_authentication_add.png) First lets create a new group for our library members. 1. Click the **Add** button (next to Group) to create a new *Group*; enter the **Name** "Library Members" for the group. ![Admin site - add group](/en-US/docs/Learn/Server-side/Django/Authentication/admin_authentication_add_group.png) 2. We don't need any permissions for the group, so just press **SAVE** (you will be taken to a list of groups). Now let's create a user: 1. Navigate back to the home page of the admin site 2. Click the **Add** button next to *Users* to open the *Add user* dialog box. ![Admin site - add user pt1](/en-US/docs/Learn/Server-side/Django/Authentication/admin_authentication_add_user_prt1.png) 3. Enter an appropriate **Username** and **Password**/**Password confirmation** for your test user 4. Press **SAVE** to create the user. The admin site will create the new user and immediately take you to a *Change user* screen where you can change your **username** and add information for the User model's optional fields. These fields include the first name, last name, email address, and the user's status and permissions (only the **Active** flag should be set). Further down you can specify the user's groups and permissions, and see important dates related to the user (e.g. their join date and last login date). ![Admin site - add user pt2](/en-US/docs/Learn/Server-side/Django/Authentication/admin_authentication_add_user_prt2.png) 5. In the *Groups* section, select **Library Member** group from the list of *Available groups*, and then press the **right-arrow** between the boxes to move it into the *Chosen groups* box. ![Admin site - add user to group](/en-US/docs/Learn/Server-side/Django/Authentication/admin_authentication_user_add_group.png) 6. We don't need to do anything else here, so just select **SAVE** again, to go to the list of users. That's it! Now you have a "normal library member" account that you will be able to use for testing (once we've implemented the pages to enable them to log in). **Note:** You should try creating another library member user. Also, create a group for Librarians, and add a user to that too! Setting up your authentication views ------------------------------------ Django provides almost everything you need to create authentication pages to handle login, log out, and password management "out of the box". This includes a URL mapper, views and forms, but it does not include the templates — we have to create our own! In this section, we show how to integrate the default system into the *LocalLibrary* website and create the templates. We'll put them in the main project URLs. **Note:** You don't have to use any of this code, but it is likely that you'll want to because it makes things a lot easier. You'll almost certainly need to change the form handling code if you change your user model, but even so, you would still be able to use the stock view functions. **Note:** In this case, we could reasonably put the authentication pages, including the URLs and templates, inside our catalog application. However, if we had multiple applications it would be better to separate out this shared login behavior and have it available across the whole site, so that is what we've shown here! ### Project URLs Add the following to the bottom of the project urls.py file (**locallibrary/locallibrary/urls.py**) file: ```python # Add Django site authentication urls (for login, logout, password management) urlpatterns += [ path('accounts/', include('django.contrib.auth.urls')), ] ``` Navigate to the `http://127.0.0.1:8000/accounts/` URL (note the trailing forward slash!). Django will show an error that it could not find this URL, and list all the URLs it tried. From this you can see the URLs that will work, for example: **Note:** Using the above method adds the following URLs with names in square brackets, which can be used to reverse the URL mappings. You don't have to implement anything else — the above URL mapping automatically maps the below mentioned URLs. ```python accounts/ login/ [name='login'] accounts/ logout/ [name='logout'] accounts/ password_change/ [name='password\_change'] accounts/ password_change/done/ [name='password\_change\_done'] accounts/ password_reset/ [name='password\_reset'] accounts/ password_reset/done/ [name='password\_reset\_done'] accounts/ reset/<uidb64>/<token>/ [name='password\_reset\_confirm'] accounts/ reset/done/ [name='password\_reset\_complete'] ``` Now try to navigate to the login URL (`http://127.0.0.1:8000/accounts/login/`). This will fail again, but with an error that tells you that we're missing the required template (**registration/login.html**) on the template search path. You'll see the following lines listed in the yellow section at the top: ```python Exception Type: TemplateDoesNotExist Exception Value: registration/login.html ``` The next step is to create a registration directory on the search path and then add the **login.html** file. ### Template directory The URLs (and implicitly, views) that we just added expect to find their associated templates in a directory **/registration/** somewhere in the templates search path. For this site, we'll put our HTML pages in the **templates/registration/** directory. This directory should be in your project root directory, that is, the same directory as the **catalog** and **locallibrary** folders. Please create these folders now. **Note:** Your folder structure should now look like the below: ``` locallibrary/ # Django project folder catalog/ locallibrary/ templates/ registration/ ``` To make the **templates** directory visible to the template loader we need to add it in the template search path. Open the project settings (**/locallibrary/locallibrary/settings.py**). Then import the `os` module (add the following line near the top of the file). ```python import os # needed by code below ``` Update the `TEMPLATES` section's `'DIRS'` line as shown: ```python # … TEMPLATES = [ { # … 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP\_DIRS': True, # … ``` ### Login template **Warning:** The authentication templates provided in this article are a very basic/slightly modified version of the Django demonstration login templates. You may need to customize them for your own use! Create a new HTML file called /**locallibrary/templates/registration/login.html** and give it the following contents: ```django {% extends "base\_generic.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is\_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf\_token %} <table> <tr> <td>{{ form.username.label\_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label\_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login"> <input type="hidden" name="next" value="{{ next }}"> </form> {# Assumes you set up the password\_reset view in your URLconf #} <p><a href="{% url 'password\_reset' %}">Lost password?</a></p> {% endblock %} ``` This template shares some similarities with the ones we've seen before — it extends our base template and overrides the `content` block. The rest of the code is fairly standard form handling code, which we will discuss in a later tutorial. All you need to know for now is that this will display a form in which you can enter your username and password, and that if you enter invalid values you will be prompted to enter correct values when the page refreshes. Navigate back to the login page (`http://127.0.0.1:8000/accounts/login/`) once you've saved your template, and you should see something like this: ![Library login page v1](/en-US/docs/Learn/Server-side/Django/Authentication/library_login.png) If you log in using valid credentials, you'll be redirected to another page (by default this will be `http://127.0.0.1:8000/accounts/profile/`). The problem is that, by default, Django expects that upon logging in you will want to be taken to a profile page, which may or may not be the case. As you haven't defined this page yet, you'll get another error! Open the project settings (**/locallibrary/locallibrary/settings.py**) and add the text below to the bottom. Now when you log in you should be redirected to the site homepage by default. ```python # Redirect to home URL after login (Default redirects to /accounts/profile/) LOGIN_REDIRECT_URL = '/' ``` ### Logout template If you navigate to the logout URL (`http://127.0.0.1:8000/accounts/logout/`) then you'll see some odd behavior — your user will be logged out sure enough, but you'll be taken to the **Admin** logout page. That's not what you want, if only because the login link on that page takes you to the Admin login screen (and that is only available to users who have the `is_staff` permission). Create and open **/locallibrary/templates/registration/logged\_out.html**. Copy in the text below: ```django {% extends "base\_generic.html" %} {% block content %} <p>Logged out!</p> <a href="{% url 'login'%}">Click here to login again.</a> {% endblock %} ``` This template is very simple. It just displays a message informing you that you have been logged out, and provides a link that you can press to go back to the login screen. If you go to the logout URL again you should see this page: ![Library logout page v1](/en-US/docs/Learn/Server-side/Django/Authentication/library_logout.png) ### Password reset templates The default password reset system uses email to send the user a reset link. You need to create forms to get the user's email address, send the email, allow them to enter a new password, and to note when the whole process is complete. The following templates can be used as a starting point. #### Password reset form This is the form used to get the user's email address (for sending the password reset email). Create **/locallibrary/templates/registration/password\_reset\_form.html**, and give it the following contents: ```django {% extends "base\_generic.html" %} {% block content %} <form action="" method="post"> {% csrf\_token %} {% if form.email.errors %} {{ form.email.errors }} {% endif %} <p>{{ form.email }}</p> <input type="submit" class="btn btn-default btn-lg" value="Reset password"> </form> {% endblock %} ``` #### Password reset done This form is displayed after your email address has been collected. Create **/locallibrary/templates/registration/password\_reset\_done.html**, and give it the following contents: ```django {% extends "base\_generic.html" %} {% block content %} <p>We've emailed you instructions for setting your password. If they haven't arrived in a few minutes, check your spam folder.</p> {% endblock %} ``` #### Password reset email This template provides the text of the HTML email containing the reset link that we will send to users. Create **/locallibrary/templates/registration/password\_reset\_email.html**, and give it the following contents: ```django Someone asked for password reset for email {{ email }}. Follow the link below: {{ protocol }}://{{ domain }}{% url 'password\_reset\_confirm' uidb64=uid token=token %} ``` #### Password reset confirm This page is where you enter your new password after clicking the link in the password reset email. Create **/locallibrary/templates/registration/password\_reset\_confirm.html**, and give it the following contents: ```django {% extends "base\_generic.html" %} {% block content %} {% if validlink %} <p>Please enter (and confirm) your new password.</p> <form action="" method="post"> {% csrf\_token %} <table> <tr> <td>{{ form.new\_password1.errors }} <label for="id\_new\_password1">New password:</label></td> <td>{{ form.new\_password1 }}</td> </tr> <tr> <td>{{ form.new\_password2.errors }} <label for="id\_new\_password2">Confirm password:</label></td> <td>{{ form.new\_password2 }}</td> </tr> <tr> <td></td> <td><input type="submit" value="Change my password"></td> </tr> </table> </form> {% else %} <h1>Password reset failed</h1> <p>The password reset link was invalid, possibly because it has already been used. Please request a new password reset.</p> {% endif %} {% endblock %} ``` #### Password reset complete This is the last password-reset template, which is displayed to notify you when the password reset has succeeded. Create **/locallibrary/templates/registration/password\_reset\_complete.html**, and give it the following contents: ```django {% extends "base\_generic.html" %} {% block content %} <h1>The password has been changed!</h1> <p><a href="{% url 'login' %}">log in again?</a></p> {% endblock %} ``` ### Testing the new authentication pages Now that you've added the URL configuration and created all these templates, the authentication pages should now just work! You can test the new authentication pages by attempting to log in to and then log out of your superuser account using these URLs: * `http://127.0.0.1:8000/accounts/login/` * `http://127.0.0.1:8000/accounts/logout/` You'll be able to test the password reset functionality from the link in the login page. **Be aware that Django will only send reset emails to addresses (users) that are already stored in its database!** **Note:** The password reset system requires that your website supports email, which is beyond the scope of this article, so this part **won't work yet**. To allow testing, put the following line at the end of your settings.py file. This logs any emails sent to the console (so you can copy the password reset link from the console). ```python EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' ``` For more information, see Sending email (Django docs). Testing against authenticated users ----------------------------------- This section looks at what we can do to selectively control content the user sees based on whether they are logged in or not. ### Testing in templates You can get information about the currently logged in user in templates with the `{{ user }}` template variable (this is added to the template context by default when you set up the project as we did in our skeleton). Typically you will first test against the `{{ user.is_authenticated }}` template variable to determine whether the user is eligible to see specific content. To demonstrate this, next we'll update our sidebar to display a "Login" link if the user is logged out, and a "Logout" link if they are logged in. Open the base template (**/locallibrary/catalog/templates/base\_generic.html**) and copy the following text into the `sidebar` block, immediately before the `endblock` template tag. ```django <ul class="sidebar-nav"> … {% if user.is\_authenticated %} <li>User: {{ user.get\_username }}</li> <li><a href="{% url 'logout' %}?next={{ request.path }}">Logout</a></li> {% else %} <li><a href="{% url 'login' %}?next={{ request.path }}">Login</a></li> {% endif %} </ul> ``` As you can see, we use `if` / `else` / `endif` template tags to conditionally display text based on whether `{{ user.is_authenticated }}` is true. If the user is authenticated then we know that we have a valid user, so we call `{{ user.get_username }}` to display their name. We create the login and logout link URLs using the `url` template tag and the names of the respective URL configurations. Note also how we have appended `?next={{ request.path }}` to the end of the URLs. What this does is add a URL parameter `next` containing the address (URL) of the *current* page, to the end of the linked URL. After the user has successfully logged in/out, the views will use this "`next`" value to redirect the user back to the page where they first clicked the login/logout link. **Note:** Try it out! If you're on the home page and you click Login/Logout in the sidebar, then after the operation completes you should end up back on the same page. ### Testing in views If you're using function-based views, the easiest way to restrict access to your functions is to apply the `login_required` decorator to your view function, as shown below. If the user is logged in then your view code will execute as normal. If the user is not logged in, this will redirect to the login URL defined in the project settings (`settings.LOGIN_URL`), passing the current absolute path as the `next` URL parameter. If the user succeeds in logging in then they will be returned back to this page, but this time authenticated. ```python from django.contrib.auth.decorators import login_required @login\_required def my\_view(request): # … ``` **Note:** You can do the same sort of thing manually by testing on `request.user.is_authenticated`, but the decorator is much more convenient! Similarly, the easiest way to restrict access to logged-in users in your class-based views is to derive from `LoginRequiredMixin`. You need to declare this mixin first in the superclass list, before the main view class. ```python from django.contrib.auth.mixins import LoginRequiredMixin class MyView(LoginRequiredMixin, View): # … ``` This has exactly the same redirect behavior as the `login_required` decorator. You can also specify an alternative location to redirect the user to if they are not authenticated (`login_url`), and a URL parameter name instead of "`next`" to insert the current absolute path (`redirect_field_name`). ```python class MyView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'redirect\_to' ``` For additional detail, check out the Django docs here. Example — listing the current user's books ------------------------------------------ Now that we know how to restrict a page to a particular user, let's create a view of the books that the current user has borrowed. Unfortunately, we don't yet have any way for users to borrow books! So before we can create the book list we'll first extend the `BookInstance` model to support the concept of borrowing and use the Django Admin application to loan a number of books to our test user. ### Models First, we're going to have to make it possible for users to have a `BookInstance` on loan (we already have a `status` and a `due_back` date, but we don't yet have any association between this model and a particular user. We'll create one using a `ForeignKey` (one-to-many) field. We also need an easy mechanism to test whether a loaned book is overdue. Open **catalog/models.py**, and import the `settings` from `django.conf` (add this just below the previous import line at the top of the file, so the settings are available to subsequent code that makes use of them): ```python from django.conf import settings ``` Next, add the `borrower` field to the `BookInstance` model, setting the user model for the key as the value of the setting `AUTH_USER_MODEL`. Since we have not overridden the setting with a custom user model this maps to the default `User` model from `django.contrib.auth.models`. ```python borrower = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True) ``` **Note:** Importing the model in this way reduces the work required if you later discover that you need a custom user model. This tutorial uses the default model, so you could instead import the `User` model directly with the following lines: ```python from django.contrib.auth.models import User ``` ```python borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) ``` While we're here, let's add a property that we can call from our templates to tell if a particular book instance is overdue. While we could calculate this in the template itself, using a property as shown below will be much more efficient. Add this somewhere near the top of the file: ```python from datetime import date ``` Now add the following property definition to the `BookInstance` class: **Note:** The following code uses Python's `bool()` function, which evaluates an object or the resulting object of an expression, and returns `True` unless the result is "falsy", in which case it returns `False`. In Python an object is *falsy* (evaluates as `False`) if it is: empty (like `[]`, `()`, `{}`), `0`, `None` or if it is `False`. ```python @property def is\_overdue(self): """Determines if the book is overdue based on due date and current date.""" return bool(self.due_back and date.today() > self.due_back) ``` **Note:** We first verify whether `due_back` is empty before making a comparison. An empty `due_back` field would cause Django to throw an error instead of showing the page: empty values are not comparable. This is not something we would want our users to experience! Now that we've updated our models, we'll need to make fresh migrations on the project and then apply those migrations: ```bash python3 manage.py makemigrations python3 manage.py migrate ``` ### Admin Now open **catalog/admin.py**, and add the `borrower` field to the `BookInstanceAdmin` class in both the `list_display` and the `fieldsets` as shown below. This will make the field visible in the Admin section, allowing us to assign a `User` to a `BookInstance` when needed. ```python @admin.register(BookInstance) class BookInstanceAdmin(admin.ModelAdmin): list_display = ('book', 'status', 'borrower', 'due\_back', 'id') list_filter = ('status', 'due\_back') fieldsets = ( (None, { 'fields': ('book', 'imprint', 'id') }), ('Availability', { 'fields': ('status', 'due\_back', 'borrower') }), ) ``` ### Loan a few books Now that it's possible to loan books to a specific user, go and loan out a number of `BookInstance` records. Set their `borrowed` field to your test user, make the `status` "On loan", and set due dates both in the future and the past. **Note:** We won't spell the process out, as you already know how to use the Admin site! ### On loan view Now we'll add a view for getting the list of all books that have been loaned to the current user. We'll use the same generic class-based list view we're familiar with, but this time we'll also import and derive from `LoginRequiredMixin`, so that only a logged in user can call this view. We will also choose to declare a `template_name`, rather than using the default, because we may end up having a few different lists of BookInstance records, with different views and templates. Add the following to catalog/views.py: ```python from django.contrib.auth.mixins import LoginRequiredMixin class LoanedBooksByUserListView(LoginRequiredMixin,generic.ListView): """Generic class-based view listing books on loan to current user.""" model = BookInstance template_name = 'catalog/bookinstance\_list\_borrowed\_user.html' paginate_by = 10 def get\_queryset(self): return ( BookInstance.objects.filter(borrower=self.request.user) .filter(status__exact='o') .order_by('due\_back') ) ``` In order to restrict our query to just the `BookInstance` objects for the current user, we re-implement `get_queryset()` as shown above. Note that "o" is the stored code for "on loan" and we order by the `due_back` date so that the oldest items are displayed first. ### URL conf for on loan books Now open **/catalog/urls.py** and add a `path()` pointing to the above view (you can just copy the text below to the end of the file). ```python urlpatterns += [ path('mybooks/', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'), ] ``` ### Template for on-loan books Now, all we need to do for this page is add a template. First, create the template file **/catalog/templates/catalog/bookinstance\_list\_borrowed\_user.html** and give it the following contents: ```django {% extends "base\_generic.html" %} {% block content %} <h1>Borrowed books</h1> {% if bookinstance\_list %} <ul> {% for bookinst in bookinstance\_list %} <li class="{% if bookinst.is\_overdue %}text-danger{% endif %}"> <a href="{% url 'book-detail' bookinst.book.pk %}">{{ bookinst.book.title }}</a> ({{ bookinst.due\_back }}) </li> {% endfor %} </ul> {% else %} <p>There are no books borrowed.</p> {% endif %} {% endblock %} ``` This template is very similar to those we've created previously for the `Book` and `Author` objects. The only "new" thing here is that we check the method we added in the model `(bookinst.is_overdue`) and use it to change the color of overdue items. When the development server is running, you should now be able to view the list for a logged in user in your browser at `http://127.0.0.1:8000/catalog/mybooks/`. Try this out with your user logged in and logged out (in the second case, you should be redirected to the login page). ### Add the list to the sidebar The very last step is to add a link for this new page into the sidebar. We'll put this in the same section where we display other information for the logged in user. Open the base template (**/locallibrary/catalog/templates/base\_generic.html**) and add the "My Borrowed" line to the sidebar in the position shown below. ```django <ul class="sidebar-nav"> {% if user.is\_authenticated %} <li>User: {{ user.get\_username }}</li> <li><a href="{% url 'my-borrowed' %}">My Borrowed</a></li> <li><a href="{% url 'logout' %}?next={{ request.path }}">Logout</a></li> {% else %} <li><a href="{% url 'login' %}?next={{ request.path }}">Login</a></li> {% endif %} </ul> ``` ### What does it look like? When any user is logged in, they'll see the *My Borrowed* link in the sidebar, and the list of books displayed as below (the first book has no due date, which is a bug we hope to fix in a later tutorial!). ![Library - borrowed books by user](/en-US/docs/Learn/Server-side/Django/Authentication/library_borrowed_by_user.png) Permissions ----------- Permissions are associated with models and define the operations that can be performed on a model instance by a user who has the permission. By default, Django automatically gives *add*, *change*, and *delete* permissions to all models, which allow users with the permissions to perform the associated actions via the admin site. You can define your own permissions to models and grant them to specific users. You can also change the permissions associated with different instances of the same model. Testing on permissions in views and templates is then very similar to testing on the authentication status (and in fact, testing for a permission also tests for authentication). ### Models Defining permissions is done on the model "`class Meta`" section, using the `permissions` field. You can specify as many permissions as you need in a tuple, each permission itself being defined in a nested tuple containing the permission name and permission display value. For example, we might define a permission to allow a user to mark that a book has been returned as shown: ```python class BookInstance(models.Model): # … class Meta: # … permissions = (("can\_mark\_returned", "Set book as returned"),) ``` We could then assign the permission to a "Librarian" group in the Admin site. Open the **catalog/models.py**, and add the permission as shown above. You will need to re-run your migrations (call `python3 manage.py makemigrations` and `python3 manage.py migrate`) to update the database appropriately. ### Templates The current user's permissions are stored in a template variable called `{{ perms }}`. You can check whether the current user has a particular permission using the specific variable name within the associated Django "app" — e.g. `{{ perms.catalog.can_mark_returned }}` will be `True` if the user has this permission, and `False` otherwise. We typically test for the permission using the template `{% if %}` tag as shown: ```django {% if perms.catalog.can\_mark\_returned %} <!-- We can mark a BookInstance as returned. --> <!-- Perhaps add code to link to a "book return" view here. --> {% endif %} ``` ### Views Permissions can be tested in function view using the `permission_required` decorator or in a class-based view using the `PermissionRequiredMixin`. The pattern are the same as for login authentication, though of course, you might reasonably have to add multiple permissions. Function view decorator: ```python from django.contrib.auth.decorators import permission_required @permission\_required('catalog.can\_mark\_returned') @permission\_required('catalog.can\_edit') def my\_view(request): # … ``` A permission-required mixin for class-based views. ```python from django.contrib.auth.mixins import PermissionRequiredMixin class MyView(PermissionRequiredMixin, View): permission_required = 'catalog.can\_mark\_returned' # Or multiple permissions permission_required = ('catalog.can\_mark\_returned', 'catalog.change\_book') # Note that 'catalog.change\_book' is permission # Is created automatically for the book model, along with add\_book, and delete\_book ``` **Note:** There is a small default difference in the behavior above. By **default** for a logged-in user with a permission violation: * `@permission_required` redirects to login screen (HTTP Status 302). * `PermissionRequiredMixin` returns 403 (HTTP Status Forbidden). Normally you will want the `PermissionRequiredMixin` behavior: return 403 if a user is logged in but does not have the correct permission. To do this for a function view use `@login_required` and `@permission_required` with `raise_exception=True` as shown: ```python from django.contrib.auth.decorators import login_required, permission_required @login\_required @permission\_required('catalog.can\_mark\_returned', raise_exception=True) def my\_view(request): # … ``` ### Example We won't update the *LocalLibrary* here; perhaps in the next tutorial! Challenge yourself ------------------ Earlier in this article, we showed you how to create a page for the current user, listing the books that they have borrowed. The challenge now is to create a similar page that is only visible for librarians, that displays *all* books that have been borrowed, and which includes the name of each borrower. You should be able to follow the same pattern as for the other view. The main difference is that you'll need to restrict the view to only librarians. You could do this based on whether the user is a staff member (function decorator: `staff_member_required`, template variable: `user.is_staff`) but we recommend that you instead use the `can_mark_returned` permission and `PermissionRequiredMixin`, as described in the previous section. **Warning:** Remember not to use your superuser for permissions based testing (permission checks always return true for superusers, even if a permission has not yet been defined!). Instead, create a librarian user, and add the required capability. When you are finished, your page should look something like the screenshot below. ![All borrowed books, restricted to librarian](/en-US/docs/Learn/Server-side/Django/Authentication/library_borrowed_all.png) Summary ------- Excellent work — you've now created a website where library members can log in and view their own content, and where librarians (with the correct permission) can view all loaned books and their borrowers. At the moment we're still just viewing content, but the same principles and techniques are used when you want to start modifying and adding data. In our next article, we'll look at how you can use Django forms to collect user input, and then start modifying some of our stored data. See also -------- * User authentication in Django (Django docs) * Using the (default) Django authentication system (Django docs) * Introduction to class-based views > Decorating class-based views (Django docs) * Previous * Overview: Django * Next
Django Tutorial Part 2: Creating a skeleton website - Learn web development
Django Tutorial Part 2: Creating a skeleton website =================================================== * Previous * Overview: Django * Next This second article in our Django Tutorial shows how you can create a "skeleton" website project as a basis, which you can then populate with site-specific settings, paths, models, views, and templates. | | | | --- | --- | | Prerequisites: | Set up a Django development environment. Review the Django Tutorial. | | Objective: | To be able to use Django's tools to start your own new website projects. | Overview -------- This article shows how you can create a "skeleton" website, which you can then populate with site-specific settings, paths, models, views, and templates (we discuss these in later articles). To get started: 1. Use the `django-admin` tool to generate a project folder, the basic file templates, and **manage.py**, which serves as your project management script. 2. Use **manage.py** to create one or more *applications*. **Note:** A website may consist of one or more sections. For example, main site, blog, wiki, downloads area, etc. Django encourages you to develop these components as separate *applications*, which could then be re-used in different projects if desired. 3. Register the new applications to include them in the project. 4. Hook up the **url/path** mapper for each application. For the Local Library website, the website and project folders are named *locallibrary*, and includes one application named *catalog*. The top-level folder structure will therefore be as follows: ```bash locallibrary/ # Website folder manage.py # Script to run Django tools for this project (created using django-admin) locallibrary/ # Website/project folder (created using django-admin) catalog/ # Application folder (created using manage.py) ``` The following sections discuss the process steps in detail, and show how you can test your changes. At the end of this article, we discuss other site-wide configuration you might also do at this stage. Creating the project -------------------- To create the project: 1. Open a command shell (or a terminal window), and make sure you are in your virtual environment. 2. Navigate to where you want to store your Django apps (make it somewhere easy to find like inside your *Documents* folder), and create a folder for your new website (in this case: *django\_projects*). Then change into your newly-created directory: ```bash mkdir django_projects cd django_projects ``` 3. Create the new project using the `django-admin startproject` command as shown, and then change into the project folder: ```bash django-admin startproject locallibrary cd locallibrary ``` The `django-admin` tool creates a folder/file structure as follows: ```bash locallibrary/ manage.py locallibrary/ __init__.py settings.py urls.py wsgi.py asgi.py ``` Our current working directory should look something like this: ```python ../django_projects/locallibrary/ ``` The *locallibrary* project sub-folder is the entry point for the website: * **\_\_init\_\_.py** is an empty file that instructs Python to treat this directory as a Python package. * **settings.py** contains all the website settings, including registering any applications we create, the location of our static files, database configuration details, etc. * **urls.py** defines the site URL-to-view mappings. While this could contain *all* the URL mapping code, it is more common to delegate some of the mappings to particular applications, as you'll see later. * **wsgi.py** is used to help your Django application communicate with the web server. You can treat this as boilerplate. * **asgi.py** is a standard for Python asynchronous web apps and servers to communicate with each other. Asynchronous Server Gateway Interface (ASGI) is the asynchronous successor to Web Server Gateway Interface (WSGI). ASGI provides a standard for both asynchronous and synchronous Python apps, whereas WSGI provided a standard for synchronous apps only. ASGI is backward-compatible with WSGI and supports multiple servers and application frameworks. The **manage.py** script is used to create applications, work with databases, and start the development web server. Creating the catalog application -------------------------------- Next, run the following command to create the *catalog* application that will live inside our *locallibrary* project. Make sure to run this command from the same folder as your project's **manage.py**: ```bash # Linux/macOS python3 manage.py startapp catalog # Windows py manage.py startapp catalog ``` **Note:** The rest of the tutorial uses the Linux/macOS syntax. If you're working on Windows, wherever you see a command starting with `python3` you should instead use `py` (or `py -3`). The tool creates a new folder and populates it with files for the different parts of the application (shown in the following example). Most of the files are named after their purpose (e.g. views should be stored in **views.py**, models in **models.py**, tests in **tests.py**, administration site configuration in **admin.py**, application registration in **apps.py**) and contain some minimal boilerplate code for working with the associated objects. The updated project directory should now look like this: ```bash locallibrary/ manage.py locallibrary/ catalog/ admin.py apps.py models.py tests.py views.py __init__.py migrations/ ``` In addition we now have: * A *migrations* folder, used to store "migrations" — files that allow you to automatically update your database as you modify your models. * **\_\_init\_\_.py** — an empty file created here so that Django/Python will recognize the folder as a Python Package and allow you to use its objects within other parts of the project. **Note:** Have you noticed what is missing from the files list above? While there is a place for your views and models, there is nowhere for you to put your URL mappings, templates, and static files. We'll show you how to create them further along (these aren't needed in every website but they are needed in this example). Registering the catalog application ----------------------------------- Now that the application has been created, we have to register it with the project so that it will be included when any tools are run (like adding models to the database for example). Applications are registered by adding them to the `INSTALLED_APPS` list in the project settings. Open the project settings file, **django\_projects/locallibrary/locallibrary/settings.py**, and find the definition for the `INSTALLED_APPS` list. Then add a new line at the end of the list, as shown below: ```bash INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Add our new application 'catalog.apps.CatalogConfig', #This object was created for us in /catalog/apps.py ] ``` The new line specifies the application configuration object (`CatalogConfig`) that was generated for you in **/locallibrary/catalog/apps.py** when you created the application. **Note:** You'll notice that there are already a lot of other `INSTALLED_APPS` (and `MIDDLEWARE`, further down in the settings file). These enable support for the Django administration site and the functionality it uses (including sessions, authentication, etc.). Specifying the database ----------------------- This is also the point where you would normally specify the database to be used for the project. It makes sense to use the same database for development and production where possible, in order to avoid minor differences in behavior. You can find out about the different options in Databases (Django docs). We'll use the default SQLite database for this example, because we don't expect to require a lot of concurrent access on a demonstration database, and it requires no additional work to set up! You can see how this database is configured in **settings.py**: ```python DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } ``` Because we are using SQLite, we don't need to do any further setup here. Let's move on! Other project settings ---------------------- The **settings.py** file is also used for configuring a number of other settings, but at this point, you probably only want to change the TIME\_ZONE — this should be made equal to a string from the standard List of tz database time zones (the TZ column in the table contains the values you want). Change your `TIME_ZONE` value to one of these strings appropriate for your time zone, for example: ```python TIME_ZONE = 'Europe/London' ``` There are two other settings you won't change now, but that you should be aware of: * `SECRET_KEY`. This is a secret key that is used as part of Django's website security strategy. If you're not protecting this code in development, you'll need to use a different code (perhaps read from an environment variable or file) when putting it into production. * `DEBUG`. This enables debugging logs to be displayed on error, rather than HTTP status code responses. This should be set to `False` in production as debug information is useful for attackers, but for now we can keep it set to `True`. Hooking up the URL mapper ------------------------- The website is created with a URL mapper file (**urls.py**) in the project folder. While you can use this file to manage all your URL mappings, it is more usual to defer mappings to the associated application. Open **locallibrary/locallibrary/urls.py** and note the instructional text which explains some of the ways to use the URL mapper. ```python """ URL configuration for locallibrary project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.2/topics/http/urls/ Examples: Function views 1. Add an import: from my\_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other\_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as\_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] ``` The URL mappings are managed through the `urlpatterns` variable, which is a Python *list* of `path()` functions. Each `path()` function either associates a URL pattern to a *specific view*, which will be displayed when the pattern is matched, or with another list of URL pattern testing code (in this second case, the pattern becomes the "base URL" for patterns defined in the target module). The `urlpatterns` list initially defines a single function that maps all URLs with the pattern *admin/* to the module `admin.site.urls`, which contains the Administration application's own URL mapping definitions. **Note:** The route in `path()` is a string defining a URL pattern to match. This string might include a named variable (in angle brackets), e.g. `'catalog/<id>/'`. This pattern will match a URL like **catalog/*any\_chars*/** and pass *`any_chars`* to the view as a string with the parameter name `id`. We discuss path methods and route patterns further in later topics. To add a new list item to the `urlpatterns` list, add the following lines to the bottom of the file. This new item includes a `path()` that forwards requests with the pattern `catalog/` to the module `catalog.urls` (the file with the relative URL **catalog/urls.py**). ```python # Use include() to add paths from the catalog application from django.urls import include urlpatterns += [ path('catalog/', include('catalog.urls')), ] ``` **Note:** Note that we included the import line (`from django.urls import include`) with the code that uses it (so it is easy to see what we've added), but it is common to include all your import lines at the top of a Python file. Now let's redirect the root URL of our site (i.e. `127.0.0.1:8000`) to the URL `127.0.0.1:8000/catalog/`. This is the only app we'll be using in this project. To do this, we'll use a special view function, `RedirectView`, which takes the new relative URL to redirect to (`/catalog/`) as its first argument when the URL pattern specified in the `path()` function is matched (the root URL, in this case). Add the following lines to the bottom of the file: ```python #Add URL maps to redirect the base URL to our application from django.views.generic import RedirectView urlpatterns += [ path('', RedirectView.as_view(url='catalog/', permanent=True)), ] ``` Leave the first parameter of the path function empty to imply '/'. If you write the first parameter as '/' Django will give you the following warning when you start the development server: ```python System check identified some issues: WARNINGS: ?: (urls.W002) Your URL pattern '/' has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'. ``` Django does not serve static files like CSS, JavaScript, and images by default, but it can be useful for the development web server to do so while you're creating your site. As a final addition to this URL mapper, you can enable the serving of static files during development by appending the following lines. Add the following final block to the bottom of the file now: ```python # Use static() to add URL mapping to serve static files during development (only) from django.conf import settings from django.conf.urls.static import static urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ``` **Note:** There are a number of ways to extend the `urlpatterns` list (previously, we just appended a new list item using the `+=` operator to clearly separate the old and new code). We could have instead just included this new pattern-map in the original list definition: ```python urlpatterns = [ path('admin/', admin.site.urls), path('catalog/', include('catalog.urls')), path('', RedirectView.as_view(url='catalog/')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ``` As a final step, create a file inside your catalog folder called **urls.py**, and add the following text to define the (empty) imported `urlpatterns`. This is where we'll add our patterns as we build the application. ```python from django.urls import path from . import views urlpatterns = [ ] ``` Testing the website framework ----------------------------- At this point we have a complete skeleton project. The website doesn't actually *do* anything yet, but it's worth running it to make sure that none of our changes have broken anything. Before we do that, we should first run a *database migration*. This updates our database (to include any models in our installed applications) and removes some build warnings. ### Running database migrations Django uses an Object-Relational-Mapper (ORM) to map model definitions in the Django code to the data structure used by the underlying database. As we change our model definitions, Django tracks the changes and can create database migration scripts (in **/locallibrary/catalog/migrations/**) to automatically migrate the underlying data structure in the database to match the model. When we created the website, Django automatically added a number of models for use by the admin section of the site (which we'll look at later). Run the following commands to define tables for those models in the database (make sure you are in the directory that contains **manage.py**): ```bash python3 manage.py makemigrations python3 manage.py migrate ``` **Warning:** You'll need to run these commands every time your models change in a way that will affect the structure of the data that needs to be stored (including both addition and removal of whole models and individual fields). The `makemigrations` command *creates* (but does not apply) the migrations for all applications installed in your project. You can specify the application name as well to just run a migration for a single app. This gives you a chance to check out the code for these migrations before they are applied. If you're a Django expert, you may choose to tweak them slightly! The `migrate` command is what applies the migrations to your database. Django tracks which ones have been added to the current database. **Note:** See Migrations (Django docs) for additional information about the lesser-used migration commands. ### Running the website During development, you can serve the website first using the *development web server*, and then viewing it on your local web browser. **Note:** The development web server is not robust or performant enough for production use, but it is a very easy way to get your Django website up and running during development to give it a convenient quick test. By default it will serve the site to your local computer (`http://127.0.0.1:8000/)`, but you can also specify other computers on your network to serve to. For more information see django-admin and manage.py: runserver (Django docs). Run the *development web server* by calling the `runserver` command (in the same directory as **manage.py**): ```bash python3 manage.py runserver ``` Once the server is running, you can view the site by navigating to `http://127.0.0.1:8000/` in your local web browser. You should see a site error page that looks like this: ![Django Debug page (Django 4.2)](/en-US/docs/Learn/Server-side/Django/skeleton_website/django_404_debug_page.png) Don't worry! This error page is expected because we don't have any pages/urls defined in the `catalog.urls` module (which we're redirected to when we get a URL to the root of the site). **Note:** The example page demonstrates a great Django feature — automated debug logging. Whenever a page cannot be found, Django displays an error screen with useful information or any error raised by the code. In this case, we can see that the URL we've supplied doesn't match any of our URL patterns (as listed). Logging is turned off in production (which is when we put the site live on the Web), in which case a less informative but more user-friendly page will be served. At this point, we know that Django is working! **Note:** You should re-run migrations and re-test the site whenever you make significant changes. It doesn't take very long! Challenge yourself ------------------ The **catalog/** directory contains files for the views, models, and other parts of the application. Open these files and inspect the boilerplate. As you saw previously, a URL-mapping for the Admin site has already been added in the project's **urls.py**. Navigate to the admin area in your browser and see what happens (you can infer the correct URL from the mapping). Summary ------- You have now created a complete skeleton website project, which you can go on to populate with URLs, models, views, and templates. Now that the skeleton for the Local Library website is complete and running, it's time to start writing the code that makes this website do what it is supposed to do. See also -------- * Writing your first Django app - part 1 (Django docs) * Applications (Django Docs). Contains information on configuring applications. * Previous * Overview: Django * Next
CSS property compatibility table for form controls - Learn web development
CSS property compatibility table for form controls ================================================== The following compatibility tables try to summarize the state of CSS support for HTML forms. Due to the complexity of CSS and HTML forms, these tables can't be considered a perfect reference. However, they will give you good insight into what can and can't be done, which will help you learn how to do things. How to read the tables ---------------------- ### Values For each property, there are four possible values: ✅ Yes There's reasonably consistent support for the property across browsers. You may still face strange side effects in certain edge cases. ⚠️ Partial While the property works, you may frequently face strange side effects or inconsistencies. You should probably avoid these properties unless you master those side effects first. ❌ No The property doesn't work or is so inconsistent that it's not reliable. n.a. The property has no meaning for this type of widget. ### Rendering For each property there are two possible renderings: N (Normal) Indicates that the property is applied as it is T (Tweaked) Indicates that the property is applied with the extra rule below: ```css \* { /\* Turn off the native look and feel \*/ appearance: none; } ``` Compatibility tables -------------------- Altering the appearance of form controls with CSS, such as with `border`, `background`, `border-radius`, and `height` can partially or fully turn off the native look & feel of widgets on some browsers. Be careful when you use them. ### Text fields See the `text`, `search`, and `password` input types. | Property | N | T | Note | | --- | --- | --- | --- | | *CSS box model* | | --- | | `width` | ✅ Yes | ✅ Yes | | | `height` | ⚠️ Partial[1] | ✅ Yes | 1. WebKit browsers (mostly on Mac OSX and iOS) use the native look & feel for the search fields. Therefore, it's required to use `appearance:none` to be able to apply this property to search fields. | | `border` | ⚠️ Partial[1] | ✅ Yes | 1. WebKit browsers (mostly on Mac OSX and iOS) use the native look & feel for the search fields. Therefore, it's required to use `appearance:none` to be able to apply this property to search fields. | | `margin` | ✅ Yes | ✅ Yes | | | `padding` | ⚠️ Partial[1] | ✅ Yes | 1. WebKit browsers (mostly on Mac OSX and iOS) use the native look & feel for the search fields. Therefore, it's required to use `appearance:none` to be able to apply this property to search fields. | | *Text and font* | | --- | | `color`[1] | ✅ Yes | ✅ Yes | 1. If the `border-color` property is not set, some WebKit based browsers will apply the `color` property to the border as well as the font on ``<textarea>``s. | | `font` | ✅ Yes | ✅ Yes | See the note about `line-height` | | `letter-spacing` | ✅ Yes | ✅ Yes | | | `text-align` | ✅ Yes | ✅ Yes | | | `text-decoration` | ⚠️ Partial | ⚠️ Partial | See the note about Opera | | `text-indent` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. IE9 supports this property only on ``<textarea>``s, whereas Opera only supports it on single line text fields. | | `text-overflow` | ⚠️ Partial | ⚠️ Partial | | | `text-shadow` | ⚠️ Partial | ⚠️ Partial | | | `text-transform` | ✅ Yes | ✅ Yes | | | *Border and background* | | --- | | `background` | ⚠️ Partial[1] | ✅ Yes | 1. WebKit browsers (mostly on Mac OSX and iOS) use the native look & feel for the search fields. Therefore, it's required to use `-webkit-appearance:none` to be able to apply this property to search fields. | | `border-radius` | ⚠️ Partial[1] | ✅ Yes | 1. WebKit browsers (mostly on Mac OSX and iOS) use the native look & feel for the search fields. Therefore, it's required to use `-webkit-appearance:none` to be able to apply this property to search fields. | | `box-shadow` | ❌ No | ⚠️ Partial[1] | 1. IE9 does not support this property. | ### Buttons See the `button`, `submit`, and `reset` input types and the ``<button>`` element. | Property | N | T | Note | | --- | --- | --- | --- | | *CSS box model* | | --- | | `width` | ✅ Yes | ✅ Yes | | | `height` | ⚠️ Partial[1] | ✅ Yes | 1. This property is not applied on WebKit based browsers on Mac OSX or iOS. | | `border` | ⚠️ Partial | ✅ Yes | | | `margin` | ✅ Yes | ✅ Yes | | | `padding` | ⚠️ Partial[1] | ✅ Yes | 1. This property is not applied on WebKit based browsers on Mac OSX or iOS. | | *Text and font* | | --- | | `color` | ✅ Yes | ✅ Yes | | | `font` | ✅ Yes | ✅ Yes | See the note about `line-height`. | | `letter-spacing` | ✅ Yes | ✅ Yes | | | `text-align` | ❌ No | ❌ No | | | `text-decoration` | ⚠️ Partial | ✅ Yes | | | `text-indent` | ✅ Yes | ✅ Yes | | | `text-overflow` | ❌ No | ❌ No | | | `text-shadow` | ⚠️ Partial | ⚠️ Partial | | | `text-transform` | ✅ Yes | ✅ Yes | | | *Border and background* | | --- | | `background` | ✅ Yes | ✅ Yes | | | `border-radius` | ✅ Yes[1] | ✅ Yes[1] | 1. On Opera the `border-radius` property is applied only if an explicit border is set. | | `box-shadow` | ❌ No | ⚠️ Partial[1] | 1. IE9 does not support this property. | ### Number See the `number` input type. There is no standard way to change the style of spinners used to change the value of the field, with the spinners on Safari being outside the field. | Property | N | T | Note | | --- | --- | --- | --- | | *CSS box model* | | --- | | `width` | ✅ Yes | ✅ Yes | | | `height` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. On Opera, the spinners are zoomed in, which can hide the content of the field. | | `border` | ✅ Yes | ✅ Yes | | | `margin` | ✅ Yes | ✅ Yes | | | `padding` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. On Opera, the spinners are zoomed in, which can hide the content of the field. | | *Text and font* | | --- | | `color` | ✅ Yes | ✅ Yes | | | `font` | ✅ Yes | ✅ Yes | See the note about `line-height`. | | `letter-spacing` | ✅ Yes | ✅ Yes | | | `text-align` | ✅ Yes | ✅ Yes | | | `text-decoration` | ⚠️ Partial | ⚠️ Partial | | | `text-indent` | ✅ Yes | ✅ Yes | | | `text-overflow` | ❌ No | ❌ No | | | `text-shadow` | ⚠️ Partial | ⚠️ Partial | | | `text-transform` | N.A. | N.A. | | | *Border and background* | | --- | | `background` | ❌ No | ❌ No | Supported but there is too much inconsistency between browsers to be reliable. | | `border-radius` | ❌ No | ❌ No | | `box-shadow` | ❌ No | ❌ No | ### Check boxes and radio buttons See the `checkbox` and `radio` input types. | Property | N | T | Note | | --- | --- | --- | --- | | *CSS box model* | | --- | | `width` | ❌ No[1] | ❌ No[1] | 1. Some browsers add extra margins and others stretch the widget. | | `height` | ❌ No[1] | ❌ No[1] | 1. Some browsers add extra margins and others stretch the widget. | | `border` | ❌ No | ❌ No | | | `margin` | ✅ Yes | ✅ Yes | | | `padding` | ❌ No | ❌ No | | | *Text and font* | | --- | | `color` | N.A. | N.A. | | | `font` | N.A. | N.A. | | | `letter-spacing` | N.A. | N.A. | | | `text-align` | N.A. | N.A. | | | `text-decoration` | N.A. | N.A. | | | `text-indent` | N.A. | N.A. | | | `text-overflow` | N.A. | N.A. | | | `text-shadow` | N.A. | N.A. | | | `text-transform` | N.A. | N.A. | | | *Border and background* | | --- | | `background` | ❌ No | ❌ No | | | `border-radius` | ❌ No | ❌ No | | | `box-shadow` | ❌ No | ❌ No | | ### Select boxes (single line) See the ``<select>``, ``<optgroup>`` and ``<option>`` elements. | Property | N | T | Note | | --- | --- | --- | --- | | *CSS box model* | | --- | | `width` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. This property is okay on the ``<select>`` element, but it cannot be the case on the ``<option>`` or ``<optgroup>`` elements. | | `height` | ❌ No | ✅ Yes | | | `border` | ⚠️ Partial | ✅ Yes | | | `margin` | ✅ Yes | ✅ Yes | | | `padding` | ❌ No[1] | ⚠️ Partial[2] | 1. The property is applied, but in an inconsistent way between browsers on Mac OSX. 2. The property is well applied on the ``<select>`` element, but is inconsistently handled on ``<option>`` and ``<optgroup>`` elements. | | *Text and font* | | --- | | `color` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. On Mac OSX, WebKit based browsers do not support this property on native widgets and they, along with Opera, do not support it at all on ``<option>`` and ``<optgroup>`` elements. | | `font` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. On Mac OSX, WebKit based browsers do not support this property on native widgets and they, along with Opera, do not support it at all on ``<option>`` and ``<optgroup>`` elements. | | `letter-spacing` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. IE9 does not support this property on ``<select>``, ``<option>``, and ``<optgroup>`` elements; WebKit based browsers on Mac OSX do not support this property on ``<option>`` and ``<optgroup>`` elements. | | `text-decoration` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. Only Firefox provides full support for this property. Other browsers only support it on the ``<select>`` element. | | `text-indent` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. Most of the browsers only support this property on the ``<select>`` element. | | `text-overflow` | ❌ No | ❌ No | | | `text-shadow` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. Most of the browsers only support this property on the ``<select>`` element. | | `text-transform` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. Most of the browsers only support this property on the ``<select>`` element. | | *Border and background* | | --- | | `background` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. Most of the browsers only support this property on the ``<select>`` element. | | `border-radius` | ⚠️ Partial[1] | ⚠️ Partial[1] | | `box-shadow` | ❌ No | ⚠️ Partial[1] | Note Firefox does not provide any way to change the down arrow on the ``<select>`` element. ### Select boxes (multiline) See the ``<select>``, ``<optgroup>`` and ``<option>`` elements and the `size` attribute. | Property | N | T | Note | | --- | --- | --- | --- | | *CSS box model* | | --- | | `width` | ✅ Yes | ✅ Yes | | | `height` | ✅ Yes | ✅ Yes | | | `border` | ✅ Yes | ✅ Yes | | | `margin` | ✅ Yes | ✅ Yes | | | `padding` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. Opera does not support `padding-top` and `padding-bottom` on the ``<select>`` element. | | *Text and font* | | --- | | `color` | ✅ Yes | ✅ Yes | | | `font` | ✅ Yes | ✅ Yes | See the note about `line-height`. | | `letter-spacing` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. IE9 does not support this property on ``<select>``, ``<option>``, and ``<optgroup>`` elements; WebKit based browsers on Mac OSX do not support this property on ``<option>`` and ``<optgroup>`` elements. | | `text-align` | ❌ No[1] | ❌ No[1] | 1. WebKit based browser on Mac OSX do not support this property on this widget. | | `text-decoration` | ❌ No[1] | ❌ No[1] | 1. Only supported by Firefox and IE9+. | | `text-indent` | ❌ No | ❌ No | | | `text-overflow` | ❌ No | ❌ No | | | `text-shadow` | ❌ No | ❌ No | | | `text-transform` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. Most of the browsers only support this property on the ``<select>`` element. | | *Border and background* | | --- | | `background` | ✅ Yes | ✅ Yes | | | `border-radius` | ✅ Yes[1] | ✅ Yes[1] | 1. On Opera the `border-radius` property is applied only if an explicit border is set. | | `box-shadow` | ❌ No | ⚠️ Partial[1] | 1. IE9 does not support this property. | ### Datalist See the ``<datalist>`` and ``<input>`` elements and the `list` attribute. | Property | N | T | Note | | --- | --- | --- | --- | | *CSS box model* | | --- | | `width` | ❌ No | ❌ No | | | `height` | ❌ No | ❌ No | | | `border` | ❌ No | ❌ No | | | `margin` | ❌ No | ❌ No | | | `padding` | ❌ No | ❌ No | | | *Text and font* | | --- | | `color` | ❌ No | ❌ No | | | `font` | ❌ No | ❌ No | | | `letter-spacing` | ❌ No | ❌ No | | | `text-align` | ❌ No | ❌ No | | | `text-decoration` | ❌ No | ❌ No | | | `text-indent` | ❌ No | ❌ No | | | `text-overflow` | ❌ No | ❌ No | | | `text-shadow` | ❌ No | ❌ No | | | `text-transform` | ❌ No | ❌ No | | | *Border and background* | | --- | | `background` | ❌ No | ❌ No | | | `border-radius` | ❌ No | ❌ No | | | `box-shadow` | ❌ No | ❌ No | | ### File picker See the `file` input type. | Property | N | T | Note | | --- | --- | --- | --- | | *CSS box model* | | --- | | `width` | ❌ No | ❌ No | | | `height` | ❌ No | ❌ No | | | `border` | ❌ No | ❌ No | | | `margin` | ✅ Yes | ✅ Yes | | | `padding` | ❌ No | ❌ No | | | *Text and font* | | --- | | `color` | ✅ Yes | ✅ Yes | | | `font` | ❌ No[1] | ❌ No[1] | 1. Supported, but there is too much inconsistency between browsers to be reliable. | | `letter-spacing` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. Many browsers apply this property to the select button. | | `text-align` | ❌ No | ❌ No | | | `text-decoration` | ❌ No | ❌ No | | | `text-indent` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. It acts more or less like an extra left margin outside the widget. | | `text-overflow` | ❌ No | ❌ No | | | `text-shadow` | ❌ No | ❌ No | | | `text-transform` | ❌ No | ❌ No | | | *Border and background* | | --- | | `background` | ❌ No[1] | ❌ No[1] | 1. Supported, but there is too much inconsistency between browsers to be reliable. | | `border-radius` | ❌ No | ❌ No | | | `box-shadow` | ❌ No | ⚠️ Partial[1] | 1. IE9 does not support this property. | ### Date pickers See the `date` and `time` input types. Many properties are supported, but there is too much inconsistency between browsers to be reliable. | Property | N | T | Note | | --- | --- | --- | --- | | *CSS box model* | | --- | | `width` | ❌ No | ❌ No | | | `height` | ❌ No | ❌ No | | | `border` | ❌ No | ❌ No | | | `margin` | ✅ Yes | ✅ Yes | | | `padding` | ❌ No | ❌ No | | | *Text and font* | | --- | | `color` | ❌ No | ❌ No | | | `font` | ❌ No | ❌ No | | | `letter-spacing` | ❌ No | ❌ No | | | `text-align` | ❌ No | ❌ No | | | `text-decoration` | ❌ No | ❌ No | | | `text-indent` | ❌ No | ❌ No | | | `text-overflow` | ❌ No | ❌ No | | | `text-shadow` | ❌ No | ❌ No | | | `text-transform` | ❌ No | ❌ No | | | *Border and background* | | --- | | `background` | ❌ No | ❌ No | | | `border-radius` | ❌ No | ❌ No | | | `box-shadow` | ❌ No | ❌ No | | ### Color pickers See the `color` input type: | Property | N | T | Note | | --- | --- | --- | --- | | *CSS box model* | | --- | | `width` | ✅ Yes | ✅ Yes | | | `height` | ❌ No[1] | ✅ Yes | 1. Opera handles this like a select widget with the same restriction. | | `border` | ✅ Yes | ✅ Yes | | | `margin` | ✅ Yes | ✅ Yes | | | `padding` | ❌ No[1] | ✅ Yes | 1. Opera handles this like a select widget with the same restriction. | | *Text and font* | | --- | | `color` | N.A. | N.A. | | | `font` | N.A. | N.A. | | | `letter-spacing` | N.A. | N.A. | | | `text-align` | N.A. | N.A. | | | `text-decoration` | N.A. | N.A. | | | `text-indent` | N.A. | N.A. | | | `text-overflow` | N.A. | N.A. | | | `text-shadow` | N.A. | N.A. | | | `text-transform` | N.A. | N.A. | | | *Border and background* | | --- | | `background` | ❌ No[1] | ❌ No[1] | 1. Supported, but there is too much inconsistency between browsers to be reliable. | | `border-radius` | ❌ No[1] | ❌ No[1] | | `box-shadow` | ❌ No[1] | ❌ No[1] | ### Meters and progress See the ``<meter>`` and ``<progress>`` elements: | Property | N | T | Note | | --- | --- | --- | --- | | *CSS box model* | | --- | | `width` | ✅ Yes | ✅ Yes | | | `height` | ✅ Yes | ✅ Yes | | | `border` | ⚠️ Partial | ✅ Yes | | | `margin` | ✅ Yes | ✅ Yes | | | `padding` | ✅ Yes | ⚠️ Partial[1] | 1. Chrome hides the ``<progress>`` and ``<meter>`` element when the `padding` property is applied on a tweaked element. | | *Text and font* | | --- | | `color` | N.A. | N.A. | | | `font` | N.A. | N.A. | | | `letter-spacing` | N.A. | N.A. | | | `text-align` | N.A. | N.A. | | | `text-decoration` | N.A. | N.A. | | | `text-indent` | N.A. | N.A. | | | `text-overflow` | N.A. | N.A. | | | `text-shadow` | N.A. | N.A. | | | `text-transform` | N.A. | N.A. | | | *Border and background* | | --- | | `background` | ❌ No[1] | ❌ No[1] | 1. Supported, but there is too much inconsistency between browsers to be reliable. | | `border-radius` | ❌ No[1] | ❌ No[1] | | `box-shadow` | ❌ No[1] | ❌ No[1] | ### Range See the `range` input type. There is no standard way to change the style of the range grip and Opera has no way to tweak the default rendering of the range widget. | Property | N | T | Note | | --- | --- | --- | --- | | *CSS box model* | | --- | | `width` | ✅ Yes | ✅ Yes | | | `height` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. Chrome and Opera add some extra space around the widget. | | `border` | ❌ No | ✅ Yes | | | `margin` | ✅ Yes | ✅ Yes | | | `padding` | ⚠️ Partial[1] | ✅ Yes | 1. The `padding` is applied, but has no visual effect. | | *Text and font* | | --- | | `color` | N.A. | N.A. | | | `font` | N.A. | N.A. | | | `letter-spacing` | N.A. | N.A. | | | `text-align` | N.A. | N.A. | | | `text-decoration` | N.A. | N.A. | | | `text-indent` | N.A. | N.A. | | | `text-overflow` | N.A. | N.A. | | | `text-shadow` | N.A. | N.A. | | | `text-transform` | N.A. | N.A. | | | *Border and background* | | --- | | `background` | ❌ No[1] | ❌ No[1] | 1. Supported, but there is too much inconsistency between browsers to be reliable. | | `border-radius` | ❌ No[1] | ❌ No[1] | | `box-shadow` | ❌ No[1] | ❌ No[1] | ### Image buttons See the `image` input type: | Property | N | T | Note | | --- | --- | --- | --- | | *CSS box model* | | --- | | `width` | ✅ Yes | ✅ Yes | | | `height` | ✅ Yes | ✅ Yes | | | `border` | ✅ Yes | ✅ Yes | | | `margin` | ✅ Yes | ✅ Yes | | | `padding` | ✅ Yes | ✅ Yes | | | *Text and font* | | --- | | `color` | N.A. | N.A. | | | `font` | N.A. | N.A. | | | `letter-spacing` | N.A. | N.A. | | | `text-align` | N.A. | N.A. | | | `text-decoration` | N.A. | N.A. | | | `text-indent` | N.A. | N.A. | | | `text-overflow` | N.A. | N.A. | | | `text-shadow` | N.A. | N.A. | | | `text-transform` | N.A. | N.A. | | | *Border and background* | | --- | | `background` | ✅ Yes | ✅ Yes | | | `border-radius` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. IE9 does not support this property. | | `box-shadow` | ⚠️ Partial[1] | ⚠️ Partial[1] | 1. IE9 does not support this property. | See also -------- ### Learning path * Your first HTML form * How to structure an HTML form * The native form widgets * HTML5 input types * Additional form controls * UI pseudo-classes * Styling HTML forms * Form data validation * Sending form data ### Advanced Topics * Sending forms through JavaScript * How to build custom form widgets * HTML forms in legacy browsers * Advanced styling for HTML forms * **Property compatibility table for form widgets**
Styling web forms - Learn web development
Styling web forms ================= * Previous * Overview: Forms * Next In the previous few articles, we showed how to create web forms in HTML. Now, we'll show how to style them in CSS. | | | | --- | --- | | Prerequisites: | A basic understanding of HTML and CSS. | | Objective: | To understand the issues behind styling forms, and learn some of the basic styling techniques that will be useful to you. | Challenges in styling form widgets ---------------------------------- ### History In 1995, the HTML 2 specification introduced form controls (a.k.a. "form widgets", or "form elements"). But CSS wasn't released until late 1996, and wasn't supported by most browsers until years afterward; so, in the interim, browsers relied on the underlying operating system to render form widgets. Even with CSS available, browser vendors were reluctant at first to make form elements stylable, because users were so accustomed to the looks of their respective browsers. But things have changed, and forms widgets are now mostly stylable, with a few exceptions. ### Types of widgets #### Easy-to-style 1. `<form>` 2. `<fieldset>` and `<legend>` 3. Single-line text `<input>`s (e.g. type text, url, email), except for `<input type="search">`. 4. Multi-line `<textarea>` 5. Buttons (both `<input>` and `<button>`) 6. `<label>` 7. `<output>` #### Harder-to-style * Checkboxes and radio buttons * `<input type="search">` The article Advanced form styling shows how to style these. #### Having internals can't be styled in CSS alone * `<input type="color">` * Date-related controls such as `<input type="datetime-local">` * `<input type="range">` * `<input type="file">` * Elements involved in creating dropdown widgets, including `<select>`, `<option>`, `<optgroup>` and `<datalist>`. * `<progress>` and `<meter>` For example, the date picker calendar, and the button on <select> that displays an options list when clicked, can't be styled using CSS alone. The articles Advanced form styling and How to build custom form controls describe how to style these. **Note:** some proprietary CSS pseudo-elements, such as `::-moz-range-track`, are capable of styling such internal components, but these aren't consistent across browsers, so aren't very reliable. We will mention these later. Styling simple form widgets --------------------------- The "easy-to-style" widgets in the previous section may be styled using techniques from the articles Your first form and CSS building blocks. There are also special selectors — UI pseudo-classes — that enable styling based on the current state of the UI. We'll walk through an example at the end of this article — but first, here are some special aspects of form styling that are worth knowing about. ### Fonts and text CSS font and text features can be used easily with any widget (and yes, you can use `@font-face` with form widgets). However, browser behavior is often inconsistent. By default, some widgets do not inherit `font-family` and `font-size` from their parents. Many browsers use the system's default appearance instead. To make your forms' appearance consistent with the rest of your content, you can add the following rules to your stylesheet: ```css button, input, select, textarea { font-family: inherit; font-size: 100%; } ``` The `inherit` property value causes the property value to match the computed value of the property of its parent element; inheriting the value of the parent. The screenshots below show the difference. On the left is the default rendering of an `<input type="text">`, `<input type="date">`, `<select>`, `<textarea>`, `<input type="submit">`, and a `<button>` in Chrome on macOS, with the platform's default font style in use. On the right are the same elements, with our above style rule applied. ![Form controls with default and inherited font families. By default, some types are serif and others are sans serif. Inheriting should change the fonts of all to the parent's font family - in this case a paragraph. Oddly, input of type submit does not inherit from the parent paragraph.](/en-US/docs/Learn/Forms/Styling_web_forms/forms_fontfamily.png) The defaults differed in a number of ways. Inheriting should change their fonts to that of the parent's font family — in this case, the default serif font of the parent container. They all do, with a strange exception — `<input type="submit">` does not inherit from the parent paragraph in Chrome. Rather, it uses the `font-family: system-ui`. This is another reason to use `<button>` elements over their equivalent input types! There's a lot of debate as to whether forms look better using the system default styles, or customized styles designed to match your content. This decision is yours to make, as the designer of your site, or web application. ### Box sizing All text fields have complete support for every property related to the CSS box model, such as `width`, `height`, `padding`, `margin`, and `border`. As before, however, browsers rely on the system default styles when displaying these widgets. It's up to you to define how you wish to blend them into your content. If you want to keep the native look and feel of the widgets, you'll face a little difficulty if you want to give them a consistent size. **This is because each widget has its own rules for border, padding, and margin.** To give the same size to several different widgets, you can use the `box-sizing` property along with some consistent values for other properties: ```css input, textarea, select, button { width: 150px; padding: 0; margin: 0; box-sizing: border-box; } ``` In the screenshot below, the left column shows the default rendering of an `<input type="radio">`, `<input type="checkbox">`, `<input type="range">`, `<input type="text">`, `<input type="date">`, `<select>`, `<textarea>`, `<input type="submit">`, and `<button>`. The right column on the other hand shows the same elements with our above rule applied to them. Notice how this lets us ensure that all of the elements occupy the same amount of space, despite the platform's default rules for each kind of widget. ![box model properties effect most input types.](/en-US/docs/Learn/Forms/Styling_web_forms/boxmodel_formcontrols1.png) What may not be apparent via the screenshot is that the radio and checkbox controls still look the same, but they are centered in the 150px of horizontal space provided by the `width` property. Other browsers may not center the widgets, but they do adhere to the space allotted. ### Legend placement The `<legend>` element is okay to style, but it can be a bit tricky to control the placement of it. By default, it is always positioned over the top border of its `<fieldset>` parent, near the top left corner. To position it somewhere else, for example inside the fieldset somewhere, or near the bottom left corner, you need to rely on the positioning. Take the following example: To position the legend in this manner, we used the following CSS (other declarations removed for brevity): ```css fieldset { position: relative; } legend { position: absolute; bottom: 0; right: 0; } ``` The `<fieldset>` needs to be positioned too, so that the `<legend>` is positioned relative to it (otherwise the `<legend>` would be positioned relative to the `<body>`). The `<legend>` element is very important for accessibility — it will be spoken by assistive technologies as part of the label of each form element inside the fieldset — but using a technique like the one above is fine. The legend contents will still be spoken in the same way; it is just the visual position that has changed. **Note:** You could also use the `transform` property to help you with positioning your `<legend>`. However, when you position it with for example a `transform: translateY();`, it moves but leaves an ugly gap in the `<fieldset>` border, which is not easy to get rid of. A specific styling example -------------------------- Let's look at a concrete example of how to style an HTML form. We will build a fancy-looking "postcard" contact form; see here for the finished version. If you want to follow along with this example, make a local copy of our postcard-start.html file, and follow the below instructions. ### The HTML The HTML is only slightly more involved than the example we used in the first article of this guide; it just has a few extra IDs and a heading. ```html <form> <h1>to: Mozilla</h1> <div id="from"> <label for="name">from:</label> <input type="text" id="name" name="user\_name" /> </div> <div id="reply"> <label for="mail">reply:</label> <input type="email" id="mail" name="user\_email" /> </div> <div id="message"> <label for="msg">Your message:</label> <textarea id="msg" name="user\_message"></textarea> </div> <div class="button"> <button type="submit">Send your message</button> </div> </form> ``` Add the above code into the body of your HTML. ### Organizing your assets This is where the fun begins! Before we start coding, we need three additional assets: 1. The postcard background — download this image and save it in the same directory as your working HTML file. 2. A typewriter font: The "Mom's Typewriter" font from dafont.com — download the TTF file into the same directory as above. 3. A hand-drawn font: The "Journal" font from dafont.com — download the TTF file into the same directory as above. Your fonts need some more processing before you start: 1. Go to the fontsquirrel.com Webfont Generator. 2. Using the form, upload both your font files and generate a webfont kit. Download the kit to your computer. 3. Unzip the provided zip file. 4. Inside the unzipped contents you will find some font files (at the time of writing, two `.woff` files and two `.woff2` files; they might vary in the future.) Copy these files into a directory called fonts, in the same directory as before. We are using two different files for each font to maximize browser compatibility; see our Web fonts article for a lot more information. ### The CSS Now we can dig into the CSS for the example. Add all the code blocks shown below inside the `<style>` element, one after another. #### Overall layout First, we prepare by defining our `@font-face` rules, and all the basic styles set on the `<body>` and `<form>` elements. If the fontsquirrel output was different from what we described above, you can find the correct `@font-face` blocks inside your downloaded webfont kit, in the `stylesheet.css` file (you'll need to replace the below `@font-face` blocks with them, and update the paths to the font files): ```css @font-face { font-family: "handwriting"; src: url("fonts/journal-webfont.woff2") format("woff2"), url("fonts/journal-webfont.woff") format("woff"); font-weight: normal; font-style: normal; } @font-face { font-family: "typewriter"; src: url("fonts/momot\_\_\_-webfont.woff2") format("woff2"), url("fonts/momot\_\_\_-webfont.woff") format("woff"); font-weight: normal; font-style: normal; } body { font: 1.3rem sans-serif; padding: 0.5em; margin: 0; background: #222; } form { position: relative; width: 740px; height: 498px; margin: 0 auto; padding: 1em; box-sizing: border-box; background: #fff url(background.jpg); /\* we create our grid \*/ display: grid; grid-gap: 20px; grid-template-columns: repeat(2, 1fr); grid-template-rows: 10em 1em 1em 1em; } ``` Notice that we've used some CSS Grid and Flexbox to lay out the form. Using this we can easily position our elements, including the title and all the form elements: ```css h1 { font: 1em "typewriter", monospace; align-self: end; } #message { grid-row: 1 / 5; } #from, #reply { display: flex; } ``` #### Labels and controls Now we can start working on the form elements themselves. First, let's ensure that the `<label>`s are given the right font: ```css label { font: 0.8em "typewriter", sans-serif; } ``` The text fields require some common rules. In other words, we remove their `borders` and `backgrounds`, and redefine their `padding` and `margin`: ```css input, textarea { font: 1.4em/1.5em "handwriting", cursive, sans-serif; border: none; padding: 0 10px; margin: 0; width: 80%; background: none; } ``` When one of these fields gains focus, we highlight them with a light grey, transparent, background (it is always important to have focus style, for usability and keyboard accessibility): ```css input:focus, textarea:focus { background: rgb(0 0 0 / 10%); border-radius: 5px; } ``` Now that our text fields are complete, we need to adjust the display of the single and multiple-line text fields to match, since they won't typically look the same using the defaults. #### Tweaking the textareas `<textarea>` elements default to being rendered as an inline-block element. The two important things here are the `resize` and `overflow` properties. While our design is a fixed-size design, and we could use the `resize` property to prevent users from resizing our multi-line text field, it is best to not prevent users from resizing a textarea if they so choose. The `overflow` property is used to make the field render more consistently across browsers. Some browsers default to the value `auto`, while some default to the value `scroll`. In our case, it's better to be sure everyone will use `auto`: ```css textarea { display: block; padding: 10px; margin: 10px 0 0 -10px; width: 100%; height: 90%; border-right: 1px solid; /\* resize : none; \*/ overflow: auto; } ``` #### Styling the submit button The `<button>` element is really convenient to style with CSS; you can do whatever you want, even using pseudo-elements: ```css button { padding: 5px; font: bold 0.6em sans-serif; border: 2px solid #333; border-radius: 5px; background: none; cursor: pointer; transform: rotate(-1.5deg); } button:after { content: " >>>"; } button:hover, button:focus { background: #000; color: #fff; } ``` ### The final result And voilà! Your form should now look like this: ![The final look and layout of the form after applying all styling and tweaking to it as described above](/en-US/docs/Learn/Forms/Styling_web_forms/updated-form-screenshot.jpg) **Note:** If your example does not work quite as you expected and you want to check it against our version, you can find it on GitHub — see it running live (also see the source code). Test your skills ---------------- You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Styling basics. Summary ------- As you can see, as long as we want to build forms with just text fields and buttons, it's easy to style them using CSS. In the next article, we will see how to handle form widgets which fall into the "bad" and "ugly" categories. * Previous * Overview: Forms * Next ### Advanced Topics * How to build custom form controls * Sending forms through JavaScript * Property compatibility table for form widgets
UI pseudo-classes - Learn web development
UI pseudo-classes ================= * Previous * Overview: Forms * Next In the previous articles, we covered the styling of various form controls in a general manner. This included some usage of pseudo-classes, for example, using `:checked` to target a checkbox only when it is selected. In this article, we explore the different UI pseudo-classes available for styling forms in different states. | | | | --- | --- | | Prerequisites: | A basic understanding of HTML and CSS, including general knowledge of pseudo-classes and pseudo-elements. | | Objective: | To understand what parts of forms are hard to style, and why; to learn what can be done to customize them. | What pseudo-classes do we have available? ----------------------------------------- The original pseudo-classes (from CSS 2.1) that are relevant to forms are: * `:hover`: Selects an element only when it is being hovered over by a mouse pointer. * `:focus`: Selects an element only when it is focused (i.e. by being tabbed to via the keyboard). * `:active`: selects an element only when it is being activated (i.e. while it is being clicked on, or when the `Return` / `Enter` key is being pressed down in the case of a keyboard activation). These basic pseudo-classes should be familiar to you now. CSS selectors provide several other pseudo-classes related to HTML forms. These provide several useful targeting conditions that you can take advantage of. We'll discuss these in more detail in the sections below, but briefly, the main ones we'll be looking at are: * `:required` and `:optional`: Target elements that can be required (e.g. elements that support the `required` HTML attribute)), based on whether they are required or optional. * `:valid` and `:invalid`, and `:in-range` and `:out-of-range`: Target form controls that are valid/invalid according to form validation constraints set on them, or in-range/out-of-range. * `:enabled` and `:disabled`, and `:read-only` and `:read-write`: Target elements that can be disabled (e.g. elements that support the `disabled` HTML attribute), based on whether they are currently enabled or disabled, and read-write or read-only form controls (e.g. elements with the `readonly` HTML attribute set). * `:checked`, `:indeterminate`, and `:default`: Respectively target checkboxes and radio buttons that are checked, in an indeterminate state (neither checked or not checked), and the default selected option when the page loads (e.g. an `<input type="checkbox">` with the `checked` attribute set, or an `<option>` element with the `selected` attribute set). There are many others, but the ones listed above are the most obviously useful. Some of them are aimed at solving very specific niche problems. The UI pseudo-classes listed above have excellent browser support, but of course, you should test your form implementations carefully to ensure they work for your target audience. **Note:** A number of the pseudo-classes discussed here are concerned with styling form controls based on their validation state (is their data valid, or not?) You'll learn much more about setting and controlling validation constraints in our next article — Client-side form validation — but for now we'll keep things simple regarding the form validation, so it doesn't confuse things. Styling inputs based on whether they are required or not -------------------------------------------------------- One of the most basic concepts regarding client-side form validation is whether a form input is required (it has to be filled in before the form can be submitted) or optional. `<input>`, `<select>`, and `<textarea>` elements have a `required` attribute available which, when set, means that you have to fill in that control before the form will successfully submit. For example: ```html <form> <fieldset> <legend>Feedback form</legend> <div> <label for="fname">First name: </label> <input id="fname" name="fname" type="text" required /> </div> <div> <label for="lname">Last name: </label> <input id="lname" name="lname" type="text" required /> </div> <div> <label for="email"> Email address (include if you want a response): </label> <input id="email" name="email" type="email" /> </div> <div><button>Submit</button></div> </fieldset> </form> ``` Here, the first name and last name are required, but the email address is optional. You can match these two states using the `:required` and `:optional` pseudo-classes. For example, if we apply the following CSS to the above HTML: ```css input:required { border: 1px solid black; } input:optional { border: 1px solid silver; } ``` The required controls would have a black border, and the optional control will have a silver border, like so: You can also try submitting the form without filling it in, to see the client-side validation error messages browsers give you by default. The above form isn't bad, but it isn't great either. For a start, we are signaling required versus optional status using color alone, which isn't great for colorblind people. Second, the standard convention on the web for required status is an asterisk (`*`), or the word "required" being associated with the controls in question. In the next section, we'll look at a better example of indicating required fields using `:required`, which also digs into using generated content. **Note:** You'll probably not find yourself using the `:optional` pseudo-class very often. Form controls are optional by default, so you could just do your optional styling by default, and add styles on top for required controls. **Note:** If one radio button in a same-named group of radio buttons has the `required` attribute set, all the radio buttons will be invalid until one is selected, but only the one with the attribute assigned will actually match `:required`. Using generated content with pseudo-classes ------------------------------------------- In previous articles, we've seen the usage of generated content, but we thought now would be a good time to talk about it in a bit more detail. The idea is that we can use the `::before` and `::after` pseudo-elements along with the `content` property to make a chunk of content appear before or after the affected element. The chunk of content is not added to the DOM, so it may be invisible to some screen readers. Because it is a pseudo-element, it can be targeted with styles in the same way that any actual DOM node can. This is really useful when you want to add a visual indicator to an element, such as a label or icon, when alternative indicators are also available to ensure accessibility for all users. For example, in our custom radio buttons example, we use generated content to handle the placement and animation of the a custom radio button's inner circle when a radio button is selected: ```css input[type="radio"]::before { display: block; content: " "; width: 10px; height: 10px; border-radius: 6px; background-color: red; font-size: 1.2em; transform: translate(3px, 3px) scale(0); transform-origin: center; transition: all 0.3s ease-in; } input[type="radio"]:checked::before { transform: translate(3px, 3px) scale(1); transition: all 0.3s cubic-bezier(0.25, 0.25, 0.56, 2); } ``` This is really useful — screen readers already let their users know when a radio button or checkbox they encounter is checked/selected, so you don't want them to read out another DOM element that indicates selection — that could be confusing. Having a purely visual indicator solves this problem. Back to our required/optional example from before, this time we'll not alter the appearance of the input itself — we'll use generated content to add an indicating label (see it live here, and see the source code here). First of all, we'll add a paragraph to the top of the form to say what you are looking for: ```html <p>Required fields are labeled with "required".</p> ``` Screen reader users will get "required" read out as an extra bit of information when they get to each required input, while sighted users will get our label. Since form inputs don't directly support having generated content put on them (this is because generated content is placed relative to an element's formatting box, but form inputs work more like replaced elements and therefore don't have one), we will add an empty `<span>` to hang the generated content on: ```html <div> <label for="fname">First name: </label> <input id="fname" name="fname" type="text" required /> <span></span> </div> ``` The immediate problem with this was that the span was dropping onto a new line below the input because the input and label are both set with `width: 100%`. To fix this we style the parent `<div>` to become a flex container, but also tell it to wrap its contents onto new lines if the content becomes too long: ```css fieldset > div { margin-bottom: 20px; display: flex; flex-flow: row wrap; } ``` The effect this has is that the label and input sit on separate lines because they are both `width: 100%`, but the `<span>` has a width of `0` so it can sit on the same line as the input. Now onto the generated content. We create it using this CSS: ```css input + span { position: relative; } input:required + span::after { font-size: 0.7rem; position: absolute; content: "required"; color: white; background-color: black; padding: 5px 10px; top: -26px; left: -70px; } ``` We set the `<span>` to `position: relative` so that we can set the generated content to `position: absolute` and position it relative to the `<span>` rather than the `<body>` (The generated content acts as though it is a child node of the element it is generated on, for the purposes of positioning). Then we give the generated content the content "required", which is what we wanted our label to say, and style and position it as we want. The result is seen below. Styling controls based on whether their data is valid ----------------------------------------------------- The other really important, fundamental concept in form validation is whether a form control's data is valid or not (in the case of numerical data, we can also talk about in-range and out-of-range data). Form controls with constraint limitations can be targeted based on these states. ### :valid and :invalid You can target form controls using the `:valid` and `:invalid` pseudo-classes. Some points worth bearing in mind: * Controls with no constraint validation will always be valid, and therefore matched with `:valid`. * Controls with `required` set on them that have no value are counted as invalid — they will be matched with `:invalid` and `:required`. * Controls with built-in validation, such as `<input type="email">` or `<input type="url">` are (matched with) `:invalid` when the data entered into them does not match the pattern they are looking for (but they are valid when empty). * Controls whose current value is outside the range limits specified by the `min` and `max` attributes are (matched with) `:invalid`, but also matched by `:out-of-range`, as you'll see later on. * There are some other ways to make an element matched by `:valid`/`:invalid`, as you'll see in the Client-side form validation article. But we'll keep things simple for now. Let's go in and look at a simple example of `:valid`/`:invalid` (see valid-invalid.html for the live version, and also check out the source code). As in the previous example, we've got extra `<span>`s to generate content on, which we'll use to provide indicators of valid/invalid data: ```html <div> <label for="fname">First name: </label> <input id="fname" name="fname" type="text" required /> <span></span> </div> ``` To provide these indicators, we use the following CSS: ```css input + span { position: relative; } input + span::before { position: absolute; right: -20px; top: 5px; } input:invalid { border: 2px solid red; } input:invalid + span::before { content: "✖"; color: red; } input:valid + span::before { content: "✓"; color: green; } ``` As before, we set the `<span>`s to `position: relative` so that we can position the generated content relative to them. We then absolutely position different generated content depending on whether the form's data is valid or invalid — a green check or a red cross, respectively. To add a bit of extra urgency to the invalid data, we've also given the inputs a thick red border when invalid. **Note:** We've used `::before` to add these labels, as we were already using `::after` for the "required" labels. You can try it below: Notice how the required text inputs are invalid when empty, but valid when they have something filled in. The email input on the other hand is valid when empty, as it is not required, but invalid when it contains something that is not a proper email address. ### In-range and out-of-range data As we hinted at above, there are two other related pseudo-classes to consider — `:in-range` and `:out-of-range`. These match numeric inputs where range limits are specified by the `min` and `max`, when their data is inside or outside the specified range, respectively. **Note:** Numeric input types are `date`, `month`, `week`, `time`, `datetime-local`, `number`, and `range`. It is worth noting that inputs whose data is in-range will also be matched by the `:valid` pseudo-class and inputs whose data is out-of-range will also be matched by the `:invalid` pseudo-class. So why have both? The issue is really one of semantics — out-of-range is a more specific type of invalid communication, so you might want to provide a different message for out-of-range inputs, which will be more helpful to users than just saying "invalid". You might even want to provide both. Let's look at an example that does exactly this. Our out-of-range.html demo (see also the source code) builds on top of the previous example to provide out-of-range messages for the numeric inputs, as well as saying whether they are required. The numeric input looks like this: ```html <div> <label for="age">Age (must be 12+): </label> <input id="age" name="age" type="number" min="12" max="120" required /> <span></span> </div> ``` And the CSS looks like this: ```css input + span { position: relative; } input + span::after { font-size: 0.7rem; position: absolute; padding: 5px 10px; top: -26px; } input:required + span::after { color: white; background-color: black; content: "Required"; left: -70px; } input:out-of-range + span::after { color: white; background-color: red; width: 155px; content: "Outside allowable value range"; left: -182px; } ``` This is a similar story to what we had before in the `:required` example, except that here we've split out the declarations that apply to any `::after` content into a separate rule, and given the separate `::after` content for `:required` and `:out-of-range` states their own content and styling. You can try it here: It is possible for the number input to be both required and out-of-range at the same time, so what happens then? Because the `:out-of-range` rule appears later in the source code than the `:required` rule, the cascade rules come into play, and the out of range message is shown. This works quite nicely — when the page first loads, "Required" is shown, along with a red cross and border. When you've typed in a valid age (i.e. in the range of 12-120), the input turns valid. If however, you then change the age entry to one that is out of range, the "Outside allowable value range" message then pops up in place of "Required". **Note:** To enter an invalid/out-of-range value, you'll have to actually focus the form and type it in using the keyboard. The spinner buttons won't let you increment/decrement the value outside the allowable range. Styling enabled and disabled inputs, and read-only and read-write ----------------------------------------------------------------- An enabled element is an element that can be activated; it can be selected, clicked on, typed into, etc. A disabled element on the other hand cannot be interacted with in any way, and its data isn't even sent to the server. These two states can be targeted using `:enabled` and `:disabled`. Why are disabled inputs useful? Well, sometimes if some data does not apply to a certain user, you might not even want to submit that data when they submit the form. A classic example is a shipping form — commonly you'll get asked if you want to use the same address for billing and shipping; if so, you can just send a single address to the server, and might as well just disable the billing address fields. Let's have a look at an example that does just this. First of all, the HTML is a simple form containing text inputs, plus a checkbox to toggle disabling the billing address on and off. The billing address fields are disabled by default. ```html <form> <fieldset id="shipping"> <legend>Shipping address</legend> <div> <label for="name1">Name: </label> <input id="name1" name="name1" type="text" required /> </div> <div> <label for="address1">Address: </label> <input id="address1" name="address1" type="text" required /> </div> <div> <label for="pcode1">Zip/postal code: </label> <input id="pcode1" name="pcode1" type="text" required /> </div> </fieldset> <fieldset id="billing"> <legend>Billing address</legend> <div> <label for="billing-checkbox">Same as shipping address:</label> <input type="checkbox" id="billing-checkbox" checked /> </div> <div> <label for="name" class="billing-label disabled-label">Name: </label> <input id="name" name="name" type="text" disabled required /> </div> <div> <label for="address2" class="billing-label disabled-label"> Address: </label> <input id="address2" name="address2" type="text" disabled required /> </div> <div> <label for="pcode2" class="billing-label disabled-label"> Zip/postal code: </label> <input id="pcode2" name="pcode2" type="text" disabled required /> </div> </fieldset> <div><button>Submit</button></div> </form> ``` Now onto the CSS. The most relevant parts of this example are as follows: ```css input[type="text"]:disabled { background: #eee; border: 1px solid #ccc; } .disabled-label { color: #aaa; } ``` We've directly selected the inputs we want to disable using `input[type="text"]:disabled`, but we also wanted to gray out the corresponding text labels. These weren't quite as easy to select, so we've used a class to provide them with that styling. Now finally, we've used some JavaScript to toggle the disabling of the billing address fields: ```js // Wait for the page to finish loading document.addEventListener( "DOMContentLoaded", () => { // Attach `change` event listener to checkbox document .getElementById("billing-checkbox") .addEventListener("change", toggleBilling); }, false, ); function toggleBilling() { // Select the billing text fields const billingItems = document.querySelectorAll('#billing input[type="text"]'); // Select the billing text labels const billingLabels = document.querySelectorAll(".billing-label"); // Toggle the billing text fields and labels for (let i = 0; i < billingItems.length; i++) { billingItems[i].disabled = !billingItems[i].disabled; if ( billingLabels[i].getAttribute("class") === "billing-label disabled-label" ) { billingLabels[i].setAttribute("class", "billing-label"); } else { billingLabels[i].setAttribute("class", "billing-label disabled-label"); } } } ``` It uses the `change` event to let the user enable/disable the billing fields, and toggle the styling of the associated labels. You can see the example in action below (also see it live here, and see the source code): ### Read-only and read-write In a similar manner to `:disabled` and `:enabled`, the `:read-only` and `:read-write` pseudo-classes target two states that form inputs toggle between. Read-only inputs have their values submitted to the server, but the user can't edit them, whereas read-write means they can be edited — their default state. An input is set to read-only using the `readonly` attribute. As an example, imagine a confirmation page where the developer has sent the details filled in on previous pages over to this page, with the aim of getting the user to check them all in one place, add any final data that is needed, and then confirm the order by submitting. At this point, all the final form data can be sent to the server in one go. Let's look at what a form might look like (see readonly-confirmation.html for the live example; also see the source code). A fragment of the HTML is as follows — note the readonly attribute: ```html <div> <label for="name">Name: </label> <input id="name" name="name" type="text" value="Mr Soft" readonly /> </div> ``` If you try the live example, you'll see that the top set of form elements are not focusable, however, the values are submitted when the form is submitted. We've styled the form controls using the `:read-only` and `:read-write` pseudo-classes, like so: ```css input:read-only, textarea:read-only { border: 0; box-shadow: none; background-color: white; } textarea:read-write { box-shadow: inset 1px 1px 3px #ccc; border-radius: 5px; } ``` The full example looks like this: **Note:** `:enabled` and `:read-write` are two more pseudo-classes that you'll probably rarely use, given that they describe the default states of input elements. Radio and checkbox states — checked, default, indeterminate ----------------------------------------------------------- As we've seen in earlier articles in the module, radio buttons and checkboxes can be checked or unchecked. But there are a couple of other states to consider too: * `:default`: Matches radios/checkboxes that are checked by default, on page load (i.e. by setting the `checked` attribute on them). These match the `:default` pseudo-class, even if the user unchecks them. * `:indeterminate`: When radios/checkboxes are neither checked nor unchecked, they are considered *indeterminate* and will match the `:indeterminate` pseudo-class. More on what this means below. ### :checked When checked, they will be matched by the `:checked` pseudo-class. The most common use of this is to add a different style onto the checkbox or radio button when it is checked, in cases where you've removed the system default styling with `appearance: none;` and want to build the styles back up yourself. We saw examples of this in the previous article when we talked about Using `appearance: none` on radios/checkboxes. As a recap, the `:checked` code from our Styled radio buttons example looks like so: ```css input[type="radio"]::before { display: block; content: " "; width: 10px; height: 10px; border-radius: 6px; background-color: red; font-size: 1.2em; transform: translate(3px, 3px) scale(0); transform-origin: center; transition: all 0.3s ease-in; } input[type="radio"]:checked::before { transform: translate(3px, 3px) scale(1); transition: all 0.3s cubic-bezier(0.25, 0.25, 0.56, 2); } ``` You can try it out here: Basically, we build the styling for a radio button's "inner circle" using the `::before` pseudo-element, but set a `scale(0)` `transform` on it. We then use a `transition` to make the generated content on the label nicely animate into view when the radio is selected/checked. The advantage of using a transform rather than transitioning `width`/`height` is that you can use `transform-origin` to make it grow from the center of the circle, rather than having it appear to grow from the circle's corner, and there is no jumping behavior as no box model property values are updated. ### :default and :indeterminate As mentioned above, the `:default` pseudo-class matches radios/checkboxes that are checked by default, on page load, even when unchecked. This could be useful for adding an indicator to a list of options to remind the user what the defaults (or starting options) were, in case they want to reset their choices. Also, the radios/checkboxes mentioned above will be matched by the `:indeterminate` pseudo-class when they are in a state where they are neither checked nor unchecked. But what does this mean? Elements that are indeterminate include: * `<input/radio>` inputs, when all radio buttons in a same-named group are unchecked * `<input/checkbox>` inputs whose `indeterminate` property is set to `true` via JavaScript * `<progress>` elements that have no value. This isn't something you'll likely use very often. One use case could be an indicator to tell users that they really need to select a radio button before they move on. Let's look at a couple of modified versions of the previous example that remind the user what the default option was, and style the labels of radio buttons when indeterminate. Both of these have the following HTML structure for the inputs: ```html <p> <input type="radio" name="fruit" value="cherry" id="cherry" /> <label for="cherry">Cherry</label> <span></span> </p> ``` For the `:default` example, we've added the `checked` attribute to the middle radio button input, so it will be selected by default when loaded. We then style this with the following CSS: ```css input ~ span { position: relative; } input:default ~ span::after { font-size: 0.7rem; position: absolute; content: "Default"; color: white; background-color: black; padding: 5px 10px; right: -65px; top: -3px; } ``` This provides a little "Default" label on the item that was originally selected when the page loaded. Note here we are using the subsequent-sibling combinator (`~`) rather than the Next-sibling combinator (`+`) — we need to do this because the `<span>` does not come right after the `<input>` in the source order. See the live result below: **Note:** You can also find the example live on GitHub at radios-checked-default.html (also see the source code.) For the `:indeterminate` example, we've got no default selected radio button — this is important — if there was, then there would be no indeterminate state to style. We style the indeterminate radio buttons with the following CSS: ```css input[type="radio"]:indeterminate { outline: 2px solid red; animation: 0.4s linear infinite alternate outline-pulse; } @keyframes outline-pulse { from { outline: 2px solid red; } to { outline: 6px solid red; } } ``` This creates a fun little animated outline on the radio buttons, which hopefully indicates that you need to select one of them! See the live result below: **Note:** You can also find the example live on GitHub at radios-checked-indeterminate.html (also see the source code.) **Note:** You can find an interesting example involving `indeterminate` states on the `<input type="checkbox">` reference page. More pseudo-classes ------------------- There are a number of other pseudo-classes of interest, and we don't have space to write about them all in detail here. Let's talk about a few more that you should take the time to investigate. * The `:focus-within` pseudo-class matches an element that has received focus or *contains* an element that has received focus. This is useful if you want a whole form to highlight in some way when an input inside it is focused. * The `:focus-visible` pseudo-class matches focused elements that received focus via keyboard interaction (rather than touch or mouse) — useful if you want to show a different style for keyboard focus compared to mouse (or other) focus. * The `:placeholder-shown` pseudo-class matches `<input>` and `<textarea>` elements that have their placeholder showing (i.e. the contents of the `placeholder` attribute) because the value of the element is empty. The following are also interesting, but as yet not well-supported in browsers: * The `:blank` pseudo-class selects empty form controls. `:empty` also matches elements that have no children, like `<input>`, but it is more general — it also matches other void elements like `<br>` and `<hr>`. `:empty` has reasonable browser support; the `:blank` pseudo-class's specification is not yet finished, so it is not yet supported in any browser. * The `:user-invalid` pseudo-class, when supported, will be similar to `:invalid`, but with better user experience. If the value is valid when the input receives focus, the element may match `:invalid` as the user enters data if the value is temporarily invalid, but will only match `:user-invalid` when the element loses focus. If the value was originally invalid, it will match both `:invalid` and `:user-invalid` for the whole duration of the focus. In a similar manner to `:invalid`, it will stop matching `:user-invalid` if the value does become valid. Test your skills! ----------------- You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Advanced styling. Summary ------- This completes our look at UI pseudo-classes that relate to form inputs. Keep playing with them, and create some fun form styles! Next up, we'll move on to something different — client-side form validation. * Previous * Overview: Forms * Next ### Advanced Topics * How to build custom form controls * Sending forms through JavaScript * Property compatibility table for form widgets
Basic native form controls - Learn web development
Basic native form controls ========================== * Previous * Overview: Forms * Next In the previous article, we marked up a functional web form example, introducing some form controls and common structural elements, and focusing on accessibility best practices. Next, we will look at the functionality of the different form controls, or widgets, in detail — studying all the different options available to collect different types of data. In this particular article, we will look at the original set of form controls, available in all browsers since the early days of the web. | | | | --- | --- | | Prerequisites: | A basic understanding of HTML. | | Objective: | To understand in detail the original set of native form widgets available in browsers for collecting data, and how to implement them using HTML. | You've already met some form elements, including `<form>`, `<fieldset>`, `<legend>`, `<textarea>`, `<label>`, `<button>`, and `<input>`. This article covers: * The common input types button, checkbox, file, hidden, image, password, radio, reset, submit, and text. * Some of the attributes that are common to all form controls. **Note:** We cover additional, more powerful form controls in the next two articles. If you want a more advanced reference, you should consult our HTML forms element reference, and in particular our extensive `<input>` types reference. Text input fields ----------------- Text `<input>` fields are the most basic form widgets. They are a very convenient way to let the user enter any kind of data, and we've already seen a few simple examples. **Note:** HTML form text fields are simple plain text input controls. This means that you cannot use them to perform rich text editing (bold, italic, etc.). All rich text editors you'll encounter are custom widgets created with HTML, CSS, and JavaScript. All basic text controls share some common behaviors: * They can be marked as `readonly` (the user cannot modify the input value but it is still sent with the rest of the form data) or `disabled` (the input value can't be modified and is never sent with the rest of the form data). * They can have a `placeholder`; this is the text that appears inside the text input box that should be used to briefly describe the purpose of the box. * They can be constrained in `size` (the physical size of the box) and `maxlength` (the maximum number of characters that can be entered into the box). * They can benefit from spell checking (using the `spellcheck` attribute), if the browser supports it. **Note:** The `<input>` element is unique amongst HTML elements because it can take many forms depending on its `type` attribute value. It is used for creating most types of form widgets including single line text fields, time and date controls, controls without text input like checkboxes, radio buttons, and color pickers, and buttons. ### Single line text fields A single line text field is created using an `<input>` element whose `type` attribute value is set to `text`, or by omitting the `type` attribute altogether (`text` is the default value). The value `text` for this attribute is also the fallback value if the value you specify for the `type` attribute is unknown by the browser (for example if you specify `type="color"` and the browser doesn't support native color pickers). **Note:** You can find examples of all the single line text field types on GitHub at single-line-text-fields.html (see it live also). Here is a basic single line text field example: ```html <input type="text" id="comment" name="comment" value="I'm a text field" /> ``` Single line text fields have only one true constraint: if you type text with line breaks, the browser removes those line breaks before sending the data to the server. The screenshot below shows a text input in default, focused, and disabled states. Most browsers indicate the focused state using a focus ring around the control and the disabled state using grey text or a faded/semi-opaque control. ![Screenshot of the default, focused and disabled states text input in Chrome on macOS](/en-US/docs/Learn/Forms/Basic_native_form_controls/disabled.png) The screenshots used in this document were taken in the Chrome browser on macOS. There may be minor variations in these fields/buttons across different browsers, but the basic highlighting technique remains similar. **Note:** We discuss values for the `type` attribute that enforce specific validation constraints including color, email, and url input types, in the next article, The HTML5 input types. #### Password field One of the original input types was the `password` text field type: ```html <input type="password" id="pwd" name="pwd" /> ``` The following screenshot shows Password input field in which each input character is shown as a dot. ![Password field in chrome 115 on macOS](/en-US/docs/Learn/Forms/Basic_native_form_controls/password.png) The `password` value doesn't add any special constraints to the entered text, but it does obscure the value entered into the field (e.g. with dots or asterisks) so it can't be easily read by others. Keep in mind this is just a user interface feature; unless you submit your form securely, it will get sent in plain text, which is bad for security — a malicious party could intercept your data and steal passwords, credit card details, or whatever else you've submitted. The best way to protect users from this is to host any pages involving forms over a secure connection (i.e. located at an `https://` address), so the data is encrypted before it is sent. Browsers recognize the security implications of sending form data over an insecure connection, and have warnings to deter users from using insecure forms. For more information on what Firefox implements, see Insecure passwords. ### Hidden content Another original text control is the `hidden` input type. This is used to create a form control that is invisible to the user, but is still sent to the server along with the rest of the form data once submitted — for example you might want to submit a timestamp to the server stating when an order was placed. Because it is hidden, the user can not see nor intentionally edit the value, it will never receive focus, and a screen reader will not notice it either. ```html <input type="hidden" id="timestamp" name="timestamp" value="1286705410" /> ``` If you create such an element, it's required to set its `name` and `value` attributes. The value can be dynamically set via JavaScript. The `hidden` input type should not have an associated label. Other text input types, like search, url, and tel, will be covered in the next tutorial, HTML5 input types. Checkable items: checkboxes and radio buttons --------------------------------------------- Checkable items are controls whose state you can change by clicking on them or their associated labels. There are two kinds of checkable items: the checkbox and the radio button. Both use the `checked` attribute to indicate whether the widget is checked by default or not. It's worth noting that these widgets do not behave exactly like other form widgets. For most form widgets, once the form is submitted all widgets that have a `name` attribute are sent, even if no value has been filled out. In the case of checkable items, their values are sent only if they are checked. If they are not checked, nothing is sent, not even their name. If they are checked but have no value, the name is sent with a value of *on.* **Note:** You can find the examples from this section on GitHub as checkable-items.html (see it live also). For maximum usability/accessibility, you are advised to surround each list of related items in a `<fieldset>`, with a `<legend>` providing an overall description of the list. Each individual pair of `<label>`/`<input>` elements should be contained in its own list item (or similar). The associated `<label>` is generally placed immediately before or after the radio button or checkbox, with the instructions for the group of radio button or checkboxes generally being the content of the `<legend>`. See the examples linked above for structural examples. ### Checkbox A checkbox is created using the `<input>` element with a `type` attribute set to the value checkbox. ```html <input type="checkbox" id="questionOne" name="subscribe" value="yes" checked /> ``` Related checkbox items should use the same `name` attribute. Including the `checked` attribute makes the checkbox checked automatically when the page loads. Clicking the checkbox or its associated label toggles the checkbox on and off. ```html <fieldset> <legend>Choose all the vegetables you like to eat</legend> <ul> <li> <label for="carrots">Carrots</label> <input type="checkbox" id="carrots" name="vegetable" value="carrots" checked /> </li> <li> <label for="peas">Peas</label> <input type="checkbox" id="peas" name="vegetable" value="peas" /> </li> <li> <label for="cabbage">Cabbage</label> <input type="checkbox" id="cabbage" name="vegetable" value="cabbage" /> </li> </ul> </fieldset> ``` The following screenshot shows checkboxes in the default, focused, and disabled states. Checkboxes in the default and disabled states appear checked, whereas in the focused state, the checkbox is unchecked, with focus ring around it. ![Default, focused and disabled Checkboxes in chrome 115 on macOS](/en-US/docs/Learn/Forms/Basic_native_form_controls/checkboxes.png) **Note:** Any checkboxes and radio buttons with the `checked` attribute on load match the `:default` pseudo-class, even if they are no longer checked. Any that are currently checked match the `:checked` pseudo-class. Due to the on-off nature of checkboxes, the checkbox is considered a toggle button, with many developers and designers expanding on the default checkbox styling to create buttons that look like toggle switches. You can see an example in action here (also see the source code). ### Radio button A radio button is created using the `<input>` element with its `type` attribute set to the value `radio`: ```html <input type="radio" id="soup" name="meal" value="soup" checked /> ``` Several radio buttons can be tied together. If they share the same value for their `name` attribute, they will be considered to be in the same group of buttons. Only one button in a given group may be checked at a time; this means that when one of them is checked all the others automatically get unchecked. When the form is sent, only the value of the checked radio button is sent. If none of them are checked, the whole pool of radio buttons is considered to be in an unknown state and no value is sent with the form. Once one of the radio buttons in a same-named group of buttons is checked, it is not possible for the user to uncheck all the buttons without resetting the form. ```html <fieldset> <legend>What is your favorite meal?</legend> <ul> <li> <label for="soup">Soup</label> <input type="radio" id="soup" name="meal" value="soup" checked /> </li> <li> <label for="curry">Curry</label> <input type="radio" id="curry" name="meal" value="curry" /> </li> <li> <label for="pizza">Pizza</label> <input type="radio" id="pizza" name="meal" value="pizza" /> </li> </ul> </fieldset> ``` The following screenshot shows default and disabled radio buttons in the checked state, along with focused a radio button in the unchecked state. ![Default, focused and disabled Radio buttons in chrome 115 on macOS](/en-US/docs/Learn/Forms/Basic_native_form_controls/radios.png) Actual buttons -------------- The radio button isn't actually a button, despite its name; let's move on and look at actual buttons! There are three input types that produce buttons: `submit` Sends the form data to the server. For `<button>` elements, omitting the `type` attribute (or an invalid value of `type`) results in a submit button. `reset` Resets all form widgets to their default values. `button` Buttons that have no automatic effect but can be customized using JavaScript code. Then we also have the `<button>` element itself. This can take a `type` attribute of value `submit`, `reset`, or `button` to mimic the behavior of the three `<input>` types mentioned above. The main difference between the two is that actual `<button>` elements are much easier to style. ```html <input type="submit" value="Submit this form" /> <input type="reset" value="Reset this form" /> <input type="button" value="Do Nothing without JavaScript" /> <button type="submit">Submit this form</button> <button type="reset">Reset this form</button> <button type="button">Do Nothing without JavaScript</button> ``` ``` <div class="buttondemo"> <p>Using &lt;input></p> <p> <input type="submit" value="Submit this form" /> <input type="reset" value="Reset this form" /> <input type="button" value="Do Nothing without JavaScript" /> </p> <p>Using &lt;button></p> <p> <button type="submit">Submit this form</button> <button type="reset">Reset this form</button> <button type="button">Do Nothing without JavaScript</button> </p> </div> ``` ``` button, input { display: none; } .buttondemo button, .buttondemo input { all: revert; } ``` **Note:** The `image` input type also renders as a button. We'll cover that later too. **Note:** You can find the examples from this section on GitHub as button-examples.html (see it live also). Below you can find examples of each button `<input>` type, along with the equivalent `<button>` type. ### submit ```html <button type="submit">This is a <strong>submit button</strong></button> <input type="submit" value="This is a submit button" /> ``` ### reset ```html <button type="reset">This is a <strong>reset button</strong></button> <input type="reset" value="This is a reset button" /> ``` ### anonymous ```html <button type="button">This is an <strong>anonymous button</strong></button> <input type="button" value="This is an anonymous button" /> ``` Buttons always behave the same whether you use a `<button>` element or an `<input>` element. As you can see from the examples, however, `<button>` elements let you use HTML in their content, which is inserted between the opening and closing `<button>` tags. `<input>` elements on the other hand are void elements; their displayed content is inserted inside the `value` attribute, and therefore only accepts plain text as content. The following screenshot shows a button in the default, focused, and disabled states. In the focused state, there is a focus ring around the button, and in the disabled state, the button is greyed out. ![Default, focus, and disabled button states in chrome 115 on macOS](/en-US/docs/Learn/Forms/Basic_native_form_controls/buttons.png) ### Image button The **image button** control is rendered exactly like an `<img>` element, except that when the user clicks on it, it behaves like a submit button. An image button is created using an `<input>` element with its `type` attribute set to the value `image`. This element supports exactly the same set of attributes as the `<img>` element, plus all the attributes supported by other form buttons. ```html <input type="image" alt="Click me!" src="my-img.png" width="80" height="30" /> ``` If the image button is used to submit the form, this control doesn't submit its value — instead, the X and Y coordinates of the click on the image are submitted (the coordinates are relative to the image, meaning that the upper-left corner of the image represents the coordinate (0, 0)). The coordinates are sent as two key/value pairs: * The X value key is the value of the `name` attribute followed by the string "*.x*". * The Y value key is the value of the `name` attribute followed by the string "*.y*". So for example when you click on the image at coordinate (123, 456) and it submits via the `get` method, you'll see the values appended to the URL as follows: ```url http://foo.com?pos.x=123&pos.y=456 ``` This is a very convenient way to build a "hot map". How these values are sent and retrieved is detailed in the Sending form data article. File picker ----------- There is one last `<input>` type that came to us in early HTML: the file input type. Forms are able to send files to a server (this specific action is also detailed in the Sending form data article). The file picker widget can be used to choose one or more files to send. To create a file picker widget, you use the `<input>` element with its `type` attribute set to `file`. The types of files that are accepted can be constrained using the `accept` attribute. In addition, if you want to let the user pick more than one file, you can do so by adding the `multiple` attribute. ### Example In this example, a file picker is created that requests graphic image files. The user is allowed to select multiple files in this case. ```html <input type="file" name="file" id="file" accept="image/\*" multiple /> ``` On some mobile devices, the file picker can access photos, videos, and audio captured directly by the device's camera and microphone by adding capture information to the `accept` attribute like so: ```html <input type="file" accept="image/\*;capture=camera" /> <input type="file" accept="video/\*;capture=camcorder" /> <input type="file" accept="audio/\*;capture=microphone" /> ``` The following screenshot shows the file picker widget in the default, focus, and disabled states when no file is selected. ![File picker widget in default, focus, and disabled states in chrome 115 on macOS](/en-US/docs/Learn/Forms/Basic_native_form_controls/filepickers.png) Common attributes ----------------- Many of the elements used to define form controls have some of their own specific attributes. However, there is a set of attributes common to all form elements. You've met some of these already, but below is a list of those common attributes, for your reference: | Attribute name | Default value | Description | | --- | --- | --- | | `autofocus` | false | This Boolean attribute lets you specify that the element should automatically have input focus when the page loads. Only one form-associated element in a document can have this attribute specified. | | `disabled` | false | This Boolean attribute indicates that the user cannot interact with the element. If this attribute is not specified, the element inherits its setting from the containing element, for example, `<fieldset>`; if there is no containing element with the `disabled` attribute set, then the element is enabled. | | `form` | | The `<form>` element that the widget is associated with, used if it is not nested within that form. The value of the attribute must be the `id` attribute of a `<form>` element in the same document. This lets you associate a form control with a form it is outside of, even if it is inside a different form element. | | `name` | | The name of the element; this is submitted with the form data. | | `value` | | The element's initial value. | Test your skills! ----------------- You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Basic controls. Summary ------- This article has covered the older input types — the original set introduced in the early days of HTML that is well-supported in all browsers. In the next section, we'll take a look at the more modern values of the `type` attribute. * Previous * Overview: Forms * Next ### Advanced Topics * How to build custom form controls * Sending forms through JavaScript * Property compatibility table for form widgets
Test your skills: Styling basics - Learn web development
Test your skills: Styling basics ================================ The aim of this skill test is to assess whether you've understood our Styling web forms article. **Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch. If you get stuck, you can reach out to us in one of our communication channels. Styling basics 1 ---------------- Our basic form styling assessment is fairly free-form, and you have a lot of flexibility over what you end up doing here. But your CSS should aim to fulfill the following requirements: 1. Add some kind of lightweight "reset" to make fonts, padding, margin, and sizing more consistent to begin with. 2. On top of that, add in some nice, consistent styling for the inputs and button. 3. Use some kind of layout technique to make the inputs and labels line up neatly. Download the starting point for this task to work in your own editor or in an online editor.
Advanced form styling - Learn web development
Advanced form styling ===================== * Previous * Overview: Forms * Next In this article, we will see what can be done with CSS to style the types of form control that are more difficult to style — the "bad" and "ugly" categories. As we saw in the previous article, text fields and buttons are perfectly easy to style; now we will dig into styling the more problematic bits. | | | | --- | --- | | Prerequisites: | A basic understanding of HTML and CSS. | | Objective: | To understand what parts of forms are hard to style, and why; to learn what can be done to customize them. | To recap what we said in the previous article, we have: **The bad**: Some elements are more difficult to style, requiring more complex CSS or some more specific tricks: * Checkboxes and radio buttons * `<input type="search">` **The ugly**: Some elements can't be styled thoroughly using CSS. These include: * Elements involved in creating dropdown widgets, including `<select>`, `<option>`, `<optgroup>` and `<datalist>`. * `<input type="color">` * Date-related controls such as `<input type="datetime-local">` * `<input type="range">` * `<input type="file">` * `<progress>` and `<meter>` Let's first talk about the `appearance` property, which is pretty useful for making all of the above more stylable. appearance: controlling OS-level styling ---------------------------------------- In the previous article we said that historically, the styling of web form controls was largely taken from the underlying operating system, which is part of the problem with customizing the look of these controls. The `appearance` property was created as a way to control what OS- or system-level styling was applied to web form controls. By far the most helpful value, and probably the only one you'll use, is `none`. This stops any control you apply it to from using system-level styling, as much as possible, and lets you build up the styles yourself using CSS. For example, let's take the following controls: ```html <form> <p> <label for="search">search: </label> <input id="search" name="search" type="search" /> </p> <p> <label for="text">text: </label> <input id="text" name="text" type="text" /> </p> <p> <label for="date">date: </label> <input id="date" name="date" type="datetime-local" /> </p> <p> <label for="radio">radio: </label> <input id="radio" name="radio" type="radio" /> </p> <p> <label for="checkbox">checkbox: </label> <input id="checkbox" name="checkbox" type="checkbox" /> </p> <p><input type="submit" value="submit" /></p> <p><input type="button" value="button" /></p> </form> ``` Applying the following CSS to them removes system-level styling. ```css input { appearance: none; } ``` The following live example shows you what they look like in your system — default on the left, and with the above CSS applied on the right (find it here also if you want to test it on other systems). In most cases, the effect is to remove the stylized border, which makes CSS styling a bit easier, but isn't really essential. In a couple of cases — search and radio buttons/checkboxes, it becomes way more useful. We'll look at those now. ### Taming search boxes `<input type="search">` is basically just a text input, so why is `appearance: none;` useful here? The answer is that Safari search boxes have some styling restrictions — you can't adjust their `height` or `font-size` freely, for example. This can be fixed using our friend `appearance: none;`, which disables the default appearance: ```css input[type="search"] { appearance: none; } ``` In the example below, you can see two identical styled search boxes. The right one has `appearance: none;` applied, and the left one doesn't. If you look at it in Safari on macOS you'll see that the left one isn't sized properly. Interestingly, setting border/background on the search field also fixes this problem. The following styled search doesn't have `appearance: none;` applied, but it doesn't suffer from the same problem in Safari as the previous example. **Note:** You may have noticed that in the search field, the "x" delete icon, which appears when the value of the search is not null, disappears when the input loses focus in Edge and Chrome, but stays put in Safari. To remove via CSS, you can use `input[type="search"]:not(:focus, :active)::-webkit-search-cancel-button { display: none; }`. ### Styling checkboxes and radio buttons Styling a checkbox or a radio button is tricky by default. The sizes of checkboxes and radio buttons are not meant to be changed with their default designs, and browsers react very differently when you try. For example, consider this simple test case: ```html <label ><span><input type="checkbox" name="q5" value="true" /></span> True</label > <label ><span><input type="checkbox" name="q5" value="false" /></span> False</label > ``` ```css span { display: inline-block; background: red; } input[type="checkbox"] { width: 100px; height: 100px; } ``` Different browsers handle the checkbox and span differently, often ugly ways: | Browser | Rendering | | --- | --- | | Firefox 71 (macOS) | Rounded corners and 1px light grey border | | Firefox 57 (Windows 10) | Rectangular corners with 1px medium grey border | | Chrome 77 (macOS), Safari 13, Opera | Rounded corner with 1px medium grey border | | Chrome 63 (Windows 10) | Rectangular borders with slightly greyish background instead of white. | | Edge 16 (Windows 10) | Rectangular borders with slightly greyish background instead of white. | #### Using appearance: none on radios/checkboxes As we showed before, you can remove the default appearance of a checkbox or radio button altogether with `appearance``:none;` Let's take this example HTML: ```html <form> <fieldset> <legend>Fruit preferences</legend> <p> <label> <input type="checkbox" name="fruit" value="cherry" /> I like cherry </label> </p> <p> <label> <input type="checkbox" name="fruit" value="banana" disabled /> I can't like banana </label> </p> <p> <label> <input type="checkbox" name="fruit" value="strawberry" /> I like strawberry </label> </p> </fieldset> </form> ``` Now, let's style these with a custom checkbox design. Let's start by unstyling the original check boxes: ```css input[type="checkbox"] { appearance: none; } ``` We can use the `:checked` and `:disabled` pseudo-classes to change the appearance of our custom checkbox as its state changes: ```css input[type="checkbox"] { position: relative; width: 1em; height: 1em; border: 1px solid gray; /\* Adjusts the position of the checkboxes on the text baseline \*/ vertical-align: -2px; /\* Set here so that Windows' High-Contrast Mode can override \*/ color: green; } input[type="checkbox"]::before { content: "✔"; position: absolute; font-size: 1.2em; right: -1px; top: -0.3em; visibility: hidden; } input[type="checkbox"]:checked::before { /\* Use `visibility` instead of `display` to avoid recalculating layout \*/ visibility: visible; } input[type="checkbox"]:disabled { border-color: black; background: #ddd; color: gray; } ``` You'll find out more about such pseudo-classes and more in the next article; the above ones do the following: * `:checked` — the checkbox (or radio button) is in a checked state — the user has clicked/activated it. * `:disabled` — the checkbox (or radio button) is in a disabled state — it cannot be interacted with. You can see the live result: We've also created a couple of other examples to give you more ideas: * Styled radio buttons: Custom radio button styling. * Toggle switch example: A checkbox styled to look like a toggle switch. If you view these checkboxes in a browser that doesn't support `appearance`, your custom design will be lost, but they will still look like checkboxes and be usable. What can be done about the "ugly" elements? ------------------------------------------- Now let's turn our attention to the "ugly" controls — the ones that are really hard to thoroughly style. In short, these are drop-down boxes, complex control types like `color` and `datetime-local`, and feedback—oriented controls like `<progress>` and `<meter>`. The problem is that these elements have very different default looks across browsers, and while you can style them in some ways, some parts of their internals are literally impossible to style. If you are prepared to live with some differences in look and feel, you can get away with some simple styling to make sizing consistent, uniform styling of things like background-colors, and usage of appearance to get rid of some system-level styling. Take the following example, which shows a number of the "ugly" form features in action: This example has the following CSS applied to it: ```css body { font-family: "Josefin Sans", sans-serif; margin: 20px auto; max-width: 400px; } form > div { margin-bottom: 20px; } select { appearance: none; width: 100%; height: 100%; } .select-wrapper { position: relative; } .select-wrapper::after { content: "▼"; font-size: 1rem; top: 3px; right: 10px; position: absolute; } button, label, input, select, progress, meter { display: block; font-family: inherit; font-size: 100%; margin: 0; box-sizing: border-box; width: 100%; padding: 5px; height: 30px; } input[type="text"], input[type="datetime-local"], input[type="color"], select { box-shadow: inset 1px 1px 3px #ccc; border-radius: 5px; } label { margin-bottom: 5px; } button { width: 60%; margin: 0 auto; } ``` **Note:** If you want to test these examples across a number of browsers simultaneously, you can find it live here (also see here for the source code). Also bear in mind that we've added some JavaScript to the page that lists the files selected by the file picker, below the control itself. This is a simplified version of the example found on the `<input type="file">` reference page. As you can see, we've done fairly well at getting these to look uniform across modern browsers. We've applied some global normalizing CSS to all the controls and their labels, to get them to size in the same way, adopt their parent font, etc., as mentioned in the previous article: ```css button, label, input, select, progress, meter { display: block; font-family: inherit; font-size: 100%; margin: 0; box-sizing: border-box; width: 100%; padding: 5px; height: 30px; } ``` We also added some uniform shadow and rounded corners to the controls on which it made sense: ```css input[type="text"], input[type="datetime-local"], input[type="color"], select { box-shadow: inset 1px 1px 3px #ccc; border-radius: 5px; } ``` On other controls like range types, progress bars, and meters they just add an ugly box around the control area, so it doesn't make sense. Let's talk about some specifics of each of these types of control, highlighting difficulties along the way. ### Selects and datalists In modern browsers, selects and datalists are generally not too bad to style provided you don't want to vary the look and feel too much from the defaults. We've managed to get the basic look of the boxes looking pretty uniform and consistent. The datalist control is `<input type="text">` anyway, so we knew this wouldn't be a problem. Two things are slightly more problematic. First of all, the select's "arrow" icon that indicates it is a dropdown differs across browsers. It also tends to change if you increase the size of the select box, or resize in an ugly fashion. To fix this in our example we first used our old friend `appearance: none` to get rid of the icon altogether: ```css select { appearance: none; } ``` We then created our own icon using generated content. We put an extra wrapper around the control, because `::before`/`::after` don't work on `<select>` elements (this is because generated content is placed relative to an element's formatting box, but form inputs work more like replaced elements — their display is generated by the browser and put in place — and therefore don't have one): ```html <label for="select">Select a fruit</label> <div class="select-wrapper"> <select id="select" name="select"> <option>Banana</option> <option>Cherry</option> <option>Lemon</option> </select> </div> ``` We then use generated content to generate a little down arrow, and put it in the right place using positioning: ```css .select-wrapper { position: relative; } .select-wrapper::after { content: "▼"; font-size: 1rem; top: 6px; right: 10px; position: absolute; } ``` The second, slightly more important issue is that you don't have control over the box that appears containing the options when you click on the `<select>` box to open it. You can inherit the font set on the parent, but you won't be able to set things like spacing and colors. The same is true for the autocomplete list that appears with `<datalist>`. If you really need full control over the option styling, you'll have to either use some kind of library to generate a custom control, or build your own custom control, or in the case of select use the `multiple` attribute, which makes all the options appear on the page, sidestepping this particular problem: ```html <label for="select">Select fruits</label> <select id="select" name="select" multiple> … </select> ``` Of course, this might also not fit in with the design you are going for, but it's worth noting! ### Date input types The date/time input types (`datetime-local`, `time`, `week`, `month`) all have the same major associated issue. The actual containing box is as easy to style as any text input, and what we've got in this demo looks fine. However, the internal parts of the control (e.g. the popup calendar that you use to pick a date, the spinner that you can use to increment/decrement values) are not stylable at all, and you can't get rid of them using `appearance: none;`. If you really need full control over the styling, you'll have to either use some kind of library to generate a custom control, or build your own. **Note:** It is worth mentioning `<input type="number">` here too — this also has a spinner that you can use to increment/decrement values, so potentially suffers from the same problem. However, in the case of the `number` type the data being collected is simpler, and it is easy to just use a `tel` input type instead which has the appearance of `text`, but displays the numeric keypad in devices with touch keyboards. ### Range input types `<input type="range">` is annoying to style. You can use something like the following to remove the default slider track completely and replace it with a custom style (a thin red track, in this case): ```css input[type="range"] { appearance: none; background: red; height: 2px; padding: 0; outline: 1px solid transparent; } ``` However, it is very difficult to customize the style of the range control's drag handle — to get full control over range styling you'll need to use a whole bunch of complex CSS code, including multiple non-standard, browser-specific pseudo-elements. Check out Styling Cross-Browser Compatible Range Inputs with CSS on CSS tricks for a detailed write-up of what's needed. ### Color input types Input controls of type color are not too bad. In supporting browsers, they tend to just give you a block of solid color with a small border. You can remove the border, just leaving the block of color, using something like this: ```css input[type="color"] { border: 0; padding: 0; } ``` However, a custom solution is the only way to get anything significantly different. ### File input types Inputs of type file are generally OK — as you saw in our example, it is fairly easy to create something that fits in OK with the rest of the page — the output line that is part of the control will inherit the parent font if you tell the input to do so, and you can style the custom list of file names and sizes in any way you want; we created it after all. The only problem with file pickers is that the button provided that you press to open the file picker is completely unstylable — it can't be sized or colored, and it won't even accept a different font. One way around this is to take advantage of the fact that if you have a label associated with a form control, clicking the label will activate the control. So you could hide the actual form input using something like this: ```css input[type="file"] { height: 0; padding: 0; opacity: 0; } ``` And then style the label to act like a button, which when pressed will open the file picker as expected: ```css label[for="file"] { box-shadow: 1px 1px 3px #ccc; background: linear-gradient(to bottom, #eee, #ccc); border: 1px solid rgb(169, 169, 169); border-radius: 5px; text-align: center; line-height: 1.5; } label[for="file"]:hover { background: linear-gradient(to bottom, #fff, #ddd); } label[for="file"]:active { box-shadow: inset 1px 1px 3px #ccc; } ``` You can see the result of the above CSS styling in the below live example (see also styled-file-picker.html live, and the source code). ### Meters and progress bars `<meter>` and `<progress>` are possibly the worst of the lot. As you saw in the earlier example, we can set them to the desired width relatively accurately. But beyond that, they are really difficult to style in any way. They don't handle height settings consistently between each other and between browsers, you can color the background, but not the foreground bar, and setting `appearance: none` on them makes things worse, not better. It is easier to just create your own custom solution for these features, if you want to be able to control the styling, or use a third-party solution such as progressbar.js. The article How to build custom form controls provides an example of how to build a custom designed select with HTML, CSS, and JavaScript. Summary ------- While there are still difficulties using CSS with HTML forms, there are ways to get around many of the problems. There are no clean, universal solutions, but modern browsers offer new possibilities. For now, the best solution is to learn more about the way the different browsers support CSS when applied to HTML form controls. In the next article of this module, we will explore the different UI pseudo-classes available to us in modern browsers for styling forms in different states. * Previous * Overview: Forms * Next ### Advanced Topics * How to build custom form controls * Sending forms through JavaScript * Property compatibility table for form widgets
Sending forms through JavaScript - Learn web development
Sending forms through JavaScript ================================ When a user submits an HTML form, for example by clicking the submit button, the browser makes an HTTP request to send the data in the form. But instead of this declarative approach, web apps sometimes use JavaScript APIs such as `fetch()` to send data programmatically to an endpoint that expects a form submission. This article explains why this is an important use case and how to do it. Why use JavaScript to submit form data? --------------------------------------- Standard HTML form submission, as described in our article on sending form data, loads the URL where the data was sent, which means the browser window navigates with a full page load. However, many web apps, especially progressive web apps and single-page apps, use JavaScript APIs to request data from the server and update the relevant parts of the page, avoiding the overhead of a full page load. For this reason, when these web apps want to submit form data, they use HTML forms only to collect input from the user, but not for data submission. When the user tries to send the data, the application takes control and sends the data using a JavaScript API such as `fetch()`. The problem with JavaScript form submission ------------------------------------------- If the server endpoint to which the web app sends the form data is under the web app developer's control, then they can send the form data in any way they choose: for example, as a JSON object. However, if the server endpoint is expecting a form submission, the web app must encode the data in a particular way. For example, if the data is just textual, it is made of URL-encoded lists of key/value pairs and sent with a `Content-Type` of `application/x-www-form-urlencoded`. If the form includes binary data, it must be sent using the `multipart/form-data` content type. The `FormData` interface takes care of the process of encoding data in this way, and in the rest of this article we'll provide a quick introduction to `FormData`. For more details, see our guide to Using FormData objects. Building a `FormData` object manually ------------------------------------- You can populate a `FormData` object by calling the object's `append()` method for each field you want to add, passing in the field's name and value. The value can be a string, for text fields, or a `Blob`, for binary fields, including `File` objects. In the following example we send data as a form submission when the user clicks a button: ```js async function sendData(data) { // Construct a FormData instance const formData = new FormData(); // Add a text field formData.append("name", "Pomegranate"); // Add a file const selection = await window.showOpenFilePicker(); if (selection.length > 0) { const file = await selection[0].getFile(); formData.append("file", file); } try { const response = await fetch("https://example.org/post", { method: "POST", // Set the FormData instance as the request body body: formData, }); console.log(await response.json()); } catch (e) { console.error(e); } } const send = document.querySelector("#send"); send.addEventListener("click", sendData); ``` 1. We first construct a new, empty, `FormData` object. 2. Next, we call `append()` twice, to add two items to the `FormData` object: a text field and a file. 3. Finally, we make a `POST` request using the `fetch()` API, setting the `FormData` object as the request body. Note that we don't have to set the `Content-Type` header: the correct header is automatically set when we pass a `FormData` object into `fetch()`. Associating a `FormData` object and a `<form>` ---------------------------------------------- If the data you're submitting is really coming from a `<form>`, you can populate the `FormData` instance by passing the form into the `FormData` constructor. Suppose our HTML declares a `<form>` element: ```html <form id="userinfo"> <div> <label for="username">Enter your name:</label> <input type="text" id="username" name="username" value="Dominic" /> </div> <div> <label for="avatar">Select an avatar</label> <input type="file" id="avatar" name="avatar" required /> </div> <input type="submit" value="Submit" /> </form> ``` The form includes a text input, a file input, and a submit button. The JavaScript is as follows: ```js const form = document.querySelector("#userinfo"); async function sendData() { // Associate the FormData object with the form element const formData = new FormData(form); try { const response = await fetch("https://example.org/post", { method: "POST", // Set the FormData instance as the request body body: formData, }); console.log(await response.json()); } catch (e) { console.error(e); } } // Take over form submission form.addEventListener("submit", (event) => { event.preventDefault(); sendData(); }); ``` We add a submit event handler for the form element. This first calls `preventDefault()` to prevent the browser's built-in form submission, so we can take over. Then we call `sendData()`, which retrieves the form element and passes it into the `FormData` constructor. After that, we send the `FormData` instance as an HTTP `POST` request, using `fetch()`. See also -------- ### Learning path * Your first HTML form * How to structure an HTML form * The native form widgets * HTML5 input types * Additional form controls * UI pseudo-classes * Styling HTML forms * Form data validation * Sending form data ### Advanced Topics * **Sending forms through JavaScript** * How to build custom form widgets * HTML forms in legacy browsers * Advanced styling for HTML forms * Property compatibility table for form widgets
Test your skills: Form validation - Learn web development
Test your skills: Form validation ================================= The aim of this skill test is to assess whether you've understood our Client-side form validation article. **Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch. If you get stuck, you can reach out to us in one of our communication channels. Form validation 1 ----------------- In this task, we are providing you with a simple support query form, and we want you to add some validation features to it: 1. Make all of the input fields mandatory to complete before the form can be submitted. 2. Change the type of the "Email address" and "Phone number" fields to make the browser apply some more specific validation suitable for the data being asked for. 3. Give the "User name" field a required length of between 5 and 20 characters, the "Phone number" field a maximum length of 15 characters, and the "Comment" field a maximum length of 200 characters. Try submitting your form — it should refuse to submit until the above constraints are followed, and give suitable error messages. To help, you might want to consider adding some simple CSS to show when a form field is valid or invalid. Download the starting point for this task to work in your own editor or in an online editor. Form validation 2 ----------------- Now we want you to take the same form you saw in the previous task (use your previous answer if you want to), and add some more specific pattern validation to the first three fields using regular expressions. 1. All of the user names in our application consist of a single letter, followed by a dot, followed by three or more letters or numbers. All letters should be lowercase. 2. All of the email addresses for our users consist of one or more letters (lower or upper case) or numbers, followed by "@bigcorp.eu". 3. Remove the length validation from the phone number field if it is present, and set it so that it accepts 10 digits — either 10 digits in a row, or a pattern of three digits, three digits, then four digits, separated by either spaces, dashes, or dots. **Note:** Regular expressions are really challenging if you are new to them, but don't despair — have a go and see where you get to; there is no shame in asking for some help. You can find everything you need to answer these questions at our regular expression reference, and by searching on Stack Overflow. Again, to help you might want to consider adding some simple CSS to show when a form field is valid or invalid. Download the starting point for this task to work in your own editor or in an online editor. Form validation 3 ----------------- In our final task for this set, we are providing you with a similar example to what you saw in the accompanying article — a simple email address entry input. We would like you to use the constraint validation API, plus some form validation attributes, to program some custom error messages. 1. Make the input mandatory to fill in, and give it a minimum length of 10 characters. 2. Add an event listener that checks whether the inputted value is an email address, and whether it is long enough. If it doesn't look like an email address or is too short, provide the user with appropriate custom error messages. Download the starting point for this task to work in your own editor or in an online editor.
Your first form - Learn web development
Your first form =============== * Overview: Forms * Next The first article in our series provides you with your very first experience of creating a web form, including designing a simple form, implementing it using the right HTML form controls and other HTML elements, adding some very simple styling via CSS, and describing how data is sent to a server. We'll expand on each of these subtopics in more detail later on in the module. | | | | --- | --- | | Prerequisites: | A basic understanding of HTML. | | Objective: | To gain familiarity with what web forms are, what they are used for, how to think about designing them, and the basic HTML elements you'll need for simple cases. | What are web forms? ------------------- **Web forms** are one of the main points of interaction between a user and a website or application. Forms allow users to enter data, which is generally sent to a web server for processing and storage (see Sending form data later in the module), or used on the client-side to immediately update the interface in some way (for example, add another item to a list, or show or hide a UI feature). A web form's HTML is made up of one or more **form controls** (sometimes called **widgets**), plus some additional elements to help structure the overall form — they are often referred to as **HTML forms**. The controls can be single or multi-line text fields, dropdown boxes, buttons, checkboxes, or radio buttons, and are mostly created using the `<input>` element, although there are some other elements to learn about too. Form controls can also be programmed to enforce specific formats or values to be entered (**form validation**), and paired with text labels that describe their purpose to both sighted and visually impaired users. Designing your form ------------------- Before starting to code, it's always better to step back and take the time to think about your form. Designing a quick mockup will help you to define the right set of data you want to ask your user to enter. From a user experience (UX) point of view, it's important to remember that the bigger your form, the more you risk frustrating people and losing users. Keep it simple and stay focused: ask only for the data you absolutely need. Designing forms is an important step when you are building a site or application. It's beyond the scope of this article to cover the user experience of forms, but if you want to dig into that topic you should read the following articles: * Smashing Magazine has some good articles about forms UX, including an older but still relevant Extensive Guide To Web Form Usability article. * UXMatters is also a very thoughtful resource with good advice from basic best practices to complex concerns such as multipage forms. In this article, we'll build a simple contact form. Let's make a rough sketch. ![The form to build, roughly sketch](/en-US/docs/Learn/Forms/Your_first_form/form-sketch-low.jpg) Our form will contain three text fields and one button. We are asking the user for their name, their email and the message they want to send. Hitting the button will send their data to a web server. Active learning: Implementing our form HTML ------------------------------------------- Ok, let's have a go at creating the HTML for our form. We will use the following HTML elements: `<form>`, `<label>`, `<input>`, `<textarea>`, and `<button>`. Before you go any further, make a local copy of our simple HTML template — you'll enter your form HTML into here. ### The `<form>` element All forms start with a `<form>` element, like this: ```html <form action="/my-handling-form-page" method="post">…</form> ``` This element formally defines a form. It's a container element like a `<section>` or `<footer>` element, but specifically for containing forms; it also supports some specific attributes to configure the way the form behaves. All of its attributes are optional, but it's standard practice to always set at least the `action` and `method` attributes: * The `action` attribute defines the location (URL) where the form's collected data should be sent when it is submitted. * The `method` attribute defines which HTTP method to send the data with (usually `get` or `post`). **Note:** We'll look at how those attributes work in our Sending form data article later on. For now, add the above `<form>` element into your HTML `<body>`. ### The `<label>`, `<input>`, and `<textarea>` elements Our contact form is not complex: the data entry portion contains three text fields, each with a corresponding `<label>`: * The input field for the name is a single-line text field. * The input field for the email is an input of type email: a single-line text field that accepts only email addresses. * The input field for the message is a `<textarea>`; a multiline text field. In terms of HTML code we need something like the following to implement these form widgets: ```html <form action="/my-handling-form-page" method="post"> <ul> <li> <label for="name">Name:</label> <input type="text" id="name" name="user\_name" /> </li> <li> <label for="mail">Email:</label> <input type="email" id="mail" name="user\_email" /> </li> <li> <label for="msg">Message:</label> <textarea id="msg" name="user\_message"></textarea> </li> </ul> </form> ``` Update your form code to look like the above. The `<li>` elements are there to conveniently structure our code and make styling easier (see later in the article). For usability and accessibility, we include an explicit label for each form control. Note the use of the `for` attribute on all `<label>` elements, which takes as its value the `id` of the form control with which it is associated — this is how you associate a form control with its label. There is great benefit to doing this — it associates the label with the form control, enabling mouse, trackpad, and touch device users to click on the label to activate the corresponding control, and it also provides an accessible name for screen readers to read out to their users. You'll find further details of form labels in How to structure a web form. On the `<input>` element, the most important attribute is the `type` attribute. This attribute is extremely important because it defines the way the `<input>` element appears and behaves. You'll find more about this in the Basic native form controls article later on. * In our simple example, we use the value text for the first input — the default value for this attribute. It represents a basic single-line text field that accepts any kind of text input. * For the second input, we use the value email, which defines a single-line text field that only accepts a well-formed email address. This turns a basic text field into a kind of "intelligent" field that will perform some validation checks on the data typed by the user. It also causes a more appropriate keyboard layout for entering email addresses (e.g. with an @ symbol by default) to appear on devices with dynamic keyboards, like smartphones. You'll find out more about form validation in the client-side form validation article later on. Last but not least, note the syntax of `<input>` vs. `<textarea></textarea>`. This is one of the oddities of HTML. The `<input>` tag is a void element, meaning that it doesn't need a closing tag. `<textarea>` is not a void element, meaning it should be closed with the proper ending tag. This has an impact on a specific feature of forms: the way you define the default value. To define the default value of an `<input>` element you have to use the `value` attribute like this: ```html <input type="text" value="by default this element is filled with this text" /> ``` On the other hand, if you want to define a default value for a `<textarea>`, you put it between the opening and closing tags of the `<textarea>` element, like this: ```html <textarea> by default this element is filled with this text </textarea> ``` ### The `<button>` element The markup for our form is almost complete; we just need to add a button to allow the user to send, or "submit", their data once they have filled out the form. This is done by using the `<button>` element; add the following just above the closing `</ul>` tag: ```html <li class="button"> <button type="submit">Send your message</button> </li> ``` The `<button>` element also accepts a `type` attribute — this accepts one of three values: `submit`, `reset`, or `button`. * A click on a `submit` button (the default value) sends the form's data to the web page defined by the `action` attribute of the `<form>` element. * A click on a `reset` button resets all the form widgets to their default value immediately. From a UX point of view, this is considered bad practice, so you should avoid using this type of button unless you really have a good reason to include one. * A click on a `button` button does *nothing*! That sounds silly, but it's amazingly useful for building custom buttons — you can define their chosen functionality with JavaScript. **Note:** You can also use the `<input>` element with the corresponding `type` to produce a button, for example `<input type="submit">`. The main advantage of the `<button>` element is that the `<input>` element only allows plain text in its label whereas the `<button>` element allows full HTML content, allowing more complex, creative button content. Basic form styling ------------------ Now that you have finished writing your form's HTML code, try saving it and looking at it in a browser. At the moment, you'll see that it looks rather ugly. **Note:** If you don't think you've got the HTML code right, try comparing it with our finished example — see first-form.html (also see it live). Forms are notoriously tricky to style nicely. It is beyond the scope of this article to teach you form styling in detail, so for the moment we will just get you to add some CSS to make it look OK. First of all, add a `<style>` element to your page, inside your HTML head. It should look like so: ```html <style> … </style> ``` Inside the `style` tags, add the following CSS: ```css form { /\* Center the form on the page \*/ margin: 0 auto; width: 400px; /\* Form outline \*/ padding: 1em; border: 1px solid #ccc; border-radius: 1em; } ul { list-style: none; padding: 0; margin: 0; } form li + li { margin-top: 1em; } label { /\* Uniform size & alignment \*/ display: inline-block; width: 90px; text-align: right; } input, textarea { /\* To make sure that all text fields have the same font settings By default, textareas have a monospace font \*/ font: 1em sans-serif; /\* Uniform text field size \*/ width: 300px; box-sizing: border-box; /\* Match form field borders \*/ border: 1px solid #999; } input:focus, textarea:focus { /\* Additional highlight for focused elements \*/ border-color: #000; } textarea { /\* Align multiline text fields with their labels \*/ vertical-align: top; /\* Provide space to type some text \*/ height: 5em; } .button { /\* Align buttons with the text fields \*/ padding-left: 90px; /\* same size as the label elements \*/ } button { /\* This extra margin represent roughly the same space as the space between the labels and their text fields \*/ margin-left: 0.5em; } ``` Save and reload, and you'll see that your form should look much less ugly. **Note:** You can find our version on GitHub at first-form-styled.html (also see it live). Sending form data to your web server ------------------------------------ The last part, and perhaps the trickiest, is to handle form data on the server side. The `<form>` element defines where and how to send the data thanks to the `action` and `method` attributes. We provide a `name` attribute for each form control. The names are important on both the client- and server-side; they tell the browser which name to give each piece of data and, on the server side, they let the server handle each piece of data by name. The form data is sent to the server as name/value pairs. To name the data in a form, you need to use the `name` attribute on each form widget that will collect a specific piece of data. Let's look at some of our form code again: ```html <form action="/my-handling-form-page" method="post"> <ul> <li> <label for="name">Name:</label> <input type="text" id="name" name="user\_name" /> </li> <li> <label for="mail">Email:</label> <input type="email" id="mail" name="user\_email" /> </li> <li> <label for="msg">Message:</label> <textarea id="msg" name="user\_message"></textarea> </li> … </ul> </form> ``` In our example, the form will send 3 pieces of data named "`user_name`", "`user_email`", and "`user_message`". That data will be sent to the URL "`/my-handling-form-page`" using the HTTP `POST` method. On the server side, the script at the URL "`/my-handling-form-page`" will receive the data as a list of 3 key/value items contained in the HTTP request. The way this script will handle that data is up to you. Each server-side language (PHP, Python, Ruby, Java, C#, etc.) has its own mechanism of handling form data. It's beyond the scope of this guide to go deeply into that subject, but if you want to know more, we have provided some examples in our Sending form data article later on. Summary ------- Congratulations, you've built your first web form. It looks like this live: ``` <form action="/my-handling-form-page" method="post"> <div> <label for="name">Name:</label> <input type="text" id="name" name="user\_name" /> </div> <div> <label for="mail">Email:</label> <input type="email" id="mail" name="user\_email" /> </div> <div> <label for="msg">Message:</label> <textarea id="msg" name="user\_message"></textarea> </div> <div class="button"> <button type="submit">Send your message</button> </div> </form> ``` ``` form { /\* Just to center the form on the page \*/ margin: 0 auto; width: 400px; /\* To see the limits of the form \*/ padding: 1em; border: 1px solid #ccc; border-radius: 1em; } div + div { margin-top: 1em; } label { /\* To make sure that all label have the same size and are properly align \*/ display: inline-block; width: 90px; text-align: right; } input, textarea { /\* To make sure that all text field have the same font settings By default, textarea are set with a monospace font \*/ font: 1em sans-serif; /\* To give the same size to all text field \*/ width: 300px; -moz-box-sizing: border-box; box-sizing: border-box; /\* To harmonize the look & feel of text field border \*/ border: 1px solid #999; } input:focus, textarea:focus { /\* To give a little highlight on active elements \*/ border-color: #000; } textarea { /\* To properly align multiline text field with their label \*/ vertical-align: top; /\* To give enough room to type some text \*/ height: 5em; /\* To allow users to resize any textarea vertically It works only on Chrome, Firefox and Safari \*/ resize: vertical; } .button { /\* To position the buttons to the same position of the text fields \*/ padding-left: 90px; /\* same size as the label elements \*/ } button { /\* This extra margin represent the same space as the space between the labels and their text fields \*/ margin-left: 0.5em; } ``` That's only the beginning, however — now it's time to take a deeper look. Forms have way more power than what we saw here and the other articles in this module will help you to master the rest. * Overview: Forms * Next ### Advanced Topics * How to build custom form controls * Sending forms through JavaScript * Property compatibility table for form widgets
Test your skills: HTML5 controls - Learn web development
Test your skills: HTML5 controls ================================ The aim of this skill test is to assess whether you've understood our The HTML5 input types article. **Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch. If you get stuck, you can reach out to us in one of our communication channels. HTML controls 1 --------------- First, let's explore some input types. Create appropriate inputs for a user to update their details for: 1. Email 2. Website 3. Phone number 4. Favorite color Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. HTML controls 2 --------------- Next, we want you to implement a slider control to allow the user to choose a maximum number of people to invite to their party. 1. Implement a basic slider control to go along with the provided label. 2. Give it a minimum value of 1, maximum value of 30, initial value of 10 and element `id` of `max-invite`. 3. Create a corresponding output element to put the current value of the slider into. Give it a class of `invite-output`, and semantically associate it with the input. If you do this correctly, the JavaScript included on the page will automatically update the output value when the slider is moved. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor.
Test your skills: Advanced styling - Learn web development
Test your skills: Advanced styling ================================== The aim of this skill test is to assess whether you've understood our Advanced form styling and UI pseudo-classes articles. **Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch. If you get stuck, you can reach out to us in one of our communication channels. Advanced form styling 1 ----------------------- In our first advanced styling tasks, we want you to handle making a search input as consistent as possible across browsers — a trickier task than with standard text inputs, even on modern browsers. We've already provided you with a basic reset to build upon. 1. First of all, try giving the search box a consistent width, height, padding, and border color across browsers. 2. You'll find that some browsers will not behave in terms of the form element's height. This is due to native OS styling being used in some cases. How can you remove this native styling? 3. Once you've removed the native styling, you'll need to add back one of the features it was providing, to keep the same look and feel we originally had. How do you do this? 4. One thing that is inconsistent across browsers (particularly looking at Safari here) is the position of the standard blue focus outline. How can you remove this? 5. There is a major problem with just getting rid of the blue focus outline. What is it? Can you add some kind of styling back in so that users can tell when the search box is being hovered or focused? 6. Another thing that commonly denotes a search box is a magnifying glass icon. We've made one available in the same directory as our HTML files — see search-24px.png — plus a `<div>` element after the search input to help you attach it, should you need it. Can you figure out a sensible way to attach it, and can you use some CSS to get it to sit to the right of the search box, and be lined up vertically as well? Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Advanced form styling 2 ----------------------- In our next task we provide you with a set of three radio buttons. We want you to give them custom styling. We've already provided you with a basic reset to build upon. 1. First of all, get rid of their default styling. 2. Next, give the radio buttons a reasonable base style — the style they have when the page first loads. This can be anything you like, but you probably want to set a width and height (of somewhere between about 18 and 24 pixels), and a subtle border and/or background color. 3. Now give the radio buttons a different style for when they are selected. 4. Align the radio buttons nicely with the labels. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Advanced form styling 3 ----------------------- In our final task for this assessment series, we provide you with a feedback form that is already nicely-styled — you've already seen something similar if you've worked through our UI pseudo-classes article, and now we want you to come up with your own solution. What we'd like you to do is make use of some advanced pseudo-classes to provide some useful indicators of validity. 1. First of all, we want you to provide some specific styling to visually indicate which inputs have to be filled in — they cannot be left empty. 2. Second, we want you to provide a useful visual indicator of whether the data entered inside each input is valid or not. Download the starting point for this task to work in your own editor or in an online editor.
HTML forms in legacy browsers - Learn web development
HTML forms in legacy browsers ============================= All web developers learn very quickly (and sometimes painfully) that the Web is a very rough place for them. Our worst curse is legacy browsers. Okay, let's admit it, when we said "legacy browser" we all have in mind "Internet Explorer", but they are far from the only ones. In the mobile world, when neither the browser nor the OS can be updated such as on older Android phones or iPhones, the stock browsers that don't update are also legacy browsers. Dealing with this wilderness is part of the job. Fortunately, there are a few tricks to know that can help you to solve most of the problems caused by legacy browsers. If a browser doesn't support an HTML `<input>` type, it doesn't fail: it just uses the default value of `type=text`. Learn about the issues ---------------------- To understand common patterns, it helps to read documentation. If you are reading this on MDN, you are at the right place to start. Just check the support of the elements (or DOM interfaces) you want to use. MDN has compatibility tables available for most elements, properties and APIs that can be used in a web page. Because HTML forms involves complex interaction, there is one important rule: keep it simple, also known as the "KISS principal". There are so many cases where we want forms that are "nicer" or "with advanced functionality", but building efficient HTML Forms is not a question of design or technology. Rather, it's about simplicity, intuitiveness, and ease of user interaction. The tutorial, forms usability on UX For The Masses, explains it well. ### Graceful degradation is web developer's best friend Graceful degradation and progressive enhancement are development patterns that allow you to build great stuff by supporting a wide range of browsers at the same time. When you build something for a modern browser, and you want to be sure it will work, one way or another, on legacy browsers, you are performing graceful degradation. Let's see some examples related to HTML forms. #### HTML input types All HTML input types are useable in all browsers, even ancient ones, because the way they degrade is highly predictable. If a browser does not know the value of the `type` attribute of an `<input>` element, it will fall back as if the value were `text`. ```html <label for="myColor"> Pick a color <input type="color" id="myColor" name="color" /> </label> ``` | Supported | Not supported | | --- | --- | | Screen shot of the color input on Chrome for Mac OSX | Screen shot of the color input on Firefox for Mac OSX | #### Form buttons There are two ways to define buttons within HTML forms: * The `<input>` element with its attribute `type` set to the values `button`, `submit`, `reset` or `image` * The `<button>` element ##### `<input>` The `<input>` element can make things a little difficult if you want to apply some CSS by using the element selector: ```html <input type="button" value="click me" /> ``` If we remove the border on all inputs, can we restore the default appearance on input buttons only? ```css input { /\* This rule turns off the default rendering for the input types that have a border, including buttons defined with an input element \*/ border: 1px solid #ccc; } input[type="button"] { /\* This does NOT restore the default rendering \*/ border: none; } input[type="button"] { /\* These don't either! Actually there is no standard way to do it in any browser \*/ border: auto; border: initial; } input[type="button"] { /\* This will come the closest to restoring default rendering. \*/ border: revert; } ``` See the global CSS `revert` value for more information. ##### `<button>` The `<button>` element suffered from two issues that are now resolved: * A bug in old versions of Internet Explorer sent the HTML content available between the starting and ending tag of the `<button>` element instead of the content of the `value` attribute when clicked. This was only an issue if that value needed to be sent, such as when data processing depends on which button a user clicked. * Some very old browsers did not use `submit` as the default value for the `type` attribute. While resolved in all modern browsers, it is still recommended to always set the `type` attribute on `<button>` elements. ```html <!-- Clicking this button sent "<em>Do A</em>" instead of "A" in some cases --> <button type="submit" name="IWantTo" value="A"> <em>Do A</em> </button> ``` Choosing one solution or the other is up to you based on your project's constraints. ### Let go of CSS One of the big issues with HTML Forms is styling form widgets with CSS. Form controls appearance is browser and operating system specific. For example, the input of color type looks different in Safari, Chrome and Firefox browser, but the color picker widget is the same in all browsers on a device as it opens up the operating system's native color picker. It's generally a good idea to not alter the default appearance of form control because altering one CSS property value may alter some input types but not others. For example, if you declare `input { font-size: 2rem; }`, it will impact `number`, `date`, and `text`, but not `color` or `range`. If you alter a property, that may impact the appearance of the widget in unexpected ways. For example, `[value] { background-color: #ccc; }` may have been used to target every `<input>` with a `value` attribute, but changing the background-color or border radius on a `<meter>` will lead to likely unexpected results that differ across browsers. You can declare `appearance: none;` to remove the browser styles, but that generally defeats the purpose: as you lose all styling, removing the default look and feel your visitors are used to. To summarize, when it comes to styling form control widgets, the side effects of styling them with CSS can be unpredictable. So don't. As you can see from the complexity of the Property compatibility table for form widgets article, it's very difficult. Even if it's still possible to do a few adjustments on text elements (such as sizing or font color), there are always side effects. The best approach remains to not style HTML Form widgets at all. But you can still apply styles to all the surrounding items. And, if you must alter the default styles of your form widgets, define a style guide to ensure consistency among all your form controls so user experience is not destroyed. You can also investigate some hard techniques such as rebuilding widgets with JavaScript. But in that case, do not hesitate to charge your client for such foolishness. Feature detection and polyfills ------------------------------- CSS and JavaScript are awesome technologies, but it's important to ensure you don't break legacy browsers. Before using features that aren't fully supported in the browsers your targeting, you should feature detect: ### CSS feature detection Before styling a replaced form control widget, you can check to see if the browser supports the features you plan on using `@supports`: ```css @supports (appearance: none) { input[type="search"] { appearance: none; /\* restyle the search input \*/ } } ``` The `appearance` property can be used to display an element using platform-native styling, or, as is done with the value of `none`, remove default platform-native based styling. ### Unobtrusive JavaScript One of the biggest problems is the availability of APIs. For that reason, it's considered best practice to work with "unobtrusive" JavaScript. It's a development pattern that defines two requirements: * A strict separation between structure and behaviors. * If the code breaks, the content and the basic functionalities must remain accessible and usable. The principles of unobtrusive JavaScript (originally written by Peter-Paul Koch for Dev.Opera.com) describes these ideas very well. ### Pay attention to performance Even though some polyfills are very aware of performance, loading additional scripts can affect the performance of your application. This is especially critical with legacy browsers; many of them have a very slow JavaScript engine that can make the execution of all your polyfills painful for the user. Performance is a subject on its own, but legacy browsers are very sensitive to it: basically, they are slow and the more polyfills they need, the more JavaScript they have to process. So they are doubly burdened compared to modern browsers. Test your code with legacy browsers to see how they actually perform. Sometimes, dropping some functionality leads to a better user experience than having exactly the same functionality in all browsers. As a last reminder, just always think about the end users. Conclusion ---------- As you can see, considering browser and operating system default form control appearance is important. There are many techniques to handle these issue; however mastering all of them is beyond the scope of this article. The basic premise is to consider whether altering the default implementation is worth the work before embarking on the challenge. If you read all the articles of this HTML Forms guide, you should now be at ease with using forms. If you discover new techniques or hints, please help improve the guide. See also -------- ### Learning path * Your first HTML form * How to structure an HTML form * The native form widgets * HTML5 input types * Additional form controls * UI pseudo-classes * Styling HTML forms * Form data validation * Sending form data ### Advanced Topics * Sending forms through JavaScript * How to build custom form widgets * **HTML forms in legacy browsers** * Advanced styling for HTML forms * Property compatibility table for form widgets
How to structure a web form - Learn web development
How to structure a web form =========================== * Previous * Overview: Forms * Next With the basics out of the way, we'll now look in more detail at the elements used to provide structure and meaning to the different parts of a form. | | | | --- | --- | | Prerequisites: | A basic understanding of HTML. | | Objective: | To understand how to structure HTML forms and give them semantics so they are usable and accessible. | The flexibility of forms makes them one of the most complex structures in HTML; you can build any kind of basic form using dedicated form elements and attributes. Using the correct structure when building an HTML form will help ensure that the form is both usable and accessible. The <form> element ------------------ The `<form>` element formally defines a form and attributes that determine the form's behavior. Each time you want to create an HTML form, you must start it by using this element, nesting all the contents inside. Many assistive technologies and browser plugins can discover `<form>` elements and implement special hooks to make them easier to use. We already met this in the previous article. **Warning:** It's strictly forbidden to nest a form inside another form. Nesting can cause forms to behave unpredictably, so it is a bad idea. It's always possible to use a form control outside of a `<form>` element. If you do so, by default that control has nothing to do with any form unless you associate it with a form using its `form` attribute. This was introduced to let you explicitly bind a control with a form even if it is not nested inside it. Let's move forward and cover the structural elements you'll find nested in a form. The <fieldset> and <legend> elements ------------------------------------ The `<fieldset>` element is a convenient way to create groups of widgets that share the same purpose, for styling and semantic purposes. You can label a `<fieldset>` by including a `<legend>` element just below the opening `<fieldset>` tag. The text content of the `<legend>` formally describes the purpose of the `<fieldset>` it is included inside. Many assistive technologies will use the `<legend>` element as if it is a part of the label of each control inside the corresponding `<fieldset>` element. For example, some screen readers such as Jaws and NVDA will speak the legend's content before speaking the label of each control. Here is a little example: ```html <form> <fieldset> <legend>Fruit juice size</legend> <p> <input type="radio" name="size" id="size\_1" value="small" /> <label for="size\_1">Small</label> </p> <p> <input type="radio" name="size" id="size\_2" value="medium" /> <label for="size\_2">Medium</label> </p> <p> <input type="radio" name="size" id="size\_3" value="large" /> <label for="size\_3">Large</label> </p> </fieldset> </form> ``` **Note:** You can find this example in fieldset-legend.html (see it live also). When reading the above form, a screen reader will speak "Fruit juice size small" for the first widget, "Fruit juice size medium" for the second, and "Fruit juice size large" for the third. The use case in this example is one of the most important. Each time you have a set of radio buttons, you should nest them inside a `<fieldset>` element. There are other use cases, and in general the `<fieldset>` element can also be used to section a form. Ideally, long forms should be spread across multiple pages, but if a form is getting long and must be on a single page, putting the different related sections inside different fieldsets improves usability. Because of its influence over assistive technology, the `<fieldset>` element is one of the key elements for building accessible forms; however, it is your responsibility not to abuse it. If possible, each time you build a form, try to listen to how a screen reader interprets it. If it sounds odd, try to improve the form structure. The <label> element ------------------- As we saw in the previous article, The `<label>` element is the formal way to define a label for an HTML form widget. This is the most important element if you want to build accessible forms — when implemented properly, screen readers will speak a form element's label along with any related instructions, as well as it being useful for sighted users. Take this example, which we saw in the previous article: ```html <label for="name">Name:</label> <input type="text" id="name" name="user\_name" /> ``` With the `<label>` associated correctly with the `<input>` via its `for` attribute (which contains the `<input>` element's `id` attribute), a screen reader will read out something like "Name, edit text". There is another way to associate a form control with a label — nest the form control within the `<label>`, implicitly associating it. ```html <label for="name"> Name: <input type="text" id="name" name="user\_name" /> </label> ``` Even in such cases however, it is considered best practice to set the `for` attribute to ensure all assistive technologies understand the relationship between label and widget. If there is no label, or if the form control is neither implicitly nor explicitly associated with a label, a screen reader will read out something like "Edit text blank", which isn't very helpful at all. ### Labels are clickable, too! Another advantage of properly set up labels is that you can click or tap the label to activate the corresponding widget. This is useful for controls like text inputs, where you can click the label as well as the input to focus it, but it is especially useful for radio buttons and checkboxes — the hit area of such a control can be very small, so it is useful to make it as easy to activate as possible. For example, clicking on the "I like cherry" label text in the example below will toggle the selected state of the *taste\_cherry* checkbox: ```html <form> <p> <input type="checkbox" id="taste\_1" name="taste\_cherry" value="cherry" /> <label for="taste\_1">I like cherry</label> </p> <p> <input type="checkbox" id="taste\_2" name="taste\_banana" value="banana" /> <label for="taste\_2">I like banana</label> </p> </form> ``` **Note:** You can find this example in checkbox-label.html (see it live also). ### Multiple labels Strictly speaking, you can put multiple labels on a single widget, but this is not a good idea as some assistive technologies can have trouble handling them. In the case of multiple labels, you should nest a widget and its labels inside a single `<label>` element. Let's consider this example: ```html <p>Required fields are followed by <span aria-label="required">*</span>.</p> <!-- So this: --> <!--div> <label for="username">Name:</label> <input id="username" type="text" name="username" required> <label for="username"><span aria-label="required">\*</label> </div--> <!-- would be better done like this: --> <!--div> <label for="username"> <span>Name:</span> <input id="username" type="text" name="username" required> <span aria-label="required">\*</span> </label> </div--> <!-- But this is probably best: --> <div> <label for="username">Name: <span aria-label="required">*</span></label> <input id="username" type="text" name="username" required /> </div> ``` The paragraph at the top states a rule for required elements. The rule must be included *before* it is used so that sighted users and users of assistive technologies such as screen readers can learn what it means before they encounter a required element. While this helps inform users what an asterisk means, it can not be relied upon. A screen reader will speak an asterisk as "*star*" when encountered. When hovered by a sighted mouse user, "*required*" should appear, which is achieved by use of the `title` attribute. Titles being read aloud depends on the screen reader's settings, so it is more reliable to also include the `aria-label` attribute, which is always read by screen readers. The above variants increase in effectiveness as you go through them: * In the first example, the label is not read out at all with the input — you just get "edit text blank", plus the actual labels are read out separately. The multiple `<label>` elements confuse the screen reader. * In the second example, things are a bit clearer — the label read out along with the input is "name star name edit text required", and the labels are still read out separately. Things are still a bit confusing, but it's a bit better this time because the `<input>` has a label associated with it. * The third example is best — the actual label is read out all together, and the label read out with the input is "name required edit text". **Note:** You might get slightly different results, depending on your screen reader. This was tested in VoiceOver (and NVDA behaves similarly). We'd love to hear about your experiences too. **Note:** You can find this example on GitHub as required-labels.html (see it live also). Don't test the example with 2 or 3 of the versions uncommented — screen readers will definitely get confused if you have multiple labels AND multiple inputs with the same ID! Common HTML structures used with forms -------------------------------------- Beyond the structures specific to web forms, it's good to remember that form markup is just HTML. This means that you can use all the power of HTML to structure a web form. As you can see in the examples, it's common practice to wrap a label and its widget with a `<li>` element within a `<ul>` or `<ol>` list. `<p>` and `<div>` elements are also commonly used. Lists are recommended for structuring multiple checkboxes or radio buttons. In addition to the `<fieldset>` element, it's also common practice to use HTML titles (e.g. h1, h2) and sectioning (e.g. `<section>`) to structure complex forms. Above all, it is up to you to find a comfortable coding style that results in accessible, usable forms. Each separate section of functionality should be contained in a separate `<section>` element, with `<fieldset>` elements to contain radio buttons. ### Active learning: building a form structure Let's put these ideas into practice and build a slightly more involved form — a payment form. This form will contain a number of control types that you may not yet understand. Don't worry about this for now; you'll find out how they work in the next article (Basic native form controls). For now, read the descriptions carefully as you follow the below instructions, and start to form an appreciation of which wrapper elements we are using to structure the form, and why. 1. To start with, make a local copy of our blank template file in a new directory on your computer. 2. Next, create your form by adding a `<form>` element: ```html <form> ``` 3. Inside the `<form>` element, add a heading and paragraph to inform users how required fields are marked: ```html <h1>Payment form</h1> <p> Required fields are followed by <strong><span aria-label="required">*</span></strong>. </p> ``` 4. Next, we'll add a larger section of code into the form, below our previous entry. Here you'll see that we are wrapping the contact information fields inside a distinct `<section>` element. Moreover, we have a set of three radio buttons, each of which we are putting inside its own list (`<li>`) element. We also have two standard text `<input>`s and their associated `<label>` elements, each contained inside a `<p>`, and a password input for entering a password. Add this code to your form: ```html <section> <h2>Contact information</h2> <fieldset> <legend>Title</legend> <ul> <li> <label for="title\_1"> <input type="radio" id="title\_1" name="title" value="A" /> Ace </label> </li> <li> <label for="title\_2"> <input type="radio" id="title\_2" name="title" value="K" /> King </label> </li> <li> <label for="title\_3"> <input type="radio" id="title\_3" name="title" value="Q" /> Queen </label> </li> </ul> </fieldset> <p> <label for="name"> <span>Name: </span> <strong><span aria-label="required">*</span></strong> </label> <input type="text" id="name" name="username" required /> </p> <p> <label for="mail"> <span>Email: </span> <strong><span aria-label="required">*</span></strong> </label> <input type="email" id="mail" name="usermail" required /> </p> <p> <label for="pwd"> <span>Password: </span> <strong><span aria-label="required">*</span></strong> </label> <input type="password" id="pwd" name="password" required /> </p> </section> ``` 5. The second `<section>` of our form is the payment information. We have three distinct controls along with their labels, each contained inside a `<p>`. The first is a drop-down menu (`<select>`) for selecting credit card type. The second is an `<input>` element of type `tel`, for entering a credit card number; while we could have used the `number` type, we don't want the number's spinner UI. The last one is an `<input>` element of type `text`, for entering the expiration date of the card; this includes a *placeholder* attribute indicating the correct format, and a *pattern* that tests that the entered date has the correct format. These newer input types are reintroduced in The HTML5 input types. Enter the following below the previous section: ```html <section> <h2>Payment information</h2> <p> <label for="card"> <span>Card type:</span> </label> <select id="card" name="usercard"> <option value="visa">Visa</option> <option value="mc">Mastercard</option> <option value="amex">American Express</option> </select> </p> <p> <label for="number"> <span>Card number:</span> <strong><span aria-label="required">*</span></strong> </label> <input type="tel" id="number" name="cardnumber" required /> </p> <p> <label for="expiration"> <span>Expiration date:</span> <strong><span aria-label="required">*</span></strong> </label> <input type="text" id="expiration" required placeholder="MM/YY" pattern="^(0[1-9]|1[0-2])\/([0-9]{2})$" /> </p> </section> ``` 6. The last section we'll add is a lot simpler, containing only a `<button>` of type `submit`, for submitting the form data. Add this to the bottom of your form now: ```html <section> <p> <button type="submit">Validate the payment</button> </p> </section> ``` 7. Finally, complete your form by adding the outer `<form>` closing tag: ```html </form> ``` ``` h1 { margin-top: 0; } ul { margin: 0; padding: 0; list-style: none; } form { margin: 0 auto; width: 400px; padding: 1em; border: 1px solid #ccc; border-radius: 1em; } div + div { margin-top: 1em; } label span { display: inline-block; text-align: right; } input, textarea { font: 1em sans-serif; width: 250px; box-sizing: border-box; border: 1px solid #999; } input[type="checkbox"], input[type="radio"] { width: auto; border: none; } input:focus, textarea:focus { border-color: #000; } textarea { vertical-align: top; height: 5em; resize: vertical; } fieldset { width: 250px; box-sizing: border-box; border: 1px solid #999; } button { margin: 20px 0 0 0; } label { position: relative; display: inline-block; } p label { width: 100%; } label em { position: absolute; right: 5px; top: 20px; } ``` We applied some extra CSS to the finished form below. If you'd like to make changes to the appearance of your form, you can copy styles from the example or visit Styling web forms. Test your skills! ----------------- You've reached the end of this article, but can you remember the most important information? You can find a further test to verify that you've retained this information before you move on — see Test your skills: Form structure. Summary ------- You now have all the knowledge you'll need to properly structure your web forms. We will cover many of the features introduced here in the next few articles, with the next article looking in more detail at using all the different types of form widgets you'll want to use to collect information from your users. See also -------- * A List Apart: *Sensible Forms: A Form Usability Checklist* * Previous * Overview: Forms * Next ### Advanced Topics * How to build custom form controls * Sending forms through JavaScript * Property compatibility table for form widgets
Other form controls - Learn web development
Other form controls =================== * Previous * Overview: Forms * Next We now look at the functionality of non-`<input>` form elements in detail, from other control types such as drop-down lists and multi-line text fields, to other useful form features such as the `<output>` element (which we saw in action in the previous article), and progress bars. | | | | --- | --- | | Prerequisites: | A basic understanding of HTML. | | Objective: | To understand the non-`<input>` form features, and how to implement them using HTML. | Multi-line text fields ---------------------- A multi-line text field is specified using a `<textarea>` element, rather than using the `<input>` element. ```html <textarea cols="30" rows="8"></textarea> ``` This renders like so: The main difference between a `<textarea>` and a regular single-line text field is that users are allowed to include hard line breaks (i.e. pressing return) that will be included when the data is submitted. `<textarea>` also takes a closing tag; any default text you want it to contain should be put between the opening and closing tags. In contrast, the `<input>` is a void element with no closing tag — any default value is put inside the `value` attribute. Note that even though you can put anything inside a `<textarea>` element (including other HTML elements, CSS, and JavaScript), because of its nature, it is all rendered as if it was plain text content. (Using `contenteditable` on non-form controls provides an API for capturing HTML/"rich" content instead of plain text). Visually, the text entered wraps and the form control is by default resizable. Modern browsers provide a drag handle that you can drag to increase/decrease the size of the text area. The following screenshots show default, focused, and disabled `<textarea>` elements in Firefox 71 and Safari 13 on macOS and in Edge 18, Yandex 14, Firefox 71, and Chrome 79 on Windows 10. ![The default, focused, and disabled 'textarea' element in Firefox 71 and Safari 13 on Mac OSX and Edge 18, Yandex 14, Firefox and Chrome on Windows 10.](/en-US/docs/Learn/Forms/Other_form_controls/textarea_basic.png) **Note:** You can find a slightly more interesting example of text area usage in the example we put together in the first article of the series (see the source code also). ### Controlling multi-line rendering `<textarea>` accepts three attributes to control its rendering across several lines: `cols` Specifies the visible width (columns) of the text control, measured in average character widths. This is effectively the starting width, as it can be changed by resizing the `<textarea>`, and overridden using CSS. The default value if none is specified is 20. `rows` Specifies the number of visible text rows for the control. This is effectively the starting height, as it can be changed by resizing the `<textarea>`, and overridden using CSS. The default value if none is specified is 2. `wrap` Specifies how the control wraps text. The values are `soft` (the default value), which means the text submitted is not wrapped but the text rendered by the browser is wrapped; `hard` (the `cols` attribute must be specified when using this value), which means both the submitted and rendered texts are wrapped, and `off`, which stops wrapping. ### Controlling textarea resizability The ability to resize a `<textarea>` is controlled with the CSS `resize` property. Its possible values are: * `both`: The default — allows resizing horizontally and vertically. * `horizontal`: Allows resizing only horizontally. * `vertical`: Allows resizing only vertically. * `none`: Allows no resizing. * `block` and `inline`: Experimental values that allow resizing in the `block` or `inline` direction only (this varies depending on the directionality of your text; read Handling different text directions if you want to find out more.) Play with the interactive example at the top of the `resize` reference page for a demonstration of how these work. Drop-down controls ------------------ Drop-down controls are a simple way to let users select from many options without taking up much space in the user interface. HTML has two types of drop-down controls: the **select box** and the **autocomplete box**. The interaction is the same in both the types of drop-down controls — after the control is activated, the browser displays a list of values the user can select from. **Note:** You can find examples of all the drop-down box types on GitHub at drop-down-content.html (see it live also). ### Select box A simple select box is created with a `<select>` element with one or more `<option>` elements as its children, each of which specifies one of its possible values. #### Basic example ```html <select id="simple" name="simple"> <option>Banana</option> <option selected>Cherry</option> <option>Lemon</option> </select> ``` If required, the default value for the select box can be set using the `selected` attribute on the desired `<option>` element — this option is then preselected when the page loads. #### Using optgroup The `<option>` elements can be nested inside `<optgroup>` elements to create visually associated groups of values: ```html <select id="groups" name="groups"> <optgroup label="fruits"> <option>Banana</option> <option selected>Cherry</option> <option>Lemon</option> </optgroup> <optgroup label="vegetables"> <option>Carrot</option> <option>Eggplant</option> <option>Potato</option> </optgroup> </select> ``` On the `<optgroup>` element, the value of the `label` attribute is displayed before the values of the nested options. The browser usually sets them visually apart from the options (i.e. by being bolded and at a different nesting level) so they are less likely to be confused for actual options. #### Using the value attribute If an `<option>` element has an explicit `value` attribute set on it, that value is sent when the form is submitted with that option selected. If the `value` attribute is omitted, as with the examples above, the content of the `<option>` element is used as the value. So `value` attributes are not needed, but you might find a reason to want to send a shortened or different value to the server than what is visually shown in the select box. For example: ```html <select id="simple" name="simple"> <option value="banana">Big, beautiful yellow banana</option> <option value="cherry">Succulent, juicy cherry</option> <option value="lemon">Sharp, powerful lemon</option> </select> ``` By default, the height of the select box is enough to display a single value. The optional `size` attribute provides control over how many options are visible when the select does not have focus. ### Multiple choice select box By default, a select box lets a user select only one value. By adding the `multiple` attribute to the `<select>` element, you can allow users to select several values. Users can select multiple values by using the default mechanism provided by the operating system (e.g., on the desktop, multiple values can be clicked while holding down `Cmd`/`Ctrl` keys). ```html <select id="multi" name="multi" multiple size="2"> <optgroup label="fruits"> <option>Banana</option> <option selected>Cherry</option> <option>Lemon</option> </optgroup> <optgroup label="vegetables"> <option>Carrot</option> <option>Eggplant</option> <option>Potato</option> </optgroup> </select> ``` **Note:** In the case of multiple choice select boxes, you'll notice that the select box no longer displays the values as drop-down content — instead, all values are displayed at once in a list, with the optional `size` attribute determining the height of the widget. **Note:** All browsers that support the `<select>` element also support the `multiple` attribute. ### Autocomplete box You can provide suggested, automatically-completed values for form widgets using the `<datalist>` element with child `<option>` elements to specify the values to display. The `<datalist>` needs to be given an `id`. The data list is then bound to an `<input>` element (e.g. a `text` or `email` input type) using the `list` attribute, the value of which is the `id` of the data list to bind. Once a data list is affiliated with a form widget, its options are used to auto-complete text entered by the user; typically, this is presented to the user as a drop-down box listing possible matches for what they've typed into the input. #### Basic example Let's look at an example. ```html <label for="myFruit">What's your favorite fruit?</label> <input type="text" name="myFruit" id="myFruit" list="mySuggestion" /> <datalist id="mySuggestion"> <option>Apple</option> <option>Banana</option> <option>Blackberry</option> <option>Blueberry</option> <option>Lemon</option> <option>Lychee</option> <option>Peach</option> <option>Pear</option> </datalist> ``` #### Datalist support and fallbacks Almost all browsers support datalist, but if you are still supporting older browsers such as IE versions below 10, there is a trick to provide a fallback: ```html <label for="myFruit">What is your favorite fruit? (With fallback)</label> <input type="text" id="myFruit" name="fruit" list="fruitList" /> <datalist id="fruitList"> <label for="suggestion">or pick a fruit</label> <select id="suggestion" name="altFruit"> <option>Apple</option> <option>Banana</option> <option>Blackberry</option> <option>Blueberry</option> <option>Lemon</option> <option>Lychee</option> <option>Peach</option> <option>Pear</option> </select> </datalist> ``` Browsers that support the `<datalist>` element will ignore all the elements that are not `<option>` elements, with the datalist working as expected. Old browsers that don't support the `<datalist>` element will display the label and the select box. The following screenshot shows the datalist fallback as rendered in Safari 6: ![Screenshot of the datalist element fallback with Safari on Mac OS](/en-US/docs/Learn/Forms/Other_form_controls/datalist-safari.png) If you use this fallback, ensure the data for both the `<input>` and the `<select>` are collected server-side. #### Less obvious datalist uses According to the HTML specification, the `list` attribute and the `<datalist>` element can be used with any kind of widget requiring a user input. This leads to some uses of it that might seem a little non-obvious. For example, in browsers that support ``<datalist>`` on `range` input types, a small tick mark will be displayed above the range for each datalist ``<option>`` value. You can see an implementation example of this on the `<input type="range">` reference page. And browsers that support `<datalist>`s and `<input type="color">` should display a customized palette of colors as the default, while still making the full color palette available. In this case, different browsers behave differently from case to case, so consider such uses as progressive enhancement, and ensure they degrade gracefully. Other form features ------------------- There are a few other form features that are not as obvious as the ones we have already mentioned, but still useful in some situations, so we thought it would be worth giving them a brief mention. **Note:** You can find the examples from this section on GitHub as other-examples.html (see it live also). ### Meters and progress bars Meters and progress bars are visual representations of numeric values. Support for `<progress>` and `<meter>` is available in all modern browsers. #### Meter A meter bar represents a fixed value in a range delimited by `max` and `min` values. This value is visually rendered as a bar, and to know how this bar looks, we compare the value to some other set values: * The `low` and `high` values divide the range into the following three parts: + The lower part of the range is between the `min` and `low` values, inclusive. + The medium part of the range is between the `low` and `high` values, exclusive. + The higher part of the range is between the `high` and `max` values, inclusive. * The `optimum` value defines the optimum value for the `<meter>` element. In conjunction with the `low` and `high` value, it defines which part of the range is preferred: + If the `optimum` value is in the lower part of the range, the lower range is considered to be the preferred part, the medium range is considered to be the average part, and the higher range is considered to be the worst part. + If the `optimum` value is in the medium part of the range, the lower range is considered to be an average part, the medium range is considered to be the preferred part, and the higher range is considered to be average as well. + If the `optimum` value is in the higher part of the range, the lower range is considered to be the worst part, the medium range is considered to be the average part and the higher range is considered to be the preferred part. All browsers that implement the `<meter>` element use those values to change the color of the meter bar: * If the current value is in the preferred part of the range, the bar is green. * If the current value is in the average part of the range, the bar is yellow. * If the current value is in the worst part of the range, the bar is red. Such a bar is created by using the `<meter>` element. This is for implementing any kind of meter; for example, a bar showing the total space used on a disk, which turns red when it starts to get full. ```html <meter min="0" max="100" value="75" low="33" high="66" optimum="0">75</meter> ``` The content inside the `<meter>` element is a fallback for browsers that don't support the element and for assistive technologies to vocalize it. #### Progress A progress bar represents a value that changes over time up to a maximum value specified by the `max` attribute. Such a bar is created using a `<progress>` element. ```html <progress max="100" value="75">75/100</progress> ``` This is for implementing anything requiring progress reporting, such as the percentage of total files downloaded, or the number of questions filled in on a questionnaire. The content inside the `<progress>` element is a fallback for browsers that don't support the element and for screen readers to vocalize it. Test your skills! ----------------- You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Other controls. Summary ------- As you'll have seen in the last few articles, there are many types of form control. You don't need to remember all of these details at once, and can return to these articles as often as you like to check up on details. Now that you have a grasp of the HTML behind the different available form controls, we'll take a look at Styling them. * Previous * Overview: Forms * Next ### Advanced Topics * How to build custom form controls * Sending forms through JavaScript * Property compatibility table for form widgets
Test your skills: Basic controls - Learn web development
Test your skills: Basic controls ================================ The aim of this skill test is to assess whether you've understood our Basic native form controls article. **Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch. If you get stuck, you can reach out to us in one of our communication channels. Basic controls 1 ---------------- This task starts you off nice and gently by asking you to create two `<input>` elements, for a user's ID and password, along with a submit button. 1. Create appropriate inputs for user ID and password. 2. You should also associate them with their text labels semantically. 3. Create a submit button inside the remaining list item, with button text of "Log in". Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Basic controls 2 ---------------- The next task requires you to create working sets of checkboxes and radio buttons, from the provided text labels. 1. Turn the first `<fieldset>`'s contents into a set of radio buttons — you should only be able to select one pony character at once. 2. Make it so that the first radio button is selected upon page load. 3. Turn the second `<fieldset>`'s content into a set of checkboxes. 4. Add a couple more hotdog choices of your own. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Basic controls 3 ---------------- The final task in this set requires you to create a file picker. 1. Create a basic file picker. 2. Allow the user to pick multiple files at once. 3. Allow the file picker to accept JPG and PNG images only. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor.
Test your skills: Form structure - Learn web development
Test your skills: Form structure ================================ The aim of this skill test is to assess whether you've understood our How to structure a web form article. **Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch. If you get stuck, you can reach out to us in one of our communication channels. Form structure 1 ---------------- In this task we want you to structure the provided form features: 1. Separate out the first two and second two form fields into two distinct containers, each with a descriptive legend (use "Personal details" for the first two, and "Comment information" for the second two). 2. Mark up each text label with an appropriate element so that it is semantically associated with its respective form field. 3. Add a suitable set of structural elements around the label/field pairs to separate them out. Download the starting point for this task to work in your own editor or in an online editor.
Sending form data - Learn web development
Sending form data ================= * Previous * Overview: Forms Once the form data has been validated on the client-side, it is okay to submit the form. And, since we covered validation in the previous article, we're ready to submit! This article looks at what happens when a user submits a form — where does the data go, and how do we handle it when it gets there? We also look at some of the security concerns associated with sending form data. | | | | --- | --- | | Prerequisites: | An understanding of HTML, and basic knowledge of HTTP and server-side programming. | | Objective: | To understand what happens when form data is submitted, including getting a basic idea of how data is processed on the server. | First, we'll discuss what happens to the data when a form is submitted. Client/server architecture -------------------------- At its most basic, the web uses a client/server architecture that can be summarized as follows: a client (usually a web browser) sends a request to a server (most of the time a web server like Apache, Nginx, IIS, Tomcat, etc.), using the HTTP protocol. The server answers the request using the same protocol. ![A basic schema of the Web client/server architecture](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data/client-server.png) An HTML form on a web page is nothing more than a convenient user-friendly way to configure an HTTP request to send data to a server. This enables the user to provide information to be delivered in the HTTP request. **Note:** To get a better idea of how client-server architectures work, read our Server-side website programming first steps module. On the client side: defining how to send the data ------------------------------------------------- The `<form>` element defines how the data will be sent. All of its attributes are designed to let you configure the request to be sent when a user hits a submit button. The two most important attributes are `action` and `method`. ### The action attribute The `action` attribute defines where the data gets sent. Its value must be a valid relative or absolute URL. If this attribute isn't provided, the data will be sent to the URL of the page containing the form — the current page. In this example, the data is sent to an absolute URL — `https://example.com`: ```html <form action="https://example.com">…</form> ``` Here, we use a relative URL — the data is sent to a different URL on the same origin: ```html <form action="/somewhere\_else">…</form> ``` When specified with no attributes, as below, the `<form>` data is sent to the same page that the form is present on: ```html <form>…</form> ``` **Note:** It's possible to specify a URL that uses the HTTPS (secure HTTP) protocol. When you do this, the data is encrypted along with the rest of the request, even if the form itself is hosted on an insecure page accessed using HTTP. On the other hand, if the form is hosted on a secure page but you specify an insecure HTTP URL with the `action` attribute, all browsers display a security warning to the user each time they try to send data because the data will not be encrypted. The names and values of the non-file form controls are sent to the server as `name=value` pairs joined with ampersands. The `action` value should be a file on the server that can handle the incoming data, including ensuring server-side validation. The server then responds, generally handling the data and loading the URL defined by the `action` attribute, causing a new page load (or a refresh of the existing page, if the `action` points to the same page). How the data is sent depends on the `method` attribute. ### The method attribute The `method` attribute defines how data is sent. The HTTP protocol provides several ways to perform a request; HTML form data can be transmitted via a number of different methods, the most common being the `GET` method and the `POST` method To understand the difference between those two methods, let's step back and examine how HTTP works. Each time you want to reach a resource on the Web, the browser sends a request to a URL. An HTTP request consists of two parts: a header that contains a set of global metadata about the browser's capabilities, and a body that can contain information necessary for the server to process the specific request. #### The GET method The `GET` method is the method used by the browser to ask the server to send back a given resource: "Hey server, I want to get this resource." In this case, the browser sends an empty body. Because the body is empty, if a form is sent using this method the data sent to the server is appended to the URL. Consider the following form: ```html <form action="http://www.foo.com" method="GET"> <div> <label for="say">What greeting do you want to say?</label> <input name="say" id="say" value="Hi" /> </div> <div> <label for="to">Who do you want to say it to?</label> <input name="to" id="to" value="Mom" /> </div> <div> <button>Send my greetings</button> </div> </form> ``` Since the `GET` method has been used, you'll see the URL `www.foo.com/?say=Hi&to=Mom` appear in the browser address bar when you submit the form. ![The changed url with query parameters after submitting the form with GET method with a "server not found" browser error page](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data/url-parameters.png) The data is appended to the URL as a series of name/value pairs. After the URL web address has ended, we include a question mark (`?`) followed by the name/value pairs, each one separated by an ampersand (`&`). In this case, we are passing two pieces of data to the server: * `say`, which has a value of `Hi` * `to`, which has a value of `Mom` The HTTP request looks like this: ```http GET /?say=Hi&to=Mom HTTP/2.0 Host: foo.com ``` **Note:** You can find this example on GitHub — see get-method.html (see it live also). #### The POST method The `POST` method is a little different. It's the method the browser uses to talk to the server when asking for a response that takes into account the data provided in the body of the HTTP request: "Hey server, take a look at this data and send me back an appropriate result." If a form is sent using this method, the data is appended to the body of the HTTP request. Let's look at an example — this is the same form we looked at in the `GET` section above, but with the `method` attribute set to `POST`. ```html <form action="http://www.foo.com" method="POST"> <div> <label for="say">What greeting do you want to say?</label> <input name="say" id="say" value="Hi" /> </div> <div> <label for="to">Who do you want to say it to?</label> <input name="to" id="to" value="Mom" /> </div> <div> <button>Send my greetings</button> </div> </form> ``` When the form is submitted using the `POST` method, you get no data appended to the URL, and the HTTP request looks like so, with the data included in the request body instead: ```http POST / HTTP/2.0 Host: foo.com Content-Type: application/x-www-form-urlencoded Content-Length: 13 say=Hi&to=Mom ``` The `Content-Length` header indicates the size of the body, and the `Content-Type` header indicates the type of resource sent to the server. We'll discuss these headers later on. **Note:** You can find this example on GitHub — see post-method.html (see it live also). ### Viewing HTTP requests HTTP requests are never displayed to the user (if you want to see them, you need to use tools such as the Firefox Network Monitor or the Chrome Developer Tools). As an example, your form data will be shown as follows in the Chrome Network tab. After submitting the form: 1. Open the developer tools. 2. Select "Network" 3. Select "All" 4. Select "foo.com" in the "Name" tab 5. Select "Headers" You can then get the form data, as shown in the image below. ![HTTP requests and response data in network monitoring tab in browser's developer tools](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data/network-monitor.png) The only thing displayed to the user is the URL called. As we mentioned above, with a `GET` request the user will see the data in their URL bar, but with a `POST` request they won't. This can be very important for two reasons: 1. If you need to send a password (or any other sensitive piece of data), never use the `GET` method or you risk displaying it in the URL bar, which would be very insecure. 2. If you need to send a large amount of data, the `POST` method is preferred because some browsers limit the sizes of URLs. In addition, many servers limit the length of URLs they accept. On the server side: retrieving the data --------------------------------------- Whichever HTTP method you choose, the server receives a string that will be parsed in order to get the data as a list of key/value pairs. The way you access this list depends on the development platform you use and on any specific frameworks you may be using with it. ### Example: Raw PHP PHP offers some global objects to access the data. Assuming you've used the `POST` method, the following example just takes the data and displays it to the user. Of course, what you do with the data is up to you. You might display it, store it in a database, send it by email, or process it in some other way. ```php <?php // The global $\_POST variable allows you to access the data sent with the POST method by name // To access the data sent with the GET method, you can use $\_GET $say = htmlspecialchars($\_POST['say']); $to = htmlspecialchars($\_POST['to']); echo $say, ' ', $to; ?> ``` This example displays a page with the data we sent. You can see this in action in our example php-example.html file — which contains the same example form as we saw before, with a `method` of `POST` and an `action` of `php-example.php`. When it is submitted, it sends the form data to php-example.php, which contains the PHP code seen in the above block. When this code is executed, the output in the browser is `Hi Mom`. ![Otherwise blank web page with "hi mom", the data received in response after submitting form data to a php file with POST method](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data/php-result.png) **Note:** This example won't work when you load it into a browser locally — browsers cannot interpret PHP code, so when the form is submitted the browser will just offer to download the PHP file for you. To get it to work, you need to run the example through a PHP server of some kind. Good options for local PHP testing are MAMP (Mac and Windows) and AMPPS (Mac, Windows, Linux). Note also that if you are using MAMP but don't have MAMP Pro installed (or if the MAMP Pro demo time trial has expired), you might have trouble getting it working. To get it working again, we have found that you can load up the MAMP app, then choose the menu options *MAMP* > *Preferences* > *PHP*, and set "Standard Version:" to "7.2.x" (x will differ depending on what version you have installed). ### Example: Python This example shows how you would use Python to do the same thing — display the submitted data on a web page. This uses the Flask framework for rendering the templates, handling the form data submission, etc. (see python-example.py). ```python from flask import Flask, render_template, request app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def form(): return render_template('form.html') @app.route('/hello', methods=['GET', 'POST']) def hello(): return render_template('greeting.html', say=request.form['say'], to=request.form['to']) if __name__ == "\_\_main\_\_": app.run() ``` The two templates referenced in the above code are as follows (these need to be in a subdirectory called `templates` in the same directory as the `python-example.py` file, if you try to run the example yourself): * form.html: The same form as we saw above in The POST method section but with the `action` set to `{{ url_for('hello') }}`. This is a Jinja template, which is basically HTML but can contain calls to the Python code that is running the web server contained in curly braces. `url_for('hello')` is basically saying "redirect to `/hello` when the form is submitted". * greeting.html: This template just contains a line that renders the two bits of data passed to it when it is rendered. This is done via the `hello()` function seen above, which runs when the `/hello` URL is navigated to. **Note:** Again, this code won't work if you just try to load it into a browser directly. Python works a bit differently from PHP — to run this code locally you'll need to install Python/PIP, then install Flask using `pip3 install flask`. At this point, you should be able to run the example using `python3 python-example.py`, then navigate to `localhost:5042` in your browser. ### Other languages and frameworks There are many other server-side technologies you can use for form handling, including Perl, Java, .Net, Ruby, etc. Just pick the one you like best. That said, it's worth noting that it's very uncommon to use these technologies directly because this can be tricky. It's more common to use one of the many high quality frameworks that make handling forms easier, such as: * Python + Django + Flask + web2py (easiest to get started with) + py4web (written by the same develops as web2py, has a more Django-like setup) * Node.js + Express + Next.js (for React apps) + Nuxt (for Vue apps) + Remix * PHP + Laravel + Laminas (formerly Zend Framework) + Symfony * Ruby + Ruby On Rails * Java + Spring Boot It's worth noting that even using these frameworks, working with forms isn't necessarily *easy*. But it's much easier than trying to write all the functionality yourself from scratch, and will save you a lot of time. **Note:** It is beyond the scope of this article to teach you any server-side languages or frameworks. The links above will give you some help, should you wish to learn them. A special case: sending files ----------------------------- Sending files with HTML forms is a special case. Files are binary data — or considered as such — whereas all other data is text data. Because HTTP is a text protocol, there are special requirements for handling binary data. ### The enctype attribute This attribute lets you specify the value of the `Content-Type` HTTP header included in the request generated when the form is submitted. This header is very important because it tells the server what kind of data is being sent. By default, its value is `application/x-www-form-urlencoded`. In human terms, this means: "This is form data that has been encoded into URL parameters." If you want to send files, you need to take three extra steps: * Set the `method` attribute to `POST` because file content can't be put inside URL parameters. * Set the value of `enctype` to `multipart/form-data` because the data will be split into multiple parts, one for each file plus one for the text data included in the form body (if the text is also entered into the form). * Include one or more `<input type="file">` controls to allow your users to select the file(s) that will be uploaded. For example: ```html <form method="post" action="https://www.foo.com" enctype="multipart/form-data"> <div> <label for="file">Choose a file</label> <input type="file" id="file" name="myFile" /> </div> <div> <button>Send the file</button> </div> </form> ``` **Note:** Servers can be configured with a size limit for files and HTTP requests in order to prevent abuse. Security issues --------------- Each time you send data to a server, you need to consider security. HTML forms are by far the most common server attack vectors (places where attacks can occur). The problems never come from the HTML forms themselves — they come from how the server handles data. The Website security article of our server-side learning topic discusses several common attacks and potential defenses against them in detail. You should go and check that article out, to get an idea of what's possible. ### Be paranoid: Never trust your users So, how do you fight these threats? This is a topic far beyond this guide, but there are a few rules to keep in mind. The most important rule is: never ever trust your users, including yourself; even a trusted user could have been hijacked. All data that comes to your server must be checked and sanitized. Always. No exception. * **Escape potentially dangerous characters**. The specific characters you should be cautious with vary depending on the context in which the data is used and the server platform you employ, but all server-side languages have functions for this. Things to watch out for are character sequences that look like executable code (such as JavaScript or SQL commands). * **Limit the incoming amount of data to allow only what's necessary**. * **Sandbox uploaded files**. Store them on a different server and allow access to the file only through a different subdomain or even better through a completely different domain. You should be able to avoid many/most problems if you follow these three rules, but it's always a good idea to get a security review performed by a competent third party. Don't assume that you've seen all the possible problems. Summary ------- As we'd alluded to above, sending form data is easy, but securing an application can be tricky. Just remember that a front-end developer is not the one who should define the security model of the data. It's possible to perform client-side form validation, but the server can't trust this validation because it has no way to truly know what has really happened on the client-side. If you've worked your way through these tutorials in order, you now know how to markup and style a form, do client-side validation, and have some idea about submitting a form. See also -------- If you want to learn more about securing a web application, you can dig into these resources: * Server-side website programming first steps * The Open Web Application Security Project (OWASP) * Web Security by Mozilla * Previous * Overview: Forms ### Advanced Topics * How to build custom form controls * Sending forms through JavaScript * Property compatibility table for form widgets
The HTML5 input types - Learn web development
The HTML5 input types ===================== * Previous * Overview: Forms * Next In the previous article we looked at the `<input>` element, covering the original values of the `type` attribute available since the early days of HTML. Now we'll look at the functionality of newer form controls in detail, including some new input types, which were added in HTML5 to allow the collection of specific types of data. | | | | --- | --- | | Prerequisites: | A basic understanding of HTML. | | Objective: | To understand the newer input type values available to create native form controls, and how to implement them using HTML. | **Note:** Most of the features discussed in this article have wide support across browsers. We'll note any exceptions. If you want more detail on browser support, you should consult our HTML forms element reference, and in particular our extensive <input> types reference. Because HTML form control appearance may be quite different from a designer's specifications, web developers sometimes build their own custom form controls. We cover this in an advanced tutorial: How to build custom form widgets. Email address field ------------------- This type of field is set using the value `email` for the `type` attribute: ```html <input type="email" id="email" name="email" /> ``` When this `type` is used, the user is required to type a valid email address into the field. Any other content causes the browser to display an error when the form is submitted. You can see this in action in the below screenshot. ![An invalid email input showing the message "Please enter an email address."](/en-US/docs/Learn/Forms/HTML5_input_types/email_address_invalid.png) You can also use the `multiple` attribute in combination with the `email` input type to allow several email addresses to be entered in the same input (separated by commas): ```html <input type="email" id="email" name="email" multiple /> ``` On some devices — notably, touch devices with dynamic keyboards like smartphones — a different virtual keypad might be presented that is more suitable for entering email addresses, including the `@` key. See the Firefox for Android keyboard screenshot below for an example: ![Firefox for Android email keyboard, with the at sign displayed by default.](/en-US/docs/Learn/Forms/HTML5_input_types/fx-android-email-type-keyboard.jpg) **Note:** You can find examples of the basic text input types at basic input examples (see the source code also). This is another good reason for using these newer input types, improving the user experience for users of these devices. ### Client-side validation As you can see above, `email` — along with other newer `input` types — provides built-in *client-side* error validation, performed by the browser before the data gets sent to the server. It *is* a helpful aid to guide users to fill out a form accurately, and it can save time: it is useful to know that your data is not correct immediately, rather than having to wait for a round trip to the server. But it *should not be considered* an exhaustive security measure! Your apps should always perform security checks on any form-submitted data on the *server-side* as well as the client-side, because client-side validation is too easy to turn off, so malicious users can still easily send bad data through to your server. Read Website security for an idea of what *could* happen; implementing server-side validation is somewhat beyond the scope of this module, but you should bear it in mind. Note that `a@b` is a valid email address according to the default provided constraints. This is because the `email` input type allows intranet email addresses by default. To implement different validation behavior, you can use the `pattern` attribute, and you can also customize the error messages; we'll talk about how to use these features in the Client-side form validation article later on. **Note:** If the data entered is not an email address, the `:invalid` pseudo-class will match, and the `validityState.typeMismatch` property will return `true`. Search field ------------ Search fields are intended to be used to create search boxes on pages and apps. This type of field is set by using the value `search` for the `type` attribute: ```html <input type="search" id="search" name="search" /> ``` The main difference between a `text` field and a `search` field is how the browser styles its appearance. Often, `search` fields are rendered with rounded corners; they also sometimes display an "Ⓧ", which clears the field of any value when clicked. Additionally, on devices with dynamic keyboards, the keyboard's enter key may read "**search**", or display a magnifying glass icon. The below screenshots show a non-empty search field in Firefox 71, Safari 13, and Chrome 79 on macOS, and Edge 18 and Chrome 79 on Windows 10. Note that the clear icon only appears if the field has a value, and, apart from Safari, it is only displayed when the field is focused. ![Screenshots of search fields on several platforms.](/en-US/docs/Learn/Forms/HTML5_input_types/search_focus.png) Another worth-noting feature is that the values of a `search` field can be automatically saved and re-used to offer auto-completion across multiple pages of the same website; this tends to happen automatically in most modern browsers. Phone number field ------------------ A special field for filling in phone numbers can be created using `tel` as the value of the `type` attribute: ```html <input type="tel" id="tel" name="tel" /> ``` When accessed via a touch device with a dynamic keyboard, most devices will display a numeric keypad when `type="tel"` is encountered, meaning this type is useful whenever a numeric keypad is useful, and doesn't just have to be used for telephone numbers. The following Firefox for Android keyboard screenshot provides an example: ![Firefox for Android email keyboard, with ampersand displayed by default.](/en-US/docs/Learn/Forms/HTML5_input_types/fx-android-tel-type-keyboard.jpg) Due to the wide variety of phone number formats around the world, this type of field does not enforce any constraints on the value entered by a user (this means it may include letters, etc.). As we mentioned earlier, the `pattern` attribute can be used to enforce constraints, which you'll learn about in Client-side form validation. URL field --------- A special type of field for entering URLs can be created using the value `url` for the `type` attribute: ```html <input type="url" id="url" name="url" /> ``` It adds special validation constraints to the field. The browser will report an error if no protocol (such as `http:`) is entered, or if the URL is otherwise malformed. On devices with dynamic keyboards, the default keyboard will often display some or all of the colon, period, and forward slash as default keys. See below for an example (taken on Firefox for Android): ![Firefox for Android email keyboard, with ampersand displayed by default.](/en-US/docs/Learn/Forms/HTML5_input_types/fx-android-url-type-keyboard.jpg) **Note:** Just because the URL is well-formed doesn't necessarily mean that it refers to a location that actually exists! Numeric field ------------- Controls for entering numbers can be created with an `<input>` `type` of `number`. This control looks like a text field but allows only floating-point numbers, and usually provides buttons in the form of a spinner to increase and decrease the value of the control. On devices with dynamic keyboards, the numeric keyboard is generally displayed. The following screenshot (from Firefox for Android) provides an example: ![Firefox for Android email keyboard, with ampersand displayed by default.](/en-US/docs/Learn/Forms/HTML5_input_types/fx-android-number-type-keyboard.jpg) With the `number` input type, you can constrain the minimum and maximum values allowed by setting the `min` and `max` attributes. You can also use the `step` attribute to set the increment increase and decrease caused by pressing the spinner buttons. By default, the number input type only validates if the number is an integer. To allow float numbers, specify `step="any"`. If omitted, the `step` value defaults to `1`, meaning only whole numbers are valid. Let's look at some examples. The first one below creates a number control whose value is restricted to any value between `1` and `10`, and whose increase and decrease buttons change its value by `2`. ```html <input type="number" name="age" id="age" min="1" max="10" step="2" /> ``` The second one creates a number control whose value is restricted to any value between `0` and `1` inclusive, and whose increase and decrease buttons change its value by `0.01`. ```html <input type="number" name="change" id="pennies" min="0" max="1" step="0.01" /> ``` The `number` input type makes sense when the range of valid values is limited, for example a person's age or height. If the range is too large for incremental increases to make sense (such as USA ZIP codes, which range from `00001` to `99999`), the `tel` type might be a better option; it provides the numeric keypad while forgoing the number's spinner UI feature. Slider controls --------------- Another way to pick a number is to use a **slider**. You see these quite often on sites like house-buying sites where you want to set a maximum property price to filter by. Let's look at a live example to illustrate this: Usage-wise, sliders are less accurate than text fields. Therefore, they are used to pick a number whose *precise* value is not necessarily important. A slider is created using the `<input>` with its `type` attribute set to the value `range`. The slider-thumb can be moved via mouse or touch, or with the arrows of the keypad. It's important to properly configure your slider. To that end, it's highly recommended that you set the `min`, `max`, and `step` attributes which set the minimum, maximum, and increment values, respectively. Let's look at the code behind the above example, so you can see how it's done. First of all, the basic HTML: ```html <label for="price">Choose a maximum house price: </label> <input type="range" name="price" id="price" min="50000" max="500000" step="100" value="250000" /> <output class="price-output" for="price"></output> ``` This example creates a slider whose value may range between `50000` and `500000`, which increments/decrements by 100 at a time. We've given it a default value of `250000`, using the `value` attribute. One problem with sliders is that they don't offer any kind of visual feedback as to what the current value is. This is why we've included an `<output>` element to contain the current value. You could display an input value or the output of a calculation inside any element, but `<output>` is special — like `<label>` — and it can take a `for` attribute that allows you to associate it with the element or elements that the output value came from. To actually display the current value, and update it as it changed, you must use JavaScript, but this is relatively easy to do: ```js const price = document.querySelector("#price"); const output = document.querySelector(".price-output"); output.textContent = price.value; price.addEventListener("input", () => { output.textContent = price.value; }); ``` Here we store references to the `range` input and the `output` in two variables. Then we immediately set the `output`'s `textContent` to the current `value` of the input. Finally, an event listener is set to ensure that whenever the range slider is moved, the `output`'s `textContent` is updated to the new value. **Note:** There is a nice tutorial covering this subject on CSS Tricks: The Output Element. Date and time pickers --------------------- Gathering date and time values has traditionally been a nightmare for web developers. For a good user experience, it is important to provide a calendar selection UI, enabling users to select dates without necessitating context switching to a native calendar application or potentially entering them in differing formats that are hard to parse. The last minute of the previous millennium can be expressed in the following different ways, for example: 1999/12/31, 23:59 or 12/31/99T11:59PM. HTML date controls are available to handle this specific kind of data, providing calendar widgets and making the data uniform. A date and time control is created using the `<input>` element and an appropriate value for the `type` attribute, depending on whether you wish to collect dates, times, or both. Here's a live example that falls back to `<select>` elements in non-supporting browsers: Let's look at the different available types in brief. Note that the usage of these types is quite complex, especially considering browser support (see below); to find out the full details, follow the links below to the reference pages for each type, including detailed examples. ### `datetime-local` `<input type="datetime-local">` creates a widget to display and pick a date with time with no specific time zone information. ```html <input type="datetime-local" name="datetime" id="datetime" /> ``` ### `month` `<input type="month">` creates a widget to display and pick a month with a year. ```html <input type="month" name="month" id="month" /> ``` ### `time` `<input type="time">` creates a widget to display and pick a time value. While time may *display* in 12-hour format, the *value returned* is in 24-hour format. ```html <input type="time" name="time" id="time" /> ``` ### `week` `<input type="week">` creates a widget to display and pick a week number and its year. Weeks start on Monday and run to Sunday. Additionally, the first week 1 of each year contains the first Thursday of that year — which may not include the first day of the year, or may include the last few days of the previous year. ```html <input type="week" name="week" id="week" /> ``` ### Constraining date/time values All date and time controls can be constrained using the `min` and `max` attributes, with further constraining possible via the `step` attribute (whose value varies according to input type). ```html <label for="myDate">When are you available this summer?</label> <input type="date" name="myDate" min="2013-06-01" max="2013-08-31" step="7" id="myDate" /> ``` Color picker control -------------------- Colors are always a bit difficult to handle. There are many ways to express them: RGB values (decimal or hexadecimal), HSL values, keywords, and so on. A `color` control can be created using the `<input>` element with its `type` attribute set to the value `color`: ```html <input type="color" name="color" id="color" /> ``` Clicking a color control generally displays the operating system's default color-picking functionality for you to choose. Here is a live example for you to try out: The value returned is always a lowercase 6-value hexadecimal color. Test your skills! ----------------- You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: HTML5 controls. Summary ------- That brings us to the end of our tour of the HTML5 form input types. There are a few other control types that cannot be easily grouped together due to their very specific behaviors, but which are still essential to know about. We cover those in the next article. * Previous * Overview: Forms * Next ### Advanced Topics * How to build custom form controls * Sending forms through JavaScript * Property compatibility table for form widgets
Test your skills: Other controls - Learn web development
Test your skills: Other controls ================================ The aim of this skill test is to assess whether you've understood our Other form controls article. **Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch. If you get stuck, you can reach out to us in one of our communication channels. Other controls 1 ---------------- In our first "other controls" assessment, we'll get you to create a multi-line text input. 1. Create a basic multi-line text input. 2. Associate it semantically with the provided "Comment" label. 3. Give the input 35 columns, and 10 rows of space in which to add comments. 4. Give the comments a maximum length of 100 characters. To create the input, update the HTML code in the editor below: Download the starting point for this task to work in your own editor or in an online editor. Other controls 2 ---------------- Now it's time to have a go at implementing a drop-down select menu, to allow a user to pick their favorite food from the choices provided. 1. Create your basic select box structure. 2. Associate it semantically with the provided "food" label. 3. Inside the list, split the choices up into 2 subgroups — "mains" and "snacks". To create the menu, update the HTML code in the editor below: Download the starting point for this task to work in your own editor or in an online editor. Other controls 3 ---------------- In our final task of this set, we start with much the same list of food choices. However, this time we want to do things differently: 1. Create a basic text input that is semantically associated with the provided label. 2. Put the food choices into a list that can be associated with a form input. 3. Associate the list with your text input, so that when you type characters, any of the list options that match the character sequence are given in a dropdown list as autocomplete suggestions. To create the input, update the HTML code in the editor below: Download the starting point for this task to work in your own editor or in an online editor.
User input methods and controls - Learn web development
User input methods and controls =============================== Web forms require user input. When designing web forms, or really any web content, it's important to consider how users interact with their devices and browsers. Web user input goes beyond simple mouse and keyboard: think of touchscreens for example. In this article, we take a look at the different ways users interact with forms and other web content and provide recommendations for managing user input, real-world examples, and links to further information. As you develop more complex and interactive forms or other UI features, there are many HTML elements and JavaScript APIs you may want to investigate. For example, you may want to create custom form controls that require non-semantic elements to be content editable. You might want to support touch events, determine or control the screen's orientation, make a form take up the full screen, or enable drag and drop features. This guide introduces all these features, and directs you to more information on each topic. To provide a good experience to the greatest number of users, you need to support multiple input methods, including mouse, keyboard, finger touch, and so on. Available input mechanisms depend on the capabilities of the device running the application. You should always be mindful of keyboard accessibility — many web users only use the keyboard to navigate websites and apps, and locking them out of your functionality is a bad idea. Topics covered -------------- * To support touch screen displays, touch events interpret finger activity on touch-based user interfaces from mobile devices, to refrigerator panels, to museum kiosk displays. * The Fullscreen API allows you to display your content in fullscreen mode, which is needed if your form is being served on a refrigerator or museum kiosk. * When you need to create a custom form control, like a rich-text editor, the `contentEditable` attribute enables creating editable controls from normally non-editable HTML elements. * The Drag and Drop API allows users to drag elements around a page and drop them in different locations. This can help improve the user experience when it comes to selecting files for upload or reordering content modules within a page. * When screen orientation matters for your layout, you can use CSS media queries to style your forms based on the browser orientation, or even use the Screen Orientation API to read the screen orientation state and perform other actions. The following sections provide a set of recommendations and best practices for enabling the widest possible set of users to use your websites and applications. Supporting common input mechanisms ---------------------------------- ### Keyboard Most users will use a keyboard to enter data into your form controls. Some will also use the keyboard to navigate to those form controls. To be accessible, and for better user experience, it's important to properly label all form controls. When each form control has a correctly associated `<label>`, your form will be fully accessible to all, most notably anyone navigating your form with a keyboard, a screen reader, and possibly no screen at all. If you want to add additional keyboard support, such as validating a form control when a specific key is hit, you can use event listeners to capture and react to keyboard events. For example, if you want to add controls when any key gets pressed, you need to add an event listener on the window object: ```js window.addEventListener("keydown", handleKeyDown, true); window.addEventListener("keyup", handleKeyUp, true); ``` `handleKeyDown` and `handleKeyUp` are functions defining the control logic to be executed when the `keydown` and `keyup` events are fired. **Note:** Have a look at the Events reference and `KeyboardEvent` guide to find out more about keyboard events. ### Mouse You can also capture mouse and other pointer events. The events occurring when the user interacts with a pointing device such as a mouse are represented by the `MouseEvent` DOM Interface. Common mouse events include `click`, `dblclick`, `mouseup`, and `mousedown`. The list of all events using the Mouse Event Interface is provided in the Events reference. When the input device is a mouse, you can also control user input through the Pointer Lock API and implement Drag & Drop (see below). You can also use CSS to test for pointer device support. ### Finger touch To provide additional support for touchscreen devices, it's a good practice to take into consideration the different capabilities in terms of screen resolution and user input. Touch events can help you implement interactive elements and common interaction gestures on touchscreen devices. If you want to use touch events, you need to add event listeners and specify handler functions, which will be called when the event gets fired: ```js element.addEventListener("touchstart", handleStart, false); element.addEventListener("touchcancel", handleCancel, false); element.addEventListener("touchend", handleEnd, false); element.addEventListener("touchmove", handleMove, false); ``` where `element` is the DOM element you want to register the touch events on. **Note:** For further information about what you can do with touch events, please read our touch events guide. ### Pointer Events Mice aren't the only pointing devices. Your user's devices may incorporate multiple forms of input, like mouse, finger touch, and pen input. Each of these pointers has a different size. The Pointer Events API may come in handy if you need to manage events across devices by normalizing the handling of each one. A pointer can be any point of contact on the screen made by a mouse cursor, pen, touch (including multi-touch), or other pointing input device. The events for handling generic pointer input look a lot like those for mouse: `pointerdown`, `pointermove`, `pointerup`, `pointerover`, `pointerout`, etc. The `PointerEvent` interface provides all the details you may want to capture about the pointer device, including its size, pressure, and angle. Implement controls ------------------ ### Screen Orientation If you need slightly different layouts depending on whether the user is in portrait or landscape mode, you can use CSS media queries to define CSS for different layouts or form control widths based on the size or orientation of the screen when styling web forms. When screen orientation matters for your form, you can read the screen orientation state, be informed when this state changes, and able to lock the screen orientation to a specific state (usually portrait or landscape) through the Screen Orientation API. * Orientation data can be retrieved through `screenOrientation.type` or with CSS through the `orientation` media feature. * When the screen orientation changes, the `change` event is fired on the screen object. * Locking the screen orientation is made possible by invoking the `ScreenOrientation.lock()` method. * The `ScreenOrientation.unlock()` method removes all the previous screen locks that have been set. **Note:** More information about the Screen Orientation API can be found in Managing screen orientation. ### Fullscreen If you need to present your form in fullscreen mode, such as when your form is displayed on a museum kiosk, toll booth, or really any publically displayed user interface, it is possible to do so by calling `Element.requestFullscreen()` on that element: ```js const elem = document.getElementById("myForm"); if (elem.requestFullscreen) { elem.requestFullscreen(); } ``` **Note:** To find out more about adding fullscreen functionality to your application, read our documentation about using fullscreen mode. ### Drag & Drop A common user interaction is the physical dragging of elements to be dropped elsewhere on the screen. Drag and drop can help improve the user experience when it comes to selecting files for upload or reordering content modules within a page. There's an API for that! The Drag & Drop API enables users to click and hold the mouse button down over an element, drag it to another location, and release the mouse button to drop the element there. Here is an example that allows a section of content to be dragged. ```html <div draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'This text may be dragged')"> This text <strong>may</strong> be dragged. </div> ``` in which we: * Set the `draggable` attribute to `true` on the element that you wish to make draggable. * Add a listener for the `dragstart` event and set the drag data within this listener. **Note:** You can find more information in the MDN Drag & Drop documentation. ### contentEditable Generally, you should use a `<textarea>` or an appropriate `<input>` type within a `<form>` to collect data from users, along with a descriptive `<label>`. But these elements may not meet your needs. For example, rich text editors capture italic, bold, and normal text, but no native form control captures rich text. This use case requires you to create a custom control that is stylable *and* editable. There's an attribute for that! Any DOM element can be made directly editable using the `contenteditable` attribute. ``` div { width: 300px; height: 130px; border: 1px solid gray; } ``` ```html <div contenteditable="true">This text can be edited by the user.</div> ``` The `contenteditable` attribute automatically adds the element to the document's default tabbing order, meaning the `tabindex` attribute does not need to be added. However, when using non-semantic elements for data entry when creating your own form controls, you will need to add JavaScript and ARIA to retrofit the element with form control functionality for everything else. To provide a good user experience, any custom form control you create must be accessible and function like native form controls: * The element's `role`, label, and description need to be added with ARIA. * All user input methods needs to be supported, including keyboard, mouse, touch, and pointer events, all described above. * JavaScript is required to handle functionality such as validation, submission, and saving of user-updated content. **Note:** Examples and other resources can be found in the Content Editable guide. Tutorials --------- * Touch events Guide * Managing screen orientation * Using fullscreen mode * Drag Operations Guide * Form validation * Sending forms through JavaScript Reference --------- * `MouseEvent` interface * `KeyboardEvent` interface * Touch events API * Pointer Lock API * Screen Orientation API * Fullscreen API * Drag & Drop API * HTML `contenteditable` attribute
Client-side form validation - Learn web development
Client-side form validation =========================== * Previous * Overview: Forms * Next Before submitting data to the server, it is important to ensure all required form controls are filled out, in the correct format. This is called **client-side form validation**, and helps ensure data submitted matches the requirements set forth in the various form controls. This article leads you through basic concepts and examples of client-side form validation. | | | | --- | --- | | Prerequisites: | Computer literacy, a reasonable understanding of HTML, CSS, and JavaScript. | | Objective: | To understand what client-side form validation is, why it's important, and how to apply various techniques to implement it. | Client-side validation is an initial check and an important feature of good user experience; by catching invalid data on the client-side, the user can fix it straight away. If it gets to the server and is then rejected, a noticeable delay is caused by a round trip to the server and then back to the client-side to tell the user to fix their data. However, client-side validation *should not be considered* an exhaustive security measure! Your apps should always perform security checks on any form-submitted data on the *server-side* **as well** as the client-side, because client-side validation is too easy to bypass, so malicious users can still easily send bad data through to your server. Read Website security for an idea of what *could* happen; implementing server-side validation is somewhat beyond the scope of this module, but you should bear it in mind. What is form validation? ------------------------ Go to any popular site with a registration form, and you will notice that they provide feedback when you don't enter your data in the format they are expecting. You'll get messages such as: * "This field is required" (You can't leave this field blank). * "Please enter your phone number in the format xxx-xxxx" (A specific data format is required for it to be considered valid). * "Please enter a valid email address" (the data you entered is not in the right format). * "Your password needs to be between 8 and 30 characters long and contain one uppercase letter, one symbol, and a number." (A very specific data format is required for your data). This is called **form validation**. When you enter data, the browser and/or the web server will check to see that the data is in the correct format and within the constraints set by the application. Validation done in the browser is called **client-side** validation, while validation done on the server is called **server-side** validation. In this chapter we are focusing on client-side validation. If the information is correctly formatted, the application allows the data to be submitted to the server and (usually) saved in a database; if the information isn't correctly formatted, it gives the user an error message explaining what needs to be corrected, and lets them try again. We want to make filling out web forms as easy as possible. So why do we insist on validating our forms? There are three main reasons: * **We want to get the right data, in the right format.** Our applications won't work properly if our users' data is stored in the wrong format, is incorrect, or is omitted altogether. * **We want to protect our users' data**. Forcing our users to enter secure passwords makes it easier to protect their account information. * **We want to protect ourselves**. There are many ways that malicious users can misuse unprotected forms to damage the application. See Website security. **Warning:** Never trust data passed to your server from the client. Even if your form is validating correctly and preventing malformed input on the client-side, a malicious user can still alter the network request. Different types of client-side validation ----------------------------------------- There are two different types of client-side validation that you'll encounter on the web: * **Built-in form validation** uses HTML form validation features, which we've discussed in many places throughout this module. This validation generally doesn't require much JavaScript. Built-in form validation has better performance than JavaScript, but it is not as customizable as JavaScript validation. * **JavaScript** validation is coded using JavaScript. This validation is completely customizable, but you need to create it all (or use a library). Using built-in form validation ------------------------------ One of the most significant features of modern form controls is the ability to validate most user data without relying on JavaScript. This is done by using validation attributes on form elements. We've seen many of these earlier in the course, but to recap: * `required`: Specifies whether a form field needs to be filled in before the form can be submitted. * `minlength` and `maxlength`: Specifies the minimum and maximum length of textual data (strings). * `min` and `max`: Specifies the minimum and maximum values of numerical input types. * `type`: Specifies whether the data needs to be a number, an email address, or some other specific preset type. * `pattern`: Specifies a regular expression that defines a pattern the entered data needs to follow. If the data entered in a form field follows all of the rules specified by the above attributes, it is considered valid. If not, it is considered invalid. When an element is valid, the following things are true: * The element matches the `:valid` CSS pseudo-class, which lets you apply a specific style to valid elements. * If the user tries to send the data, the browser will submit the form, provided there is nothing else stopping it from doing so (e.g., JavaScript). When an element is invalid, the following things are true: * The element matches the `:invalid` CSS pseudo-class, and sometimes other UI pseudo-classes (e.g., `:out-of-range`) depending on the error, which lets you apply a specific style to invalid elements. * If the user tries to send the data, the browser will block the form and display an error message. **Note:** There are several errors that will prevent the form from being submitted, including a `badInput`, `patternMismatch`, `rangeOverflow` or `rangeUnderflow`, `stepMismatch`, `tooLong` or `tooShort`, `typeMismatch`, `valueMissing`, or a `customError`. Built-in form validation examples --------------------------------- In this section, we'll test out some of the attributes that we discussed above. ### Simple start file Let's start with a simple example: an input that allows you to choose whether you prefer a banana or a cherry. This example involves a simple text `<input>` with an associated `<label>` and a submit `<button>`. Find the source code on GitHub at fruit-start.html and a live example below. ```html <form> <label for="choose">Would you prefer a banana or cherry?</label> <input id="choose" name="i-like" /> <button>Submit</button> </form> ``` ```css input:invalid { border: 2px dashed red; } input:valid { border: 2px solid black; } ``` To begin, make a copy of `fruit-start.html` in a new directory on your hard drive. ### The required attribute The simplest HTML validation feature is the `required` attribute. To make an input mandatory, add this attribute to the element. When this attribute is set, the element matches the `:required` UI pseudo-class and the form won't submit, displaying an error message on submission when the input is empty. While empty, the input will also be considered invalid, matching the `:invalid` UI pseudo-class. Add a `required` attribute to your input, as shown below. ```html <form> <label for="choose">Would you prefer a banana or cherry? (required)</label> <input id="choose" name="i-like" required /> <button>Submit</button> </form> ``` Note the CSS that is included in the example file: ```css input:invalid { border: 2px dashed red; } input:invalid:required { background-image: linear-gradient(to right, pink, lightgreen); } input:valid { border: 2px solid black; } ``` This CSS causes the input to have a red dashed border when it is invalid and a more subtle solid black border when valid. We also added a background gradient when the input is required *and* invalid. Try out the new behavior in the example below: **Note:** You can find this example live on GitHub as fruit-validation.html. See also the source code. Try submitting the form without a value. Note how the invalid input gets focus, a default error message ("Please fill out this field") appears, and the form is prevented from being sent. The presence of the `required` attribute on any element that supports this attribute means the element matches the `:required` pseudo-class whether it has a value or not. If the `<input>` has no value, the `input` will match the `:invalid` pseudo-class. **Note:** For good user experience, indicate to the user when form fields are required. It isn't only good user experience, it is required by WCAG accessibility guidelines. Also, only require users to input data you actually need: For example, why do you really need to know someone's gender or title? ### Validating against a regular expression Another useful validation feature is the `pattern` attribute, which expects a Regular Expression as its value. A regular expression (regexp) is a pattern that can be used to match character combinations in text strings, so regexps are ideal for form validation and serve a variety of other uses in JavaScript. Regexps are quite complex, and we don't intend to teach you them exhaustively in this article. Below are some examples to give you a basic idea of how they work. * `a` — Matches one character that is `a` (not `b`, not `aa`, and so on). * `abc` — Matches `a`, followed by `b`, followed by `c`. * `ab?c` — Matches `a`, optionally followed by a single `b`, followed by `c`. (`ac` or `abc`) * `ab*c` — Matches `a`, optionally followed by any number of `b`s, followed by `c`. (`ac`, `abc`, `abbbbbc`, and so on). * `a|b` — Matches one character that is `a` or `b`. * `abc|xyz` — Matches exactly `abc` or exactly `xyz` (but not `abcxyz` or `a` or `y`, and so on). There are many more possibilities that we don't cover here. For a complete list and many examples, consult our Regular expression documentation. Let's implement an example. Update your HTML to add a `pattern` attribute like this: ```html <form> <label for="choose">Would you prefer a banana or a cherry?</label> <input id="choose" name="i-like" required pattern="[Bb]anana|[Cc]herry" /> <button>Submit</button> </form> ``` ``` input:invalid { border: 2px dashed red; } input:valid { border: 2px solid black; } ``` This gives us the following update — try it out: **Note:** You can find this example live on GitHub as fruit-pattern.html (see also the source code.) In this example, the `<input>` element accepts one of four possible values: the strings "banana", "Banana", "cherry", or "Cherry". Regular expressions are case-sensitive, but we've made it support capitalized as well as lower-case versions using an extra "Aa" pattern nested inside square brackets. At this point, try changing the value inside the `pattern` attribute to equal some of the examples you saw earlier, and look at how that affects the values you can enter to make the input value valid. Try writing some of your own, and see how it goes. Make them fruit-related where possible so that your examples make sense! If a non-empty value of the `<input>` doesn't match the regular expression's pattern, the `input` will match the `:invalid` pseudo-class. **Note:** Some `<input>` element types don't need a `pattern` attribute to be validated against a regular expression. Specifying the `email` type, for example, validates the inputs value against a well-formed email address pattern or a pattern matching a comma-separated list of email addresses if it has the `multiple` attribute. **Note:** The `<textarea>` element doesn't support the `pattern` attribute. ### Constraining the length of your entries You can constrain the character length of all text fields created by `<input>` or `<textarea>` by using the `minlength` and `maxlength` attributes. A field is invalid if it has a value and that value has fewer characters than the `minlength` value or more than the `maxlength` value. Browsers often don't let the user type a longer value than expected into text fields. A better user experience than just using `maxlength` is to also provide character count feedback in an accessible manner and let them edit their content down to size. An example of this is the character limit seen on Twitter when Tweeting. JavaScript, including solutions using `maxlength`, can be used to provide this. ### Constraining the values of your entries For number fields (i.e. `<input type="number">`), the `min` and `max` attributes can be used to provide a range of valid values. If the field contains a value outside this range, it will be invalid. Let's look at another example. Create a new copy of the fruit-start.html file. Now delete the contents of the `<body>` element, and replace it with the following: ```html <form> <div> <label for="choose">Would you prefer a banana or a cherry?</label> <input type="text" id="choose" name="i-like" required minlength="6" maxlength="6" /> </div> <div> <label for="number">How many would you like?</label> <input type="number" id="number" name="amount" value="1" min="1" max="10" /> </div> <div> <button>Submit</button> </div> </form> ``` * Here you'll see that we've given the `text` field a `minlength` and `maxlength` of six, which is the same length as banana and cherry. * We've also given the `number` field a `min` of one and a `max` of ten. Entered numbers outside this range will show as invalid; users won't be able to use the increment/decrement arrows to move the value outside of this range. If the user manually enters a number outside of this range, the data is invalid. The number is not required, so removing the value will still result in a valid value. ``` input:invalid { border: 2px dashed red; } input:valid { border: 2px solid black; } div { margin-bottom: 10px; } ``` Here is the example running live: **Note:** You can find this example live on GitHub as fruit-length.html. See also the source code. **Note:** `<input type="number">` (and other types, such as `range` and `date`) can also take a `step` attribute, which specifies what increment the value will go up or down by when the input controls are used (such as the up and down number buttons). In the above example we've not included a `step` attribute, so the value defaults to `1`. This means that floats, like 3.2, will also show as invalid. ### Full example Here is a full example to show usage of HTML's built-in validation features. First, some HTML: ```html <form> <fieldset> <legend> Do you have a driver's license?<span aria-label="required">*</span> </legend> <!-- While only one radio button in a same-named group can be selected at a time, and therefore only one radio button in a same-named group having the "required" attribute suffices in making a selection a requirement --> <input type="radio" required name="driver" id="r1" value="yes" /><label for="r1" >Yes</label > <input type="radio" required name="driver" id="r2" value="no" /><label for="r2" >No</label > </fieldset> <p> <label for="n1">How old are you?</label> <!-- The pattern attribute can act as a fallback for browsers which don't implement the number input type but support the pattern attribute. Please note that browsers that support the pattern attribute will make it fail silently when used with a number field. Its usage here acts only as a fallback --> <input type="number" min="12" max="120" step="1" id="n1" name="age" pattern="\d+" /> </p> <p> <label for="t1" >What's your favorite fruit?<span aria-label="required">*</span></label > <input type="text" id="t1" name="fruit" list="l1" required pattern="[Bb]anana|[Cc]herry|[Aa]pple|[Ss]trawberry|[Ll]emon|[Oo]range" /> <datalist id="l1"> <option>Banana</option> <option>Cherry</option> <option>Apple</option> <option>Strawberry</option> <option>Lemon</option> <option>Orange</option> </datalist> </p> <p> <label for="t2">What's your email address?</label> <input type="email" id="t2" name="email" /> </p> <p> <label for="t3">Leave a short message</label> <textarea id="t3" name="msg" maxlength="140" rows="5"></textarea> </p> <p> <button>Submit</button> </p> </form> ``` And now some CSS to style the HTML: ```css form { font: 1em sans-serif; max-width: 320px; } p > label { display: block; } input[type="text"], input[type="email"], input[type="number"], textarea, fieldset { width: 100%; border: 1px solid #333; box-sizing: border-box; } input:invalid { box-shadow: 0 0 5px 1px red; } input:focus:invalid { box-shadow: none; } ``` This renders as follows: See Validation-related attributes for a complete list of attributes that can be used to constrain input values and the input types that support them. **Note:** You can find this example live on GitHub as full-example.html (see also the source code.) Validating forms using JavaScript --------------------------------- You must use JavaScript if you want to take control over the look and feel of native error messages. In this section we will look at the different ways to do this. ### The Constraint Validation API The Constraint Validation API consists of a set of methods and properties available on the following form element DOM interfaces: * `HTMLButtonElement` (represents a `<button>` element) * `HTMLFieldSetElement` (represents a `<fieldset>` element) * `HTMLInputElement` (represents an `<input>` element) * `HTMLOutputElement` (represents an `<output>` element) * `HTMLSelectElement` (represents a `<select>` element) * `HTMLTextAreaElement` (represents a `<textarea>` element) The Constraint Validation API makes the following properties available on the above elements. * `validationMessage`: Returns a localized message describing the validation constraints that the control doesn't satisfy (if any). If the control is not a candidate for constraint validation (`willValidate` is `false`) or the element's value satisfies its constraints (is valid), this will return an empty string. * `validity`: Returns a `ValidityState` object that contains several properties describing the validity state of the element. You can find full details of all the available properties in the `ValidityState` reference page; below is listed a few of the more common ones: + `patternMismatch`: Returns `true` if the value does not match the specified `pattern`, and `false` if it does match. If true, the element matches the `:invalid` CSS pseudo-class. + `tooLong`: Returns `true` if the value is longer than the maximum length specified by the `maxlength` attribute, or `false` if it is shorter than or equal to the maximum. If true, the element matches the `:invalid` CSS pseudo-class. + `tooShort`: Returns `true` if the value is shorter than the minimum length specified by the `minlength` attribute, or `false` if it is greater than or equal to the minimum. If true, the element matches the `:invalid` CSS pseudo-class. + `rangeOverflow`: Returns `true` if the value is greater than the maximum specified by the `max` attribute, or `false` if it is less than or equal to the maximum. If true, the element matches the `:invalid` and `:out-of-range` CSS pseudo-classes. + `rangeUnderflow`: Returns `true` if the value is less than the minimum specified by the `min` attribute, or `false` if it is greater than or equal to the minimum. If true, the element matches the `:invalid` and `:out-of-range` CSS pseudo-classes. + `typeMismatch`: Returns `true` if the value is not in the required syntax (when `type` is `email` or `url`), or `false` if the syntax is correct. If `true`, the element matches the `:invalid` CSS pseudo-class. + `valid`: Returns `true` if the element meets all its validation constraints, and is therefore considered to be valid, or `false` if it fails any constraint. If true, the element matches the `:valid` CSS pseudo-class; the `:invalid` CSS pseudo-class otherwise. + `valueMissing`: Returns `true` if the element has a `required` attribute, but no value, or `false` otherwise. If true, the element matches the `:invalid` CSS pseudo-class. * `willValidate`: Returns `true` if the element will be validated when the form is submitted; `false` otherwise. The Constraint Validation API also makes the following methods available on the above elements and the `form` element. * `checkValidity()`: Returns `true` if the element's value has no validity problems; `false` otherwise. If the element is invalid, this method also fires an `invalid` event on the element. * `reportValidity()`: Reports invalid field(s) using events. This method is useful in combination with `preventDefault()` in an `onSubmit` event handler. * `setCustomValidity(message)`: Adds a custom error message to the element; if you set a custom error message, the element is considered to be invalid, and the specified error is displayed. This lets you use JavaScript code to establish a validation failure other than those offered by the standard HTML validation constraints. The message is shown to the user when reporting the problem. #### Implementing a customized error message As you saw in the HTML validation constraint examples earlier, each time a user tries to submit an invalid form, the browser displays an error message. The way this message is displayed depends on the browser. These automated messages have two drawbacks: * There is no standard way to change their look and feel with CSS. * They depend on the browser locale, which means that you can have a page in one language but an error message displayed in another language, as seen in the following Firefox screenshot. ![Example of an error message with Firefox in French on an English page](/en-US/docs/Learn/Forms/Form_validation/error-firefox-win7.png) Customizing these error messages is one of the most common use cases of the Constraint Validation API. Let's work through a simple example of how to do this. We'll start with some simple HTML (feel free to put this in a blank HTML file; use a fresh copy of fruit-start.html as a basis, if you like): ```html <form> <label for="mail"> I would like you to provide me with an email address: </label> <input type="email" id="mail" name="mail" /> <button>Submit</button> </form> ``` And add the following JavaScript to the page: ```js const email = document.getElementById("mail"); email.addEventListener("input", (event) => { if (email.validity.typeMismatch) { email.setCustomValidity("I am expecting an email address!"); } else { email.setCustomValidity(""); } }); ``` Here we store a reference to the email input, then add an event listener to it that runs the contained code each time the value inside the input is changed. Inside the contained code, we check whether the email input's `validity.typeMismatch` property returns `true`, meaning that the contained value doesn't match the pattern for a well-formed email address. If so, we call the `setCustomValidity()` method with a custom message. This renders the input invalid, so that when you try to submit the form, submission fails and the custom error message is displayed. If the `validity.typeMismatch` property returns `false`, we call the `setCustomValidity()` method with an empty string. This renders the input valid, so the form will submit. You can try it out below: **Note:** You can find this example live on GitHub as custom-error-message.html (see also the source code.) #### A more detailed example Now that we've seen a really simple example, let's see how we can use this API to build some slightly more complex custom validation. First, the HTML. Again, feel free to build this along with us: ```html <form novalidate> <p> <label for="mail"> <span>Please enter an email address:</span> <input type="email" id="mail" name="mail" required minlength="8" /> <span class="error" aria-live="polite"></span> </label> </p> <button>Submit</button> </form> ``` This simple form uses the `novalidate` attribute to turn off the browser's automatic validation; this lets our script take control over validation. However, this doesn't disable support for the constraint validation API nor the application of CSS pseudo-classes like `:valid`, etc. That means that even though the browser doesn't automatically check the validity of the form before sending its data, you can still do it yourself and style the form accordingly. Our input to validate is an `<input type="email">`, which is `required`, and has a `minlength` of 8 characters. Let's check these using our own code, and show a custom error message for each one. We are aiming to show the error messages inside a `<span>` element. The `aria-live` attribute is set on that `<span>` to make sure that our custom error message will be presented to everyone, including it being read out to screen reader users. **Note:** A key point here is that setting the `novalidate` attribute on the form is what stops the form from showing its own error message bubbles, and allows us to instead display the custom error messages in the DOM in some manner of our own choosing. Now onto some basic CSS to improve the look of the form slightly, and provide some visual feedback when the input data is invalid: ```css body { font: 1em sans-serif; width: 200px; padding: 0; margin: 0 auto; } p \* { display: block; } input[type="email"] { appearance: none; width: 100%; border: 1px solid #333; margin: 0; font-family: inherit; font-size: 90%; box-sizing: border-box; } /\* This is our style for the invalid fields \*/ input:invalid { border-color: #900; background-color: #fdd; } input:focus:invalid { outline: none; } /\* This is the style of our error messages \*/ .error { width: 100%; padding: 0; font-size: 80%; color: white; background-color: #900; border-radius: 0 0 5px 5px; box-sizing: border-box; } .error.active { padding: 0.3em; } ``` Now let's look at the JavaScript that implements the custom error validation. ```js // There are many ways to pick a DOM node; here we get the form itself and the email // input box, as well as the span element into which we will place the error message. const form = document.querySelector("form"); const email = document.getElementById("mail"); const emailError = document.querySelector("#mail + span.error"); email.addEventListener("input", (event) => { // Each time the user types something, we check if the // form fields are valid. if (email.validity.valid) { // In case there is an error message visible, if the field // is valid, we remove the error message. emailError.textContent = ""; // Reset the content of the message emailError.className = "error"; // Reset the visual state of the message } else { // If there is still an error, show the correct error showError(); } }); form.addEventListener("submit", (event) => { // if the email field is valid, we let the form submit if (!email.validity.valid) { // If it isn't, we display an appropriate error message showError(); // Then we prevent the form from being sent by canceling the event event.preventDefault(); } }); function showError() { if (email.validity.valueMissing) { // If the field is empty, // display the following error message. emailError.textContent = "You need to enter an email address."; } else if (email.validity.typeMismatch) { // If the field doesn't contain an email address, // display the following error message. emailError.textContent = "Entered value needs to be an email address."; } else if (email.validity.tooShort) { // If the data is too short, // display the following error message. emailError.textContent = `Email should be at least ${email.minLength} characters; you entered ${email.value.length}.`; } // Set the styling appropriately emailError.className = "error active"; } ``` The comments explain things pretty well, but briefly: * Every time we change the value of the input, we check to see if it contains valid data. If it has then we remove any error message being shown. If the data is not valid, we run `showError()` to show the appropriate error. * Every time we try to submit the form, we again check to see if the data is valid. If so, we let the form submit. If not, we run `showError()` to show the appropriate error, and stop the form submitting with `preventDefault()`. * The `showError()` function uses various properties of the input's `validity` object to determine what the error is, and then displays an error message as appropriate. Here is the live result: **Note:** You can find this example live on GitHub as detailed-custom-validation.html. See also the source code. The constraint validation API gives you a powerful tool to handle form validation, letting you have enormous control over the user interface above and beyond what you can do with HTML and CSS alone. ### Validating forms without a built-in API In some cases, such as custom controls, you won't be able to or won't want to use the Constraint Validation API. You're still able to use JavaScript to validate your form, but you'll just have to write your own. To validate a form, ask yourself a few questions: What kind of validation should I perform? You need to determine how to validate your data: string operations, type conversion, regular expressions, and so on. It's up to you. What should I do if the form doesn't validate? This is clearly a UI matter. You have to decide how the form will behave. Does the form send the data anyway? Should you highlight the fields that are in error? Should you display error messages? How can I help the user to correct invalid data? In order to reduce the user's frustration, it's very important to provide as much helpful information as possible in order to guide them in correcting their inputs. You should offer up-front suggestions so they know what's expected, as well as clear error messages. If you want to dig into form validation UI requirements, here are some useful articles you should read: * Help users enter the right data in forms * Validating input * How to Report Errors in Forms: 10 Design Guidelines #### An example that doesn't use the constraint validation API In order to illustrate this, the following is a simplified version of the previous example without the Constraint Validation API. The HTML is almost the same; we just removed the HTML validation features. ```html <form> <p> <label for="mail"> <span>Please enter an email address:</span> <input type="text" id="mail" name="mail" /> <span class="error" aria-live="polite"></span> </label> </p> <button>Submit</button> </form> ``` Similarly, the CSS doesn't need to change very much; we've just turned the `:invalid` CSS pseudo-class into a real class and avoided using the attribute selector. ```css body { font: 1em sans-serif; width: 200px; padding: 0; margin: 0 auto; } form { max-width: 200px; } p \* { display: block; } input#mail { appearance: none; width: 100%; border: 1px solid #333; margin: 0; font-family: inherit; font-size: 90%; box-sizing: border-box; } /\* This is our style for the invalid fields \*/ input.invalid { border-color: #900; background-color: #fdd; } input:focus:invalid { outline: none; } /\* This is the style of our error messages \*/ .error { width: 100%; padding: 0; font-size: 80%; color: white; background-color: #900; border-radius: 0 0 5px 5px; box-sizing: border-box; } .error.active { padding: 0.3em; } ``` The big changes are in the JavaScript code, which needs to do much more heavy lifting. ```js const form = document.querySelector("form"); const email = document.getElementById("mail"); const error = email.nextElementSibling; // As per the HTML Specification const emailRegExp = /^[a-zA-Z0-9.!#$%&'\*+/=?^\_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)\*$/; // Now we can rebuild our validation constraint // Because we do not rely on CSS pseudo-class, we have to // explicitly set the valid/invalid class on our email field window.addEventListener("load", () => { // Here, we test if the field is empty (remember, the field is not required) // If it is not, we check if its content is a well-formed email address. const isValid = email.value.length === 0 || emailRegExp.test(email.value); email.className = isValid ? "valid" : "invalid"; }); // This defines what happens when the user types in the field email.addEventListener("input", () => { const isValid = email.value.length === 0 || emailRegExp.test(email.value); if (isValid) { email.className = "valid"; error.textContent = ""; error.className = "error"; } else { email.className = "invalid"; } }); // This defines what happens when the user tries to submit the data form.addEventListener("submit", (event) => { event.preventDefault(); const isValid = email.value.length === 0 || emailRegExp.test(email.value); if (!isValid) { email.className = "invalid"; error.textContent = "I expect an email, darling!"; error.className = "error active"; } else { email.className = "valid"; error.textContent = ""; error.className = "error"; } }); ``` The result looks like this: As you can see, it's not that hard to build a validation system on your own. The difficult part is to make it generic enough to use both cross-platform and on any form you might create. There are many libraries available to perform form validation, such as Validate.js. Test your skills! ----------------- You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Form validation. Summary ------- Client-side form validation sometimes requires JavaScript if you want to customize styling and error messages, but it *always* requires you to think carefully about the user. Always remember to help your users correct the data they provide. To that end, be sure to: * Display explicit error messages. * Be permissive about the input format. * Point out exactly where the error occurs, especially on large forms. Once you have checked that the form is filled out correctly, the form can be submitted. We'll cover sending form data next. * Previous * Overview: Forms * Next ### Advanced Topics * How to build custom form controls * Sending forms through JavaScript * Property compatibility table for form widgets
How to build custom form controls - Learn web development
How to build custom form controls ================================= There are some cases where the available native HTML form controls may seem like they are not enough. For example, if you need to perform advanced styling on some controls such as the `<select>` element, or if you want to provide custom behaviors, you may consider building your own controls. In this article, we will discuss how to build a custom control. To that end, we will work with an example: rebuilding the `<select>` element. We will also discuss how, when, and whether building your own control makes sense, and what to consider when building a control is a requirement. **Note:** We'll focus on building the control, not on how to make the code generic and reusable; that would involve some non-trivial JavaScript code and DOM manipulation in an unknown context, and that is out of the scope of this article. Design, structure, and semantics -------------------------------- Before building a custom control, you should start by figuring out exactly what you want. This will save you some precious time. In particular, it's important to clearly define all the states of your control. To do this, it's good to start with an existing control whose states and behavior are well known, so that you can mimic those as much as possible. In our example, we will rebuild the `<select>` element. Here is the result we want to achieve: ![The three states of a select box](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls/custom-select.png) This screenshot shows the three main states of our control: the normal state (on the left); the active state (in the middle) and the open state (on the right). In terms of behavior, we are recreating a native HTML element. Therefore it should have the same behaviors and semantics as the native HTML element. We require our control to be usable with a mouse as well as with a keyboard, and comprehensible to a screen reader, just like any native control. Let's start by defining how the control reaches each state: **The control is in its normal state when:** * the page loads. * the control was active and the user clicks anywhere outside it. * the control was active and the user moves the focus to another control using the keyboard (e.g. the `Tab` key). **The control is in its active state when:** * the user clicks on it or touches it on a touch screen. * the user hits the tab key and it gains focus. * the control was in its open state and the user clicks on it. **The control is in its open state when:** * the control is in any other state than open and the user clicks on it. Once we know how to change states, it is important to define how to change the control's value: **The value changes when:** * the user clicks on an option when the control is in the open state. * the user hits the up or down arrow keys when the control is in its active state. **The value does not change when:** * the user hits the up arrow key when the first option is selected. * the user hits the down arrow key when the last option is selected. Finally, let's define how the control's options will behave: * When the control is opened, the selected option is highlighted * When the mouse is over an option, the option is highlighted and the previously highlighted option is returned to its normal state For the purposes of our example, we'll stop with that; however, if you're a careful reader, you'll notice that some behaviors are missing. For example, what do you think will happen if the user hits the tab key while the control is in its open state? The answer is *nothing*. OK, the right behavior seems obvious but the fact is, because it's not defined in our specs, it is very easy to overlook this behavior. This is especially true in a team environment when the people who design the control's behavior are different from the ones who implement it. Another fun example: what will happen if the user hits the up or down arrow keys while the control is in the open state? This one is a little bit trickier. If you consider that the active state and the open state are completely different, the answer is again "nothing will happen" because we did not define any keyboard interactions for the opened state. On the other hand, if you consider that the active state and the open state overlap a bit, the value may change but the option will definitely not be highlighted accordingly, once again because we did not define any keyboard interactions over options when the control is in its opened state (we have only defined what should happen when the control is opened, but nothing after that). We have to think a little further: what about the escape key? Pressing `Esc` key closes an open select. Remember, if you want to provide the same functionality as the existing native `<select>`, it should behave the exact same way as the select for all users, from keyboard to mouse to touch to screen reader, and any other input device. In our example, the missing specifications are obvious so we will handle them, but it can be a real problem for exotic new controls. When it comes to standardized elements, of which the `<select>` is one, the specification authors spent an inordinate amount of time specifying all interactions for every use case for every input device. Creating new controls is not that easy, especially if you are creating something that has not been done before, and therefore nobody has the slightest idea of what the expected behaviors and interactions are. At least select has been done before, so we know how it should behave! Designing new interactions is generally only an option for very large industry players who have enough reach that an interaction they create can become a standard. For example, Apple introduced the scroll wheel with the iPod in 2001. They had the market share to successfully introduce a completely new way of interacting with a device, something most device companies can't do. It is best not to invent new user interactions. For any interaction you do add, it is vital to spend time in the design stage; if you define a behavior poorly, or forget to define one, it will be very hard to redefine it once the users have gotten used to it. If you have doubts, ask for the opinions of others, and if you have the budget for it, do not hesitate to perform user tests. This process is called UX Design. If you want to learn more about this topic, you should check out the following helpful resources: * UXMatters.com * UXDesign.com * The UX Design section of SmashingMagazine **Note:** Also, in most systems there is a way to open the `<select>` element with the keyboard to look at all the available choices (this is the same as clicking the `<select>` element with a mouse). This is achieved with `Alt` + `Down` on Windows. We didn't implement this in our example, but it would be easy to do so, as the mechanism has already been implemented for the `click` event. Defining the HTML structure and (some) semantics ------------------------------------------------ Now that the control's basic functionality has been decided upon, it's time to start building it. The first step is to define its HTML structure and give it some basic semantics. Here is what we need to rebuild a `<select>` element: ```html <!-- This is our main container for our control. The tabindex attribute is what allows the user to focus on the control. We'll see later that it's better to set it through JavaScript. --> <div class="select" tabindex="0"> <!-- This container will be used to display the current value of the control --> <span class="value">Cherry</span> <!-- This container will contain all the options available for our control. Because it's a list, it makes sense to use the ul element. --> <ul class="optList"> <!-- Each option only contains the value to be displayed, we'll see later how to handle the real value that will be sent with the form data --> <li class="option">Cherry</li> <li class="option">Lemon</li> <li class="option">Banana</li> <li class="option">Strawberry</li> <li class="option">Apple</li> </ul> </div> ``` Note the use of class names; these identify each relevant part regardless of the actual underlying HTML elements used. This is important to make sure that we don't bind our CSS and JavaScript to a strong HTML structure, so that we can make implementation changes later without breaking code that uses the control. For example, what if you wish to implement the equivalent of the `<optgroup>` element later on? Class names, however, provide no semantic value. In this current state, the screen reader user only "sees" an unordered list. We will add ARIA semantics in a bit. Creating the look and feel using CSS ------------------------------------ Now that we have a structure, we can start designing our control. The whole point of building this custom control is to be able to style it exactly how we want. To that end, we will split our CSS work into two parts: the first part will be the CSS rules absolutely necessary to make our control behave like a `<select>` element, and the second part will consist of the fancy styles used to make it look the way we want. ### Required styles The required styles are those necessary to handle the three states of our control. ```css .select { /\* This will create a positioning context for the list of options; adding this to `.select:focus-within` will be a better option when fully supported \*/ position: relative; /\* This will make our control become part of the text flow and sizable at the same time \*/ display: inline-block; } ``` We need an extra class `active` to define the look and feel of our control when it is in its active state. Because our control is focusable, we double this custom style with the `:focus` pseudo-class in order to be sure they will behave the same. ```css .select.active, .select:focus { outline-color: transparent; /\* This box-shadow property is not exactly required, however it's imperative to ensure active state is visible, especially to keyboard users, that we use it as a default value. \*/ box-shadow: 0 0 3px 1px #227755; } ``` Now, let's handle the list of options: ```css /\* The .select selector here helps to make sure we only select element inside our control. \*/ .select .optList { /\* This will make sure our list of options will be displayed below the value and out of the HTML flow \*/ position: absolute; top: 100%; left: 0; } ``` We need an extra class to handle when the list of options is hidden. This is necessary in order to manage the differences between the active state and the open state that do not exactly match. ```css .select .optList.hidden { /\* This is a simple way to hide the list in an accessible way; we will talk more about accessibility in the end \*/ max-height: 0; visibility: hidden; } ``` **Note:** We could also have used `transform: scale(1, 0)` to give the option list no height and full width. ### Beautification So now that we have the basic functionality in place, the fun can start. The following is just an example of what is possible, and will match the screenshot at the beginning of this article. However, you should feel free to experiment and see what you can come up with. ```css .select { /\* The computations are made assuming 1em equals 16px which is the default value in most browsers. If you are lost with px to em conversion, try https://nekocalc.com/px-to-em-converter \*/ font-size: 0.625em; /\* this (10px) is the new font size context for em value in this context \*/ font-family: Verdana, Arial, sans-serif; box-sizing: border-box; /\* We need extra room for the down arrow we will add \*/ padding: 0.1em 2.5em 0.2em 0.5em; width: 10em; /\* 100px \*/ border: 0.2em solid #000; border-radius: 0.4em; box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /\* The first declaration is for browsers that do not support linear gradients. \*/ background: #f0f0f0; background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { /\* Because the value can be wider than our control, we have to make sure it will not change the control's width. If the content overflows, we display an ellipsis \*/ display: inline-block; width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; vertical-align: top; } ``` We don't need an extra element to design the down arrow; instead, we're using the `::after` pseudo-element. It could also be implemented using a simple background image on the `select` class. ```css .select::after { content: "▼"; /\* We use the unicode character U+25BC; make sure to set a charset meta tag \*/ position: absolute; z-index: 1; /\* This will be important to keep the arrow from overlapping the list of options \*/ top: 0; right: 0; box-sizing: border-box; height: 100%; width: 2em; padding-top: 0.1em; border-left: 0.2em solid #000; border-radius: 0 0.1em 0.1em 0; background-color: #000; color: #fff; text-align: center; } ``` Next, let's style the list of options: ```css .select .optList { z-index: 2; /\* We explicitly said the list of options will always be on top of the down arrow \*/ /\* this will reset the default style of the ul element \*/ list-style: none; margin: 0; padding: 0; box-sizing: border-box; /\* If the values are smaller than the control, the list of options will be as wide as the control itself \*/ min-width: 100%; /\* In case the list is too long, its content will overflow vertically (which will add a vertical scrollbar automatically) but never horizontally (because we haven't set a width, the list will adjust its width automatically. If it can't, the content will be truncated) \*/ max-height: 10em; /\* 100px \*/ overflow-y: auto; overflow-x: hidden; border: 0.2em solid #000; border-top-width: 0.1em; border-radius: 0 0 0.4em 0.4em; box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%); background: #f0f0f0; } ``` For the options, we need to add a `highlight` class to be able to identify the value the user will pick (or has picked). ```css .select .option { padding: 0.2em 0.3em; /\* 2px 3px \*/ } .select .highlight { background: #000; color: #ffffff; } ``` So here's the result with our three states (check out the source code here): #### Basic state ``` <div class="select"> <span class="value">Cherry</span> <ul class="optList hidden"> <li class="option">Cherry</li> <li class="option">Lemon</li> <li class="option">Banana</li> <li class="option">Strawberry</li> <li class="option">Apple</li> </ul> </div> ``` ``` .select { position: relative; display: inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline-color: transparent; } .select .optList { position: absolute; top: 100%; left: 0; } .select .optList.hidden { max-height: 0; visibility: hidden; } .select { font-size: 0.625em; /\* 10px \*/ font-family: Verdana, Arial, sans-serif; box-sizing: border-box; padding: 0.1em 2.5em 0.2em 0.5em; /\* 1px 25px 2px 5px \*/ width: 10em; /\* 100px \*/ border: 0.2em solid #000; /\* 2px \*/ border-radius: 0.4em; /\* 4px \*/ box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /\* 0 1px 2px \*/ background: #f0f0f0; background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display: inline-block; width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; vertical-align: top; } .select::after { content: "▼"; position: absolute; z-index: 1; height: 100%; width: 2em; /\* 20px \*/ top: 0; right: 0; padding-top: 0.1em; box-sizing: border-box; text-align: center; border-left: 0.2em solid #000; border-radius: 0 0.1em 0.1em 0; background-color: #000; color: #fff; } .select .optList { z-index: 2; list-style: none; margin: 0; padding: 0; background: #f0f0f0; border: 0.2em solid #000; border-top-width: 0.1em; border-radius: 0 0 0.4em 0.4em; box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%); box-sizing: border-box; min-width: 100%; max-height: 10em; /\* 100px \*/ overflow-y: auto; overflow-x: hidden; } .select .option { padding: 0.2em 0.3em; } .select .highlight { background: #000; color: #ffffff; } ``` #### Active state ``` <div class="select active"> <span class="value">Cherry</span> <ul class="optList hidden"> <li class="option">Cherry</li> <li class="option">Lemon</li> <li class="option">Banana</li> <li class="option">Strawberry</li> <li class="option">Apple</li> </ul> </div> ``` ``` .select { position: relative; display: inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline-color: transparent; } .select .optList { position: absolute; top: 100%; left: 0; } .select .optList.hidden { max-height: 0; visibility: hidden; } .select { font-size: 0.625em; /\* 10px \*/ font-family: Verdana, Arial, sans-serif; box-sizing: border-box; padding: 0.1em 2.5em 0.2em 0.5em; /\* 1px 25px 2px 5px \*/ width: 10em; /\* 100px \*/ border: 0.2em solid #000; /\* 2px \*/ border-radius: 0.4em; /\* 4px \*/ box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /\* 0 1px 2px \*/ background: #f0f0f0; background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display: inline-block; width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; vertical-align: top; } .select::after { content: "▼"; position: absolute; z-index: 1; height: 100%; width: 2em; /\* 20px \*/ top: 0; right: 0; padding-top: 0.1em; box-sizing: border-box; text-align: center; border-left: 0.2em solid #000; border-radius: 0 0.1em 0.1em 0; background-color: #000; color: #fff; } .select .optList { z-index: 2; list-style: none; margin: 0; padding: 0; background: #f0f0f0; border: 0.2em solid #000; border-top-width: 0.1em; border-radius: 0 0 0.4em 0.4em; box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%); box-sizing: border-box; min-width: 100%; max-height: 10em; /\* 100px \*/ overflow-y: auto; overflow-x: hidden; } .select .option { padding: 0.2em 0.3em; } .select .highlight { background: #000; color: #ffffff; } ``` #### Open state ``` <div class="select active"> <span class="value">Cherry</span> <ul class="optList"> <li class="option highlight">Cherry</li> <li class="option">Lemon</li> <li class="option">Banana</li> <li class="option">Strawberry</li> <li class="option">Apple</li> </ul> </div> ``` ``` .select { position: relative; display: inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline-color: transparent; } .select .optList { position: absolute; top: 100%; left: 0; } .select .optList.hidden { max-height: 0; visibility: hidden; } .select { font-size: 0.625em; /\* 10px \*/ font-family: Verdana, Arial, sans-serif; box-sizing: border-box; padding: 0.1em 2.5em 0.2em 0.5em; /\* 1px 25px 2px 5px \*/ width: 10em; /\* 100px \*/ border: 0.2em solid #000; /\* 2px \*/ border-radius: 0.4em; /\* 4px \*/ box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /\* 0 1px 2px \*/ background: #f0f0f0; background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display: inline-block; width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; vertical-align: top; } .select::after { content: "▼"; position: absolute; z-index: 1; height: 100%; width: 2em; /\* 20px \*/ top: 0; right: 0; padding-top: 0.1em; box-sizing: border-box; text-align: center; border-left: 0.2em solid #000; border-radius: 0 0.1em 0.1em 0; background-color: #000; color: #fff; } .select .optList { z-index: 2; list-style: none; margin: 0; padding: 0; background: #f0f0f0; border: 0.2em solid #000; border-top-width: 0.1em; border-radius: 0 0 0.4em 0.4em; box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%); box-sizing: border-box; min-width: 100%; max-height: 10em; /\* 100px \*/ overflow-y: auto; overflow-x: hidden; } .select .option { padding: 0.2em 0.3em; } .select .highlight { background: #000; color: #fff; } ``` Bringing your control to life with JavaScript --------------------------------------------- Now that our design and structure are ready, we can write the JavaScript code to make the control actually work. **Warning:** The following is educational code, not production code, and should not be used as-is. It is neither future-proof nor will work on legacy browsers. It also has redundant parts that should be optimized in production code. ### Why isn't it working? Before starting, it's important to remember **JavaScript in the browser is an unreliable technology**. Custom controls rely on JavaScript to tie everything together. However, there are cases in which JavaScript isn't able to run in the browser: * The user has turned off JavaScript: This is unusual; very few people turn off JavaScript nowadays. * The script did not load: This is one of the most common cases, especially in the mobile world where the network is not very reliable. * The script is buggy: You should always consider this possibility. * The script conflicts with a third-party script: This can happen with tracking scripts or any bookmarklets the user uses. * The script conflicts with, or is affected by, a browser extension (such as Firefox's NoScript extension or Chrome's ScriptBlock extension). * The user is using a legacy browser, and one of the features you require is not supported: This will happen frequently when you make use of cutting-edge APIs. * The user is interacting with the content before the JavaScript has been fully downloaded, parsed, and executed. Because of these risks, it's really important to seriously consider what will happen if your JavaScript doesn't work. We'll discuss options to consider and cover the basics in our example (a full discussion of solving this issue for all scenarios would require a book). Just remember, it is vital to make your script generic and reusable. In our example, if our JavaScript code isn't running, we'll fall back to displaying a standard `<select>` element. We include our control and the `<select>`; which one is displayed depends on the class of the body element, with the class of the body element being updated by the script that makes the control function, when it loads successfully. To achieve this, we need two things: First, we need to add a regular `<select>` element before each instance of our custom control. There is a benefit to having this "extra" select even if our JavaScript works as hoped: we will use this select to send data from our custom control along with the rest of our form data. We will discuss this in greater depth later. ```html <body> <form class="no-widget"> <select name="myFruit"> <option>Cherry</option> <option>Lemon</option> <option>Banana</option> <option>Strawberry</option> <option>Apple</option> </select> <div class="select"> <span class="value">Cherry</span> <ul class="optList hidden"> <li class="option">Cherry</li> <li class="option">Lemon</li> <li class="option">Banana</li> <li class="option">Strawberry</li> <li class="option">Apple</li> </ul> </div> </form> </body> ``` Second, we need two new classes to let us hide the unneeded element: we visually hide the custom control if our script isn't running, or the "real" `<select>` element if it is running. Note that, by default, our HTML code hides our custom control. ```css .widget select, .no-widget .select { /\* This CSS selector basically says: - either we have set the body class to "widget" and thus we hide the actual <select> element - or we have not changed the body class, therefore the body class is still "no-widget", so the elements whose class is "select" must be hidden \*/ position: absolute; left: -5000em; height: 0; overflow: hidden; } ``` This CSS visually hides one of the elements, but it is still available to screen readers. Now we need a JavaScript switch to determine if the script is running or not. This switch is a couple of lines: if at page load time our script is running, it will remove the `no-widget` class and add the `widget` class, thereby swapping the visibility of the `<select>` element and the custom control. ```js window.addEventListener("load", () => { document.body.classList.remove("no-widget"); document.body.classList.add("widget"); }); ``` #### Without JS Check out the full source code. ``` <form class="no-widget"> <select name="myFruit"> <option>Cherry</option> <option>Lemon</option> <option>Banana</option> <option>Strawberry</option> <option>Apple</option> </select> <div class="select"> <span class="value">Cherry</span> <ul class="optList hidden"> <li class="option">Cherry</li> <li class="option">Lemon</li> <li class="option">Banana</li> <li class="option">Strawberry</li> <li class="option">Apple</li> </ul> </div> </form> ``` ``` .widget select, .no-widget .select { position: absolute; left: -5000em; height: 0; overflow: hidden; } ``` #### With JS Check out the full source code. ``` <form class="no-widget"> <select name="myFruit"> <option>Cherry</option> <option>Lemon</option> <option>Banana</option> <option>Strawberry</option> <option>Apple</option> </select> <div class="select"> <span class="value">Cherry</span> <ul class="optList hidden"> <li class="option">Cherry</li> <li class="option">Lemon</li> <li class="option">Banana</li> <li class="option">Strawberry</li> <li class="option">Apple</li> </ul> </div> </form> ``` ``` .widget select, .no-widget .select { position: absolute; left: -5000em; height: 0; overflow: hidden; } .select { position: relative; display: inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline-color: transparent; } .select .optList { position: absolute; top: 100%; left: 0; } .select .optList.hidden { max-height: 0; visibility: hidden; } .select { font-size: 0.625em; /\* 10px \*/ font-family: Verdana, Arial, sans-serif; box-sizing: border-box; padding: 0.1em 2.5em 0.2em 0.5em; /\* 1px 25px 2px 5px \*/ width: 10em; /\* 100px \*/ border: 0.2em solid #000; /\* 2px \*/ border-radius: 0.4em; /\* 4px \*/ box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /\* 0 1px 2px \*/ background: #f0f0f0; background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display: inline-block; width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; vertical-align: top; } .select::after { content: "▼"; position: absolute; z-index: 1; height: 100%; width: 2em; /\* 20px \*/ top: 0; right: 0; padding-top: 0.1em; box-sizing: border-box; text-align: center; border-left: 0.2em solid #000; border-radius: 0 0.1em 0.1em 0; background-color: #000; color: #fff; } .select .optList { z-index: 2; list-style: none; margin: 0; padding: 0; background: #f0f0f0; border: 0.2em solid #000; border-top-width: 0.1em; border-radius: 0 0 0.4em 0.4em; box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%); box-sizing: border-box; min-width: 100%; max-height: 10em; /\* 100px \*/ overflow-y: auto; overflow-x: hidden; } .select .option { padding: 0.2em 0.3em; } .select .highlight { background: #000; color: #ffffff; } ``` ``` window.addEventListener("load", () => { const form = document.querySelector("form"); form.classList.remove("no-widget"); form.classList.add("widget"); }); ``` **Note:** If you really want to make your code generic and reusable, instead of doing a class switch it's far better to just add the widget class to hide the `<select>` elements, and to dynamically add the DOM tree representing the custom control after every `<select>` element in the page. ### Making the job easier In the code we are about to build, we will use the standard JavaScript and DOM APIs to do all the work we need. The features we plan to use are the following: 1. `classList` 2. `addEventListener()` 3. `NodeList.forEach()` 4. `querySelector()` and `querySelectorAll()` ### Building event callbacks The groundwork is done. We can now start to define all the functions that will be used each time the user interacts with our control. ```js // This function will be used each time we want to deactivate a custom control // It takes one parameter // select : the DOM node with the `select` class to deactivate function deactivateSelect(select) { // If the control is not active there is nothing to do if (!select.classList.contains("active")) return; // We need to get the list of options for the custom control const optList = select.querySelector(".optList"); // We close the list of option optList.classList.add("hidden"); // and we deactivate the custom control itself select.classList.remove("active"); } // This function will be used each time the user wants to activate the control // (which, in turn, will deactivate other select controls) // It takes two parameters: // select : the DOM node with the `select` class to activate // selectList : the list of all the DOM nodes with the `select` class function activeSelect(select, selectList) { // If the control is already active there is nothing to do if (select.classList.contains("active")) return; // We have to turn off the active state on all custom controls // Because the deactivateSelect function fulfills all the requirements of the // forEach callback function, we use it directly without using an intermediate // anonymous function. selectList.forEach(deactivateSelect); // And we turn on the active state for this specific control select.classList.add("active"); } // This function will be used each time the user wants to open/closed the list of options // It takes one parameter: // select : the DOM node with the list to toggle function toggleOptList(select) { // The list is kept from the control const optList = select.querySelector(".optList"); // We change the class of the list to show/hide it optList.classList.toggle("hidden"); } // This function will be used each time we need to highlight an option // It takes two parameters: // select : the DOM node with the `select` class containing the option to highlight // option : the DOM node with the `option` class to highlight function highlightOption(select, option) { // We get the list of all option available for our custom select element const optionList = select.querySelectorAll(".option"); // We remove the highlight from all options optionList.forEach((other) => { other.classList.remove("highlight"); }); // We highlight the right option option.classList.add("highlight"); } ``` You need these to handle the various states of custom control. Next, we bind these functions to the appropriate events: ```js // We handle the event binding when the document is loaded. window.addEventListener("load", () => { const selectList = document.querySelectorAll(".select"); // Each custom control needs to be initialized selectList.forEach((select) => { // as well as all its `option` elements const optionList = select.querySelectorAll(".option"); // Each time a user hovers their mouse over an option, we highlight the given option optionList.forEach((option) => { option.addEventListener("mouseover", () => { // Note: the `select` and `option` variable are closures // available in the scope of our function call. highlightOption(select, option); }); }); // Each times the user clicks on or taps a custom select element select.addEventListener("click", (event) => { // Note: the `select` variable is a closure // available in the scope of our function call. // We toggle the visibility of the list of options toggleOptList(select); }); // In case the control gains focus // The control gains the focus each time the user clicks on it or each time // they use the tabulation key to access the control select.addEventListener("focus", (event) => { // Note: the `select` and `selectList` variable are closures // available in the scope of our function call. // We activate the control activeSelect(select, selectList); }); // In case the control loses focus select.addEventListener("blur", (event) => { // Note: the `select` variable is a closure // available in the scope of our function call. // We deactivate the control deactivateSelect(select); }); // Loose focus if the user hits `esc` select.addEventListener("keyup", (event) => { // deactivate on keyup of `esc` if (event.key === "Escape") { deactivateSelect(select); } }); }); }); ``` At that point, our control will change state according to our design, but its value doesn't get updated yet. We'll handle that next. #### Live example Check out the full source code. ``` <form class="no-widget"> <select name="myFruit" tabindex="-1"> <option>Cherry</option> <option>Lemon</option> <option>Banana</option> <option>Strawberry</option> <option>Apple</option> </select> <div class="select" tabindex="0"> <span class="value">Cherry</span> <ul class="optList hidden"> <li class="option">Cherry</li> <li class="option">Lemon</li> <li class="option">Banana</li> <li class="option">Strawberry</li> <li class="option">Apple</li> </ul> </div> </form> ``` ``` .widget select, .no-widget .select { position: absolute; left: -5000em; height: 0; overflow: hidden; } .select { position: relative; display: inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline-color: transparent; } .select .optList { position: absolute; top: 100%; left: 0; } .select .optList.hidden { max-height: 0; visibility: hidden; } .select { font-size: 0.625em; /\* 10px \*/ font-family: Verdana, Arial, sans-serif; box-sizing: border-box; padding: 0.1em 2.5em 0.2em 0.5em; /\* 1px 25px 2px 5px \*/ width: 10em; /\* 100px \*/ border: 0.2em solid #000; /\* 2px \*/ border-radius: 0.4em; /\* 4px \*/ box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /\* 0 1px 2px \*/ background: #f0f0f0; background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display: inline-block; width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; vertical-align: top; } .select::after { content: "▼"; position: absolute; z-index: 1; height: 100%; width: 2em; /\* 20px \*/ top: 0; right: 0; padding-top: 0.1em; box-sizing: border-box; text-align: center; border-left: 0.2em solid #000; border-radius: 0 0.1em 0.1em 0; background-color: #000; color: #fff; } .select .optList { z-index: 2; list-style: none; margin: 0; padding: 0; background: #f0f0f0; border: 0.2em solid #000; border-top-width: 0.1em; border-radius: 0 0 0.4em 0.4em; box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%); box-sizing: border-box; min-width: 100%; max-height: 10em; /\* 100px \*/ overflow-y: auto; overflow-x: hidden; } .select .option { padding: 0.2em 0.3em; } .select .highlight { background: #000; color: #ffffff; } ``` ``` function deactivateSelect(select) { if (!select.classList.contains("active")) return; const optList = select.querySelector(".optList"); optList.classList.add("hidden"); select.classList.remove("active"); } function activeSelect(select, selectList) { if (select.classList.contains("active")) return; selectList.forEach(deactivateSelect); select.classList.add("active"); } function toggleOptList(select, show) { const optList = select.querySelector(".optList"); optList.classList.toggle("hidden"); } function highlightOption(select, option) { const optionList = select.querySelectorAll(".option"); optionList.forEach((other) => { other.classList.remove("highlight"); }); option.classList.add("highlight"); } window.addEventListener("load", () => { const form = document.querySelector("form"); form.classList.remove("no-widget"); form.classList.add("widget"); }); window.addEventListener("load", () => { const selectList = document.querySelectorAll(".select"); selectList.forEach((select) => { const optionList = select.querySelectorAll(".option"); optionList.forEach((option) => { option.addEventListener("mouseover", () => { highlightOption(select, option); }); }); select.addEventListener( "click", (event) => { toggleOptList(select); }, false, ); select.addEventListener("focus", (event) => { activeSelect(select, selectList); }); select.addEventListener("blur", (event) => { deactivateSelect(select); }); select.addEventListener("keyup", (event) => { if (event.key === "Escape") { deactivateSelect(select); } }); }); }); ``` ### Handling the control's value Now that our control is working, we have to add code to update its value according to user input and make it possible to send the value along with form data. The easiest way to do this is to use a native control under the hood. Such a control will keep track of the value with all the built-in controls provided by the browser, and the value will be sent as usual when a form is submitted. There's no point in reinventing the wheel when we can have all this done for us. As seen previously, we already use a native select control as a fallback for accessibility reasons; we can synchronize its value with that of our custom control: ```js // This function updates the displayed value and synchronizes it with the native control. // It takes two parameters: // select : the DOM node with the class `select` containing the value to update // index : the index of the value to be selected function updateValue(select, index) { // We need to get the native control for the given custom control // In our example, that native control is a sibling of the custom control const nativeWidget = select.previousElementSibling; // We also need to get the value placeholder of our custom control const value = select.querySelector(".value"); // And we need the whole list of options const optionList = select.querySelectorAll(".option"); // We set the selected index to the index of our choice nativeWidget.selectedIndex = index; // We update the value placeholder accordingly value.innerHTML = optionList[index].innerHTML; // And we highlight the corresponding option of our custom control highlightOption(select, optionList[index]); } // This function returns the current selected index in the native control // It takes one parameter: // select : the DOM node with the class `select` related to the native control function getIndex(select) { // We need to access the native control for the given custom control // In our example, that native control is a sibling of the custom control const nativeWidget = select.previousElementSibling; return nativeWidget.selectedIndex; } ``` With these two functions, we can bind the native controls to the custom ones: ```js // We handle event binding when the document is loaded. window.addEventListener("load", () => { const selectList = document.querySelectorAll(".select"); // Each custom control needs to be initialized selectList.forEach((select) => { const optionList = select.querySelectorAll(".option"); const selectedIndex = getIndex(select); // We make our custom control focusable select.tabIndex = 0; // We make the native control no longer focusable select.previousElementSibling.tabIndex = -1; // We make sure that the default selected value is correctly displayed updateValue(select, selectedIndex); // Each time a user clicks on an option, we update the value accordingly optionList.forEach((option, index) => { option.addEventListener("click", (event) => { updateValue(select, index); }); }); // Each time a user uses their keyboard on a focused control, we update the value accordingly select.addEventListener("keyup", (event) => { let index = getIndex(select); // When the user hits the Escape key, deactivate the custom control if (event.key === "Escape") { deactivateSelect(select); } // When the user hits the down arrow, we jump to the next option if (event.key === "ArrowDown" && index < optionList.length - 1) { index++; } // When the user hits the up arrow, we jump to the previous option if (event.key === "ArrowUp" && index > 0) { index--; } updateValue(select, index); }); }); }); ``` In the code above, it's worth noting the use of the `tabIndex` property. Using this property is necessary to ensure that the native control will never gain focus, and to make sure that our custom control gains focus when the user uses their keyboard or mouse. With that, we're done! #### Live example Check out the source code here. ``` <form class="no-widget"> <select name="myFruit"> <option>Cherry</option> <option>Lemon</option> <option>Banana</option> <option>Strawberry</option> <option>Apple</option> </select> <div class="select"> <span class="value">Cherry</span> <ul class="optList hidden"> <li class="option">Cherry</li> <li class="option">Lemon</li> <li class="option">Banana</li> <li class="option">Strawberry</li> <li class="option">Apple</li> </ul> </div> </form> ``` ``` .widget select, .no-widget .select { position: absolute; left: -5000em; height: 0; overflow: hidden; } .select { position: relative; display: inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline-color: transparent; } .select .optList { position: absolute; top: 100%; left: 0; } .select .optList.hidden { max-height: 0; visibility: hidden; } .select { font-size: 0.625em; /\* 10px \*/ font-family: Verdana, Arial, sans-serif; box-sizing: border-box; padding: 0.1em 2.5em 0.2em 0.5em; /\* 1px 25px 2px 5px \*/ width: 10em; /\* 100px \*/ border: 0.2em solid #000; /\* 2px \*/ border-radius: 0.4em; /\* 4px \*/ box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /\* 0 1px 2px \*/ background: #f0f0f0; background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display: inline-block; width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; vertical-align: top; } .select::after { content: "▼"; position: absolute; z-index: 1; height: 100%; width: 2em; /\* 20px \*/ top: 0; right: 0; padding-top: 0.1em; box-sizing: border-box; text-align: center; border-left: 0.2em solid #000; border-radius: 0 0.1em 0.1em 0; background-color: #000; color: #fff; } .select .optList { z-index: 2; list-style: none; margin: 0; padding: 0; background: #f0f0f0; border: 0.2em solid #000; border-top-width: 0.1em; border-radius: 0 0 0.4em 0.4em; box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%); box-sizing: border-box; min-width: 100%; max-height: 10em; /\* 100px \*/ overflow-y: auto; overflow-x: hidden; } .select .option { padding: 0.2em 0.3em; } .select .highlight { background: #000; color: #ffffff; } ``` ``` function deactivateSelect(select) { if (!select.classList.contains("active")) return; const optList = select.querySelector(".optList"); optList.classList.add("hidden"); select.classList.remove("active"); } function activeSelect(select, selectList) { if (select.classList.contains("active")) return; selectList.forEach(deactivateSelect); select.classList.add("active"); } function toggleOptList(select, show) { const optList = select.querySelector(".optList"); optList.classList.toggle("hidden"); } function highlightOption(select, option) { const optionList = select.querySelectorAll(".option"); optionList.forEach((other) => { other.classList.remove("highlight"); }); option.classList.add("highlight"); } function updateValue(select, index) { const nativeWidget = select.previousElementSibling; const value = select.querySelector(".value"); const optionList = select.querySelectorAll(".option"); nativeWidget.selectedIndex = index; value.innerHTML = optionList[index].innerHTML; highlightOption(select, optionList[index]); } function getIndex(select) { const nativeWidget = select.previousElementSibling; return nativeWidget.selectedIndex; } window.addEventListener("load", () => { const form = document.querySelector("form"); form.classList.remove("no-widget"); form.classList.add("widget"); }); window.addEventListener("load", () => { const selectList = document.querySelectorAll(".select"); selectList.forEach((select) => { const optionList = select.querySelectorAll(".option"); optionList.forEach((option) => { option.addEventListener("mouseover", () => { highlightOption(select, option); }); }); select.addEventListener("click", (event) => { toggleOptList(select); }); select.addEventListener("focus", (event) => { activeSelect(select, selectList); }); select.addEventListener("blur", (event) => { deactivateSelect(select); }); }); }); window.addEventListener("load", () => { const selectList = document.querySelectorAll(".select"); selectList.forEach((select) => { const optionList = select.querySelectorAll(".option"); const selectedIndex = getIndex(select); select.tabIndex = 0; select.previousElementSibling.tabIndex = -1; updateValue(select, selectedIndex); optionList.forEach((option, index) => { option.addEventListener("click", (event) => { updateValue(select, index); }); }); select.addEventListener("keyup", (event) => { let index = getIndex(select); if (event.key === "Escape") { deactivateSelect(select); } if (event.key === "ArrowDown" && index < optionList.length - 1) { index++; } if (event.key === "ArrowUp" && index > 0) { index--; } updateValue(select, index); }); }); }); ``` But wait a second, are we really done? Making it accessible -------------------- We have built something that works and though we're far from a fully-featured select box, it works nicely. But what we've done is nothing more than fiddle with the DOM. It has no real semantics, and even though it looks like a select box, from the browser's point of view it isn't one, so assistive technologies won't be able to understand it's a select box. In short, this pretty new select box isn't accessible! Fortunately, there is a solution and it's called ARIA. ARIA stands for "Accessible Rich Internet Application", and it's a W3C specification specifically designed for what we are doing here: making web applications and custom controls accessible. It's basically a set of attributes that extend HTML so that we can better describe roles, states, and properties as though the element we've just devised was the native element it tries to pass for. Using these attributes can be done by editing the HTML markup. We also update the ARIA attributes via JavaScript as the user updates their selected value. ### The `role` attribute The key attribute used by ARIA is the `role` attribute. The `role` attribute accepts a value that defines what an element is used for. Each role defines its own requirements and behaviors. In our example, we will use the `listbox` role. It's a "composite role", which means elements with that role expect to have children, each with a specific role (in this case, at least one child with the `option` role). It's also worth noting that ARIA defines roles that are applied by default to standard HTML markup. For example, the `<table>` element matches the role `grid`, and the `<ul>` element matches the role `list`. Because we use a `<ul>` element, we want to make sure the `listbox` role of our control will supersede the `list` role of the `<ul>` element. To that end, we will use the role `presentation`. This role is designed to let us indicate that an element has no special meaning, and is used solely to present information. We will apply it to our `<ul>` element. To support the `listbox` role, we just have to update our HTML like this: ```html <!-- We add the role="listbox" attribute to our top element --> <div class="select" role="listbox"> <span class="value">Cherry</span> <!-- We also add the role="presentation" to the ul element --> <ul class="optList" role="presentation"> <!-- And we add the role="option" attribute to all the li elements --> <li role="option" class="option">Cherry</li> <li role="option" class="option">Lemon</li> <li role="option" class="option">Banana</li> <li role="option" class="option">Strawberry</li> <li role="option" class="option">Apple</li> </ul> </div> ``` **Note:** Including both the `role` attribute and a `class` attribute is not necessary. Instead of using `.option` use the `[role="option"]` attribute selectors in your CSS. ### The `aria-selected` attribute Using the `role` attribute is not enough. ARIA also provides many states and property attributes. The more and better you use them, the better your control will be understood by assistive technologies. In our case, we will limit our usage to one attribute: `aria-selected`. The `aria-selected` attribute is used to mark which option is currently selected; this lets assistive technologies inform the user what the current selection is. We will use it dynamically with JavaScript to mark the selected option each time the user chooses one. To that end, we need to revise our `updateValue()` function: ```js function updateValue(select, index) { const nativeWidget = select.previousElementSibling; const value = select.querySelector(".value"); const optionList = select.querySelectorAll('[role="option"]'); // We make sure that all the options are not selected optionList.forEach((other) => { other.setAttribute("aria-selected", "false"); }); // We make sure the chosen option is selected optionList[index].setAttribute("aria-selected", "true"); nativeWidget.selectedIndex = index; value.innerHTML = optionList[index].innerHTML; highlightOption(select, optionList[index]); } ``` It might have seemed simpler to let a screen reader focus on the off-screen select and ignore our stylized one, but this is not an accessible solution. Screen readers are not limited to blind people; people with low vision and even perfect vision use them as well. For this reason, you can not have the screen reader focus on an off-screen element. Below is the final result of all these changes (you'll get a better feel for this by trying it with an assistive technology such as NVDA or VoiceOver). #### Live example Check out the full source code here. ``` <form class="no-widget"> <select name="myFruit"> <option>Cherry</option> <option>Lemon</option> <option>Banana</option> <option>Strawberry</option> <option>Apple</option> </select> <div class="select" role="listbox"> <span class="value">Cherry</span> <ul class="optList hidden" role="presentation"> <li class="option" role="option" aria-selected="true">Cherry</li> <li class="option" role="option">Lemon</li> <li class="option" role="option">Banana</li> <li class="option" role="option">Strawberry</li> <li class="option" role="option">Apple</li> </ul> </div> </form> ``` ``` .widget select, .no-widget .select { position: absolute; left: -5000em; height: 0; overflow: hidden; } .select { position: relative; display: inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline-color: transparent; } .select .optList { position: absolute; top: 100%; left: 0; } .select .optList.hidden { max-height: 0; visibility: hidden; } .select { font-size: 0.625em; /\* 10px \*/ font-family: Verdana, Arial, sans-serif; box-sizing: border-box; padding: 0.1em 2.5em 0.2em 0.5em; /\* 1px 25px 2px 5px \*/ width: 10em; /\* 100px \*/ border: 0.2em solid #000; /\* 2px \*/ border-radius: 0.4em; /\* 4px \*/ box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /\* 0 1px 2px \*/ background: #f0f0f0; background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display: inline-block; width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; vertical-align: top; } .select::after { content: "▼"; position: absolute; z-index: 1; height: 100%; width: 2em; /\* 20px \*/ top: 0; right: 0; padding-top: 0.1em; box-sizing: border-box; text-align: center; border-left: 0.2em solid #000; border-radius: 0 0.1em 0.1em 0; background-color: #000; color: #fff; } .select .optList { z-index: 2; list-style: none; margin: 0; padding: 0; background: #f0f0f0; border: 0.2em solid #000; border-top-width: 0.1em; border-radius: 0 0 0.4em 0.4em; box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%); box-sizing: border-box; min-width: 100%; max-height: 10em; /\* 100px \*/ overflow-y: auto; overflow-x: hidden; } .select .option { padding: 0.2em 0.3em; } .select .highlight { background: #000; color: #ffffff; } ``` ``` function deactivateSelect(select) { if (!select.classList.contains("active")) return; const optList = select.querySelector(".optList"); optList.classList.add("hidden"); select.classList.remove("active"); } function activeSelect(select, selectList) { if (select.classList.contains("active")) return; selectList.forEach(deactivateSelect); select.classList.add("active"); } function toggleOptList(select, show) { const optList = select.querySelector(".optList"); optList.classList.toggle("hidden"); } function highlightOption(select, option) { const optionList = select.querySelectorAll(".option"); optionList.forEach((other) => { other.classList.remove("highlight"); }); option.classList.add("highlight"); } function updateValue(select, index) { const nativeWidget = select.previousElementSibling; const value = select.querySelector(".value"); const optionList = select.querySelectorAll(".option"); optionList.forEach((other) => { other.setAttribute("aria-selected", "false"); }); optionList[index].setAttribute("aria-selected", "true"); nativeWidget.selectedIndex = index; value.innerHTML = optionList[index].innerHTML; highlightOption(select, optionList[index]); } function getIndex(select) { const nativeWidget = select.previousElementSibling; return nativeWidget.selectedIndex; } window.addEventListener("load", () => { const form = document.querySelector("form"); form.classList.remove("no-widget"); form.classList.add("widget"); }); window.addEventListener("load", () => { const selectList = document.querySelectorAll(".select"); selectList.forEach((select) => { const optionList = select.querySelectorAll(".option"); const selectedIndex = getIndex(select); select.tabIndex = 0; select.previousElementSibling.tabIndex = -1; updateValue(select, selectedIndex); optionList.forEach((option, index) => { option.addEventListener("mouseover", () => { highlightOption(select, option); }); option.addEventListener("click", (event) => { updateValue(select, index); }); }); select.addEventListener("click", (event) => { toggleOptList(select); }); select.addEventListener("focus", (event) => { activeSelect(select, selectList); }); select.addEventListener("blur", (event) => { deactivateSelect(select); }); select.addEventListener("keyup", (event) => { let index = getIndex(select); if (event.key === "Escape") { deactivateSelect(select); } if (event.key === "ArrowDown" && index < optionList.length - 1) { index++; } if (event.key === "ArrowUp" && index > 0) { index--; } updateValue(select, index); }); }); }); ``` If you want to move forward, the code in this example needs some improvement before it becomes generic and reusable. This is an exercise you can try to perform. Two hints to help you in this: the first argument for all our functions is the same, which means those functions need the same context. Building an object to share that context would be wise. An alternative approach: Using radio buttons -------------------------------------------- In the above example, we reinvented a `<select>` element using non-semantic HTML, CSS, and JavaScript. This select was selecting one option from a limited number of options, which is the same functionality of a same-named group of radio buttons. We could therefore reinvent this using radio buttons instead; let's look at this option. We can start with a completely semantic, accessible, unordered list of radio buttons with an associated `<label>`, labeling the entire group with a semantically appropriate `<fieldset>` and `<legend>` pair. ```html <fieldset> <legend>Pick a fruit</legend> <ul class="styledSelect"> <li> <input type="radio" name="fruit" value="Cherry" id="fruitCherry" checked /> <label for="fruitCherry">Cherry</label> </li> <li> <input type="radio" name="fruit" value="Lemon" id="fruitLemon" /> <label for="fruitLemon">Lemon</label> </li> <li> <input type="radio" name="fruit" value="Banana" id="fruitBanana" /> <label for="fruitBanana">Banana</label> </li> <li> <input type="radio" name="fruit" value="Strawberry" id="fruitStrawberry" /> <label for="fruitStrawberry">Strawberry</label> </li> <li> <input type="radio" name="fruit" value="Apple" id="fruitApple" /> <label for="fruitApple">Apple</label> </li> </ul> </fieldset> ``` We'll do a little styling of the radio button list (not the legend/fieldset) to make it look somewhat like the earlier example, just to show that it can be done: ```css .styledSelect { display: inline-block; padding: 0; } .styledSelect li { list-style-type: none; padding: 0; display: flex; } .styledSelect [type="radio"] { position: absolute; left: -100vw; top: -100vh; } .styledSelect label { margin: 0; line-height: 2; padding: 0 0 0 4px; } .styledSelect:not(:focus-within) input:not(:checked) + label { height: 0; outline-color: transparent; overflow: hidden; } .styledSelect:not(:focus-within) input:checked + label { border: 0.2em solid #000; border-radius: 0.4em; box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); } .styledSelect:not(:focus-within) input:checked + label::after { content: "▼"; background: black; float: right; color: white; padding: 0 4px; margin: 0 -4px 0 4px; } .styledSelect:focus-within { border: 0.2em solid #000; border-radius: 0.4em; box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); } .styledSelect:focus-within input:checked + label { background-color: #333; color: #fff; width: 100%; } ``` With no JavaScript, and just a little bit of CSS, we can style the list of radio buttons to display only the checked item. When the focus is within the `<ul>` in the `<fieldset>`, the list opens up, and the up and down (and left and right) arrows work to select the previous and next items. Try it out: This works, to some extent, without JavaScript. We've created a similar control to our custom control, that works even if the JavaScript fails. Looks like a great solution, right? Well, not 100%. It does work with the keyboard, but not as expected with a mouse click. It likely makes more sense to use web standards as the basis for custom controls instead of relying on frameworks to create elements with no native semantics. However, our control doesn't have the same functionality that a `<select>` has natively. On the plus side, this control is fully accessible to a screen reader and fully navigable via the keyboard. However, this control isn't a `<select>` replacement. There is functionality that differs and/or is missing. For example, all four arrows navigate through the options, but clicking the down arrow when the user is on the last button takes them to the first button; it doesn't stop at the top and bottom of the option list like a `<select>` does. We'll leave adding this missing functionality as a reader exercise. Conclusion ---------- We have seen all the basics of building a custom form control, but as you can see it's not trivial to do. Before creating your own customized control, consider whether HTML provides alternative elements that can be used to adequately support your requirements. If you do need to create a custom control, it is often easier to rely on third-party libraries instead of building your own. But, if you do create your own, modify existing elements, or use a framework to implement a pre-baked control, remember that creating a usable and accessible form control is more complicated than it looks. Here are a few libraries you should consider before coding your own: * jQuery UI * AXE accessible custom select dropdowns * msDropDown If you do create alternative controls via radio buttons, your own JavaScript, or with a 3rd party library, ensure it is accessible and feature-proof; that is, it needs to be able to work better with a variety of browsers whose compatibility with the Web standards they use vary. Have fun! See also -------- ### Learning path * Your first HTML form * How to structure an HTML form * The native form controls * HTML5 input types * Additional form controls * UI pseudo-classes * Styling HTML forms * Form data validation * Sending form data ### Advanced Topics * Sending forms through JavaScript * **How to build custom form controls** * HTML forms in legacy browsers * Advanced styling for HTML forms * Property compatibility table for form controls
Example - Learn web development
Example ======= This the example for a basic payment form for the article How to structure an HTML form. A payment form -------------- ### HTML ```html <form method="post"> <h1>Payment form</h1> <p> Required fields are followed by <strong><span aria-label="required">*</span></strong>. </p> <section> <h2>Contact information</h2> <fieldset> <legend>Title</legend> <ul> <li> <label for="title\_1"> <input type="radio" id="title\_1" name="title" value="A" /> Ace </label> </li> <li> <label for="title\_2"> <input type="radio" id="title\_2" name="title" value="K" /> King </label> </li> <li> <label for="title\_3"> <input type="radio" id="title\_3" name="title" value="Q" /> Queen </label> </li> </ul> </fieldset> <p> <label for="name"> <span>Name: </span> <strong><span aria-label="required">*</span></strong> </label> <input type="text" id="name" name="username" required /> </p> <p> <label for="mail"> <span>Email: </span> <strong><span aria-label="required">*</span></strong> </label> <input type="email" id="mail" name="usermail" required /> </p> <p> <label for="pwd"> <span>Password: </span> <strong><span aria-label="required">*</span></strong> </label> <input type="password" id="pwd" name="password" required /> </p> </section> <section> <h2>Payment information</h2> <p> <label for="card"> <span>Card type:</span> </label> <select id="card" name="usercard"> <option value="visa">Visa</option> <option value="mc">Mastercard</option> <option value="amex">American Express</option> </select> </p> <p> <label for="number"> <span>Card number:</span> <strong><span aria-label="required">*</span></strong> </label> <input type="tel" id="number" name="cardnumber" /> </p> <p> <label for="expiration"> <span>Expiration date:</span> <strong><span aria-label="required">*</span></strong> </label> <input type="text" id="expiration" required="true" placeholder="MM/YY" pattern="^(0[1-9]|1[0-2])\/([0-9]{2})$" /> </p> </section> <section> <p><button type="submit">Validate the payment</button></p> </section> </form> ``` ### CSS ```css h1 { margin-top: 0; } ul { margin: 0; padding: 0; list-style: none; } form { margin: 0 auto; width: 400px; padding: 1em; border: 1px solid #ccc; border-radius: 1em; } div + div { margin-top: 1em; } label span { display: inline-block; text-align: right; } input, textarea { font: 1em sans-serif; width: 250px; box-sizing: border-box; border: 1px solid #999; } input[type="checkbox"], input[type="radio"] { width: auto; border: none; } input:focus, textarea:focus { border-color: #000; } textarea { vertical-align: top; height: 5em; resize: vertical; } fieldset { width: 250px; box-sizing: border-box; border: 1px solid #999; } button { margin: 20px 0 0 0; } label { position: relative; display: inline-block; } p label { width: 100%; } label em { position: absolute; right: 5px; top: 20px; } ``` ### Result
Example 3 - Learn web development
Example 3 ========= This is the third example that explain how to build custom form widgets. Change states ------------- ### HTML ```html <form class="no-widget"> <select name="myFruit" tabindex="-1"> <option>Cherry</option> <option>Lemon</option> <option>Banana</option> <option>Strawberry</option> <option>Apple</option> </select> <div class="select" tabindex="0"> <span class="value">Cherry</span> <ul class="optList hidden"> <li class="option">Cherry</li> <li class="option">Lemon</li> <li class="option">Banana</li> <li class="option">Strawberry</li> <li class="option">Apple</li> </ul> </div> </form> ``` ### CSS ```css .widget select, .no-widget .select { position: absolute; left: -5000em; height: 0; overflow: hidden; } /\* --------------- \*/ /\* Required Styles \*/ /\* --------------- \*/ .select { position: relative; display: inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline-color: transparent; } .select .optList { position: absolute; top: 100%; left: 0; } .select .optList.hidden { max-height: 0; visibility: hidden; } /\* ------------ \*/ /\* Fancy Styles \*/ /\* ------------ \*/ .select { font-size: 0.625em; /\* 10px \*/ font-family: Verdana, Arial, sans-serif; box-sizing: border-box; padding: 0.1em 2.5em 0.2em 0.5em; /\* 1px 25px 2px 5px \*/ width: 10em; /\* 100px \*/ border: 0.2em solid #000; /\* 2px \*/ border-radius: 0.4em; /\* 4px \*/ box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /\* 0 1px 2px \*/ background: #f0f0f0; background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display: inline-block; width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; vertical-align: top; } .select::after { content: "▼"; position: absolute; z-index: 1; height: 100%; width: 2em; /\* 20px \*/ top: 0; right: 0; padding-top: 0.1em; box-sizing: border-box; text-align: center; border-left: 0.2em solid #000; border-radius: 0 0.1em 0.1em 0; background-color: #000; color: #fff; } .select .optList { z-index: 2; list-style: none; margin: 0; padding: 0; background: #f0f0f0; border: 0.2em solid #000; border-top-width: 0.1em; border-radius: 0 0 0.4em 0.4em; box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%); box-sizing: border-box; min-width: 100%; max-height: 10em; /\* 100px \*/ overflow-y: auto; overflow-x: hidden; } .select .option { padding: 0.2em 0.3em; } .select .highlight { background: #000; color: #ffffff; } ``` ### JavaScript ```js // -------------------- // // Function definitions // // -------------------- // function deactivateSelect(select) { if (!select.classList.contains("active")) return; const optList = select.querySelector(".optList"); optList.classList.add("hidden"); select.classList.remove("active"); } function activeSelect(select, selectList) { if (select.classList.contains("active")) return; selectList.forEach(deactivateSelect); select.classList.add("active"); } function toggleOptList(select, show) { const optList = select.querySelector(".optList"); optList.classList.toggle("hidden"); } function highlightOption(select, option) { const optionList = select.querySelectorAll(".option"); optionList.forEach((other) => { other.classList.remove("highlight"); }); option.classList.add("highlight"); } // ------------- // // Event binding // // ------------- // window.addEventListener("load", () => { const form = document.querySelector("form"); form.classList.remove("no-widget"); form.classList.add("widget"); }); window.addEventListener("load", () => { const selectList = document.querySelectorAll(".select"); selectList.forEach((select) => { const optionList = select.querySelectorAll(".option"); optionList.forEach((option) => { option.addEventListener("mouseover", () => { highlightOption(select, option); }); }); select.addEventListener( "click", (event) => { toggleOptList(select); }, false, ); select.addEventListener("focus", (event) => { activeSelect(select, selectList); }); select.addEventListener("blur", (event) => { deactivateSelect(select); }); select.addEventListener("keyup", (event) => { if (event.key === "Escape") { deactivateSelect(select); } }); }); }); ``` ### Result
Example 2 - Learn web development
Example 2 ========= This is the second example that explain how to build custom form widgets. JS -- ### HTML ```html <form class="no-widget"> <select name="myFruit"> <option>Cherry</option> <option>Lemon</option> <option>Banana</option> <option>Strawberry</option> <option>Apple</option> </select> <div class="select"> <span class="value">Cherry</span> <ul class="optList hidden"> <li class="option">Cherry</li> <li class="option">Lemon</li> <li class="option">Banana</li> <li class="option">Strawberry</li> <li class="option">Apple</li> </ul> </div> </form> ``` ### CSS ```css .widget select, .no-widget .select { position: absolute; left: -5000em; height: 0; overflow: hidden; } /\* --------------- \*/ /\* Required Styles \*/ /\* --------------- \*/ .select { position: relative; display: inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline: none; } .select .optList { position: absolute; top: 100%; left: 0; } .select .optList.hidden { max-height: 0; visibility: hidden; } /\* ------------ \*/ /\* Fancy Styles \*/ /\* ------------ \*/ .select { font-size: 0.625em; /\* 10px \*/ font-family: Verdana, Arial, sans-serif; box-sizing: border-box; padding: 0.1em 2.5em 0.2em 0.5em; /\* 1px 25px 2px 5px \*/ width: 10em; /\* 100px \*/ border: 0.2em solid #000; /\* 2px \*/ border-radius: 0.4em; /\* 4px \*/ box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /\* 0 1px 2px \*/ background: #f0f0f0; background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display: inline-block; width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; vertical-align: top; } .select::after { content: "▼"; position: absolute; z-index: 1; height: 100%; width: 2em; /\* 20px \*/ top: 0; right: 0; padding-top: 0.1em; box-sizing: border-box; text-align: center; border-left: 0.2em solid #000; border-radius: 0 0.1em 0.1em 0; background-color: #000; color: #fff; } .select .optList { z-index: 2; list-style: none; margin: 0; padding: 0; background: #f0f0f0; border: 0.2em solid #000; border-top-width: 0.1em; border-radius: 0 0 0.4em 0.4em; box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%); box-sizing: border-box; min-width: 100%; max-height: 10em; /\* 100px \*/ overflow-y: auto; overflow-x: hidden; } .select .option { padding: 0.2em 0.3em; } .select .highlight { background: #000; color: #ffffff; } ``` ### JavaScript ```js window.addEventListener("load", () => { const form = document.querySelector("form"); form.classList.remove("no-widget"); form.classList.add("widget"); }); ``` ### Result No JS ----- ### HTML ```html <form class="no-widget"> <select name="myFruit"> <option>Cherry</option> <option>Lemon</option> <option>Banana</option> <option>Strawberry</option> <option>Apple</option> </select> <div class="select"> <span class="value">Cherry</span> <ul class="optList hidden"> <li class="option">Cherry</li> <li class="option">Lemon</li> <li class="option">Banana</li> <li class="option">Strawberry</li> <li class="option">Apple</li> </ul> </div> </form> ``` ### CSS ```css .widget select, .no-widget .select { position: absolute; left: -5000em; height: 0; overflow: hidden; } ``` ### Result
Example 4 - Learn web development
Example 4 ========= This is the fourth example that explain how to build custom form widgets. Change states ------------- ### HTML ```html <form class="no-widget"> <select name="myFruit"> <option>Cherry</option> <option>Lemon</option> <option>Banana</option> <option>Strawberry</option> <option>Apple</option> </select> <div class="select"> <span class="value">Cherry</span> <ul class="optList hidden"> <li class="option">Cherry</li> <li class="option">Lemon</li> <li class="option">Banana</li> <li class="option">Strawberry</li> <li class="option">Apple</li> </ul> </div> </form> ``` ### CSS ```css .widget select, .no-widget .select { position: absolute; left: -5000em; height: 0; overflow: hidden; } /\* --------------- \*/ /\* Required Styles \*/ /\* --------------- \*/ .select { position: relative; display: inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline-color: transparent; } .select .optList { position: absolute; top: 100%; left: 0; } .select .optList.hidden { max-height: 0; visibility: hidden; } /\* ------------ \*/ /\* Fancy Styles \*/ /\* ------------ \*/ .select { font-size: 0.625em; /\* 10px \*/ font-family: Verdana, Arial, sans-serif; box-sizing: border-box; padding: 0.1em 2.5em 0.2em 0.5em; /\* 1px 25px 2px 5px \*/ width: 10em; /\* 100px \*/ border: 0.2em solid #000; /\* 2px \*/ border-radius: 0.4em; /\* 4px \*/ box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /\* 0 1px 2px \*/ background: #f0f0f0; background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display: inline-block; width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; vertical-align: top; } .select::after { content: "▼"; position: absolute; z-index: 1; height: 100%; width: 2em; /\* 20px \*/ top: 0; right: 0; padding-top: 0.1em; box-sizing: border-box; text-align: center; border-left: 0.2em solid #000; border-radius: 0 0.1em 0.1em 0; background-color: #000; color: #fff; } .select .optList { z-index: 2; list-style: none; margin: 0; padding: 0; background: #f0f0f0; border: 0.2em solid #000; border-top-width: 0.1em; border-radius: 0 0 0.4em 0.4em; box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%); box-sizing: border-box; min-width: 100%; max-height: 10em; /\* 100px \*/ overflow-y: auto; overflow-x: hidden; } .select .option { padding: 0.2em 0.3em; } .select .highlight { background: #000; color: #ffffff; } ``` ### JavaScript ```js // -------------------- // // Function definitions // // -------------------- // function deactivateSelect(select) { if (!select.classList.contains("active")) return; const optList = select.querySelector(".optList"); optList.classList.add("hidden"); select.classList.remove("active"); } function activeSelect(select, selectList) { if (select.classList.contains("active")) return; selectList.forEach(deactivateSelect); select.classList.add("active"); } function toggleOptList(select, show) { const optList = select.querySelector(".optList"); optList.classList.toggle("hidden"); } function highlightOption(select, option) { const optionList = select.querySelectorAll(".option"); optionList.forEach((other) => { other.classList.remove("highlight"); }); option.classList.add("highlight"); } function updateValue(select, index) { const nativeWidget = select.previousElementSibling; const value = select.querySelector(".value"); const optionList = select.querySelectorAll(".option"); nativeWidget.selectedIndex = index; value.innerHTML = optionList[index].innerHTML; highlightOption(select, optionList[index]); } function getIndex(select) { const nativeWidget = select.previousElementSibling; return nativeWidget.selectedIndex; } // ------------- // // Event binding // // ------------- // window.addEventListener("load", () => { const form = document.querySelector("form"); form.classList.remove("no-widget"); form.classList.add("widget"); }); window.addEventListener("load", () => { const selectList = document.querySelectorAll(".select"); selectList.forEach((select) => { const optionList = select.querySelectorAll(".option"); optionList.forEach((option) => { option.addEventListener("mouseover", () => { highlightOption(select, option); }); }); select.addEventListener("click", (event) => { toggleOptList(select); }); select.addEventListener("focus", (event) => { activeSelect(select, selectList); }); select.addEventListener("blur", (event) => { deactivateSelect(select); }); }); }); window.addEventListener("load", () => { const selectList = document.querySelectorAll(".select"); selectList.forEach((select) => { const optionList = select.querySelectorAll(".option"); const selectedIndex = getIndex(select); select.tabIndex = 0; select.previousElementSibling.tabIndex = -1; updateValue(select, selectedIndex); optionList.forEach((option, index) => { option.addEventListener("click", (event) => { updateValue(select, index); }); }); select.addEventListener("keyup", (event) => { let index = getIndex(select); if (event.key === "Escape") { deactivateSelect(select); } if (event.key === "ArrowDown" && index < optionList.length - 1) { index++; } if (event.key === "ArrowUp" && index > 0) { index--; } updateValue(select, index); }); }); }); ``` ### Result
Example 1 - Learn web development
Example 1 ========= This is the first example of code that explains how to build a custom form widget. Basic state ----------- ### HTML ```html <div class="select"> <span class="value">Cherry</span> <ul class="optList hidden"> <li class="option">Cherry</li> <li class="option">Lemon</li> <li class="option">Banana</li> <li class="option">Strawberry</li> <li class="option">Apple</li> </ul> </div> ``` ### CSS ```css /\* --------------- \*/ /\* Required Styles \*/ /\* --------------- \*/ .select { position: relative; display: inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline-color: transparent; } .select .optList { position: absolute; top: 100%; left: 0; } .select .optList.hidden { max-height: 0; visibility: hidden; } /\* ------------ \*/ /\* Fancy Styles \*/ /\* ------------ \*/ .select { font-size: 0.625em; /\* 10px \*/ font-family: Verdana, Arial, sans-serif; box-sizing: border-box; padding: 0.1em 2.5em 0.2em 0.5em; /\* 1px 25px 2px 5px \*/ width: 10em; /\* 100px \*/ border: 0.2em solid #000; /\* 2px \*/ border-radius: 0.4em; /\* 4px \*/ box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /\* 0 1px 2px \*/ background: #f0f0f0; background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display: inline-block; width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; vertical-align: top; } .select::after { content: "▼"; position: absolute; z-index: 1; height: 100%; width: 2em; /\* 20px \*/ top: 0; right: 0; padding-top: 0.1em; box-sizing: border-box; text-align: center; border-left: 0.2em solid #000; border-radius: 0 0.1em 0.1em 0; background-color: #000; color: #fff; } .select .optList { z-index: 2; list-style: none; margin: 0; padding: 0; background: #f0f0f0; border: 0.2em solid #000; border-top-width: 0.1em; border-radius: 0 0 0.4em 0.4em; box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%); box-sizing: border-box; min-width: 100%; max-height: 10em; /\* 100px \*/ overflow-y: auto; overflow-x: hidden; } .select .option { padding: 0.2em 0.3em; } .select .highlight { background: #000; color: #ffffff; } ``` ### Result for basic state Active state ------------ ### HTML ```html <div class="select active"> <span class="value">Cherry</span> <ul class="optList hidden"> <li class="option">Cherry</li> <li class="option">Lemon</li> <li class="option">Banana</li> <li class="option">Strawberry</li> <li class="option">Apple</li> </ul> </div> ``` ### CSS ```css /\* --------------- \*/ /\* Required Styles \*/ /\* --------------- \*/ .select { position: relative; display: inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline-color: transparent; } .select .optList { position: absolute; top: 100%; left: 0; } .select .optList.hidden { max-height: 0; visibility: hidden; } /\* ------------ \*/ /\* Fancy Styles \*/ /\* ------------ \*/ .select { font-size: 0.625em; /\* 10px \*/ font-family: Verdana, Arial, sans-serif; box-sizing: border-box; padding: 0.1em 2.5em 0.2em 0.5em; /\* 1px 25px 2px 5px \*/ width: 10em; /\* 100px \*/ border: 0.2em solid #000; /\* 2px \*/ border-radius: 0.4em; /\* 4px \*/ box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /\* 0 1px 2px \*/ background: #f0f0f0; background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display: inline-block; width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; vertical-align: top; } .select::after { content: "▼"; position: absolute; z-index: 1; height: 100%; width: 2em; /\* 20px \*/ top: 0; right: 0; padding-top: 0.1em; box-sizing: border-box; text-align: center; border-left: 0.2em solid #000; border-radius: 0 0.1em 0.1em 0; background-color: #000; color: #fff; } .select .optList { z-index: 2; list-style: none; margin: 0; padding: 0; background: #f0f0f0; border: 0.2em solid #000; border-top-width: 0.1em; border-radius: 0 0 0.4em 0.4em; box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%); box-sizing: border-box; min-width: 100%; max-height: 10em; /\* 100px \*/ overflow-y: auto; overflow-x: hidden; } .select .option { padding: 0.2em 0.3em; } .select .highlight { background: #000; color: #ffffff; } ``` ### Result for active state Open state ---------- ### HTML ```html <div class="select active"> <span class="value">Cherry</span> <ul class="optList"> <li class="option highlight">Cherry</li> <li class="option">Lemon</li> <li class="option">Banana</li> <li class="option">Strawberry</li> <li class="option">Apple</li> </ul> </div> ``` ### CSS ```css /\* --------------- \*/ /\* Required Styles \*/ /\* --------------- \*/ .select { position: relative; display: inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline-color: transparent; } .select .optList { position: absolute; top: 100%; left: 0; } .select .optList.hidden { max-height: 0; visibility: hidden; } /\* ------------ \*/ /\* Fancy Styles \*/ /\* ------------ \*/ .select { font-size: 0.625em; /\* 10px \*/ font-family: Verdana, Arial, sans-serif; box-sizing: border-box; padding: 0.1em 2.5em 0.2em 0.5em; /\* 1px 25px 2px 5px \*/ width: 10em; /\* 100px \*/ border: 0.2em solid #000; /\* 2px \*/ border-radius: 0.4em; /\* 4px \*/ box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /\* 0 1px 2px \*/ background: #f0f0f0; background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display: inline-block; width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; vertical-align: top; } .select::after { content: "▼"; position: absolute; z-index: 1; height: 100%; width: 2em; /\* 20px \*/ top: 0; right: 0; padding-top: 0.1em; box-sizing: border-box; text-align: center; border-left: 0.2em solid #000; border-radius: 0 0.1em 0.1em 0; background-color: #000; color: #fff; } .select .optList { z-index: 2; list-style: none; margin: 0; padding: 0; background: #f0f0f0; border: 0.2em solid #000; border-top-width: 0.1em; border-radius: 0 0 0.4em 0.4em; box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%); box-sizing: border-box; min-width: 100%; max-height: 10em; /\* 100px \*/ overflow-y: auto; overflow-x: hidden; } .select .option { padding: 0.2em 0.3em; } .select .highlight { background: #000; color: #fff; } ``` ### Result for open state
Example 5 - Learn web development
Example 5 ========= This is the last example that explain how to build custom form widgets. Change states ------------- ### HTML ```html <form class="no-widget"> <select name="myFruit"> <option>Cherry</option> <option>Lemon</option> <option>Banana</option> <option>Strawberry</option> <option>Apple</option> </select> <div class="select" role="listbox"> <span class="value">Cherry</span> <ul class="optList hidden" role="presentation"> <li class="option" role="option" aria-selected="true">Cherry</li> <li class="option" role="option">Lemon</li> <li class="option" role="option">Banana</li> <li class="option" role="option">Strawberry</li> <li class="option" role="option">Apple</li> </ul> </div> </form> ``` ### CSS ```css .widget select, .no-widget .select { position: absolute; left: -5000em; height: 0; overflow: hidden; } /\* --------------- \*/ /\* Required Styles \*/ /\* --------------- \*/ .select { position: relative; display: inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline-color: transparent; } .select .optList { position: absolute; top: 100%; left: 0; } .select .optList.hidden { max-height: 0; visibility: hidden; } /\* ------------ \*/ /\* Fancy Styles \*/ /\* ------------ \*/ .select { font-size: 0.625em; /\* 10px \*/ font-family: Verdana, Arial, sans-serif; box-sizing: border-box; padding: 0.1em 2.5em 0.2em 0.5em; /\* 1px 25px 2px 5px \*/ width: 10em; /\* 100px \*/ border: 0.2em solid #000; /\* 2px \*/ border-radius: 0.4em; /\* 4px \*/ box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /\* 0 1px 2px \*/ background: #f0f0f0; background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display: inline-block; width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; vertical-align: top; } .select::after { content: "▼"; position: absolute; z-index: 1; height: 100%; width: 2em; /\* 20px \*/ top: 0; right: 0; padding-top: 0.1em; box-sizing: border-box; text-align: center; border-left: 0.2em solid #000; border-radius: 0 0.1em 0.1em 0; background-color: #000; color: #fff; } .select .optList { z-index: 2; list-style: none; margin: 0; padding: 0; background: #f0f0f0; border: 0.2em solid #000; border-top-width: 0.1em; border-radius: 0 0 0.4em 0.4em; box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%); box-sizing: border-box; min-width: 100%; max-height: 10em; /\* 100px \*/ overflow-y: auto; overflow-x: hidden; } .select .option { padding: 0.2em 0.3em; } .select .highlight { background: #000; color: #ffffff; } ``` ### JavaScript ```js // -------------------- // // Function definitions // // -------------------- // function deactivateSelect(select) { if (!select.classList.contains("active")) return; const optList = select.querySelector(".optList"); optList.classList.add("hidden"); select.classList.remove("active"); } function activeSelect(select, selectList) { if (select.classList.contains("active")) return; selectList.forEach(deactivateSelect); select.classList.add("active"); } function toggleOptList(select, show) { const optList = select.querySelector(".optList"); optList.classList.toggle("hidden"); } function highlightOption(select, option) { const optionList = select.querySelectorAll(".option"); optionList.forEach((other) => { other.classList.remove("highlight"); }); option.classList.add("highlight"); } function updateValue(select, index) { const nativeWidget = select.previousElementSibling; const value = select.querySelector(".value"); const optionList = select.querySelectorAll(".option"); optionList.forEach((other) => { other.setAttribute("aria-selected", "false"); }); optionList[index].setAttribute("aria-selected", "true"); nativeWidget.selectedIndex = index; value.innerHTML = optionList[index].innerHTML; highlightOption(select, optionList[index]); } function getIndex(select) { const nativeWidget = select.previousElementSibling; return nativeWidget.selectedIndex; } // ------------- // // Event binding // // ------------- // window.addEventListener("load", () => { const form = document.querySelector("form"); form.classList.remove("no-widget"); form.classList.add("widget"); }); window.addEventListener("load", () => { const selectList = document.querySelectorAll(".select"); selectList.forEach((select) => { const optionList = select.querySelectorAll(".option"); const selectedIndex = getIndex(select); select.tabIndex = 0; select.previousElementSibling.tabIndex = -1; updateValue(select, selectedIndex); optionList.forEach((option, index) => { option.addEventListener("mouseover", () => { highlightOption(select, option); }); option.addEventListener("click", (event) => { updateValue(select, index); }); }); select.addEventListener("click", (event) => { toggleOptList(select); }); select.addEventListener("focus", (event) => { activeSelect(select, selectList); }); select.addEventListener("blur", (event) => { deactivateSelect(select); }); select.addEventListener("keyup", (event) => { let index = getIndex(select); if (event.key === "Escape") { deactivateSelect(select); } if (event.key === "ArrowDown" && index < optionList.length - 1) { index++; } if (event.key === "ArrowUp" && index > 0) { index--; } updateValue(select, index); }); }); }); ``` ### Result
Tools for game development - Game development
Tools for game development ========================== On this page, you can find links to our game development tools articles, which eventually aim to cover frameworks, compilers, and debugging tools. asm.js asm.js is a very limited subset of the JavaScript language, which can be significantly optimized and run in an ahead-of-time (AOT) compiling engine for much faster performance than your typical JavaScript performance. This is, of course, great for games. Emscripten An LLVM to JavaScript compiler; with Emscripten, you can compile C++ and other languages that can compile to LLVM bytecode into high-performance JavaScript. This is an excellent tool for porting applications to the Web! There is a useful Emscripten tutorial available on the wiki. Firefox Profiler The Firefox Profiler lets you profile your code to help figure out where your performance issues are so that you can make your game run at top speed. Toolchain for developing and debugging games How does this differ from normal web app debugging? What specialist tools are available? A lot of this is going to be covered by Will in tools, but here we should provide a kind of practical toolchain tutorial for debugging games, with links to Will's stuff: * Basic tools overview * Shader editor * Performance tools (still in production, estimated early 2014)
Publishing games - Game development
Publishing games ================ HTML games have a huge advantage over native in terms of publishing and distribution — you have the freedom of distribution, promotion and monetization of your game on the Web, rather than each version being locked into a single store controlled by one company. You can benefit from the web being truly multiplatform. This series of articles looks at the options you have when you want to publish and distribute your game, and earn something out of it while you wait for it to become famous. Game distribution ----------------- So you've followed a tutorial or two and created an HTML game — that's great! Game distribution provides all you need to know about the ways you can distribute your newly created game into the wild — including hosting it yourself online, submitting it to open marketplaces, and submitting it to closed ones like Google Play or the iOS App Store. Game promotion -------------- Developing and finishing the game is not enough. You have to let the world know that you have made something interesting available, which people will enjoy playing. There are many Game promotion techniques — many of them free — so even if you're struggling to make a living as an indie dev with zero budget you can still do a lot to let people know about your great new game. Promoting the game helps a lot in monetizing it later on too, so it's important to do it effectively. Game monetization ----------------- When you spend your time building, publishing and promoting your game, you will at some point consider earning money out of it. Game monetization is essential to anyone who considers their game development work a serious endeavour on the path to becoming an independent game developer able to make a living, so read on and see what your options are. The technology is mature enough; it's just a matter of choosing the right approach.
Introduction to game development for the Web - Game development
Introduction to game development for the Web ============================================ The modern web has quickly become a viable platform not only for creating stunning, high quality games, but also for distributing those games. The range of games that can be created is on par with desktop and native OS counterparts. With modern Web technologies and a recent browser, it's entirely possible to make stunning, top-notch games for the Web. And we're not talking about simple card games or multiplayer social games that have in the olden days been done using Flash®. We're talking about 3D action shooters, RPGs, and more. Thanks to massive performance improvements in JavaScript just-in-time compiler technology and new APIs, you can build games that run in the browser (or on HTML5-powered devices) without making compromises. The HTML game platform ---------------------- You can truly think of the Web as a better target platform for your game. As we like to say, "the Web is the platform." Let's take a look at the core of the Web platform: | Function | Technology | | --- | --- | | **Audio** | Web Audio API | | **Graphics** | WebGL (OpenGL ES 2.0) | | **Input** | Touch events, Gamepad API, device sensors, WebRTC, Full Screen API, Pointer Lock API | | **Language** | JavaScript (or C/C++ using Emscripten to compile to JavaScript) | | **Networking** | WebRTC and/or WebSockets | | **Storage** | IndexedDB or the "cloud" | | **Web** | HTML, CSS, SVG (and much more!) | The business case ----------------- As a game developer, whether you're an individual or a large game studio, you want to know why it makes sense to target the Web with your next game project. Let's look at how the Web can help you. 1. The reach of the Web is enormous; it's everywhere. Games built with HTML work on smartphones, tablets, PCs and Smart TVs. 2. Marketing and discoverability are improved. You're not limited to promoting your app on someone else's app store. Instead, you can advertise and promote your game all over the Web as well as other media, taking advantage of the Web's inherent linkability and shareability to reach new customers. 3. You have control where it matters: Payments. You don't have to hand over 30% of your revenues to someone else just because your game is in their ecosystem. Instead, charge what you want and use whatever payment processing service you like. 4. Again with more control, you can update your game whenever you want. No waiting breathlessly for approval while someone hidden within another company decides whether your critical bug fix will ship today or tomorrow. 5. Control your analytics! Instead of relying on someone else to make all the decisions about what analytics you need, you can collect your own — or choose the third party that you like the best — to gather information about your sales and your game's reach. 6. You get to manage your customer relationship more closely, in your own way. No more having customer feedback filtered through an app store's limited mechanisms. Engage with your customers the way you want to, without a middleman. 7. Your players can play your game anywhere, anytime. Because the Web is ubiquitous, your customers can check their game's status on their phones, tablets, their home laptops, their work desktops, or anything else. Web technologies for game developers ------------------------------------ For the tech folks, let's dig into the APIs the Web brings to the table that cater to game developers. Here's a thorough list to give you a taste of what the Web can do for you: Fetch API Send and receive any kind of data you want from a Web server like downloading new game levels and artwork to transmitting non-real-time game status information back and forth. Full Screen API This simple API lets your game take over the entire screen, thereby immersing the player in action. Gamepad API If you want your users to be able to use gamepads or other game controllers to work your game, you'll need this API. HTML and CSS Together, these two technologies let you build, style, and lay out your game's user interface. Part of HTML is the `<canvas>` element, which provides one way to do 2D graphics. HTML audio The `<audio>` element lets you easily play simple sound effects and music. If your needs are more involved, check out the Web Audio API for real audio processing power! IndexedDB A powerful data storage API for maintaining user data on their own computer or device. A great way to save game state and other information locally so it doesn't have to be downloaded every time it's needed. Also useful to help make your game playable even when the user isn't connected to the Web (such as when they're stuck on an airplane for hours on end). JavaScript JavaScript, the programming language used on the Web, is blazing fast in modern browsers and getting faster all the time. Use its power to write the code for your game, or look at using technologies like Emscripten or Asm.js to easily port your existing games. Pointer Lock API The Pointer Lock API lets you lock the mouse or other pointing device within your game's interface so that instead of absolute cursor positioning you receive coordinate deltas that give you more precise measurements of what the user is doing, and prevent the user from accidentally sending their input somewhere else, thereby missing important action. SVG (Scalable Vector Graphics) Lets you build vector graphics that scale smoothly regardless of the size or resolution of the user's display. Typed Arrays JavaScript typed arrays give you access to raw binary data from within JavaScript; this lets you manipulate GL textures, game data, or anything else, even if it's not in a native JavaScript format. Web Audio API This API for controlling the playback, synthesis, and manipulation of audio from JavaScript code lets you create awesome sound effects as well as play and manipulate music in real time. WebGL Lets you create high-performance, hardware-accelerated 3D (and 2D) graphics from Web content. This is a Web-supported implementation of OpenGL ES 2.0. WebRTC The WebRTC (Real-Time Communications) API gives you the power to control audio and video data, including teleconferencing and transmitting other application data back and forth between two users. Want your players to be able to talk to each other while blowing up monsters? This is the API for you. WebSockets The WebSocket API lets you connect your app or site to a server to transmit data back and forth in real-time. Perfect for multiplayer gaming action, chat services, and so forth. Web Workers Workers give you the ability to spawn background threads running their own JavaScript code, to take advantage of modern, multicore processors.
Anatomy of a video game - Game development
Anatomy of a video game ======================= This article looks at the anatomy and workflow of the average video game from a technical point of view, in terms of how the main loop should run. It helps beginners to modern game development understand what is required when building a game and how web standards like JavaScript lend themselves as tools. Experienced game programmers who are new to web development could also benefit, too. Present, accept, interpret, calculate, repeat --------------------------------------------- The goal of every video game is to **present** the user(s) with a situation, **accept** their input, **interpret** those signals into actions, and **calculate** a new situation resulting from those acts. Games are constantly looping through these stages, over and over, until some end condition occurs (such as winning, losing, or exiting to go to bed). Not surprisingly, this pattern corresponds to how a game engine is programmed. The specifics depend on the game. Some games drive this cycle by user input. Imagine that you are developing a *"find the differences between these two similar pictures"*-type game. These games **present** two images to the user; they **accept** their click (or touch); they **interpret** the input as a success, failure, pause, menu interaction, etc.; finally, they **calculate** an updated scene resulting from that input. The game loop is advanced by the user's input and sleeps until they provide it. This is more of a turn-based approach that doesn't demand a constant update every frame, only when the player reacts. Other games demand control over each of the smallest possible individual timeslices. The same principles as above apply with a slight twist: each frame of animation progresses the cycle and any change in user input is caught at the first available turn. This once-per-frame model is implemented in something called a **main loop**. If your game loops based on time then this will be its authority that your simulations will adhere to. But it might not need per-frame control. Your game loop might be similar to the *find the differences* example and base itself on input events. It might require both input and simulated time. It might even loop based on something else entirely. Modern JavaScript — as described in the next sections — thankfully makes it easy to develop an efficient, execute-once-per-frame main loop. Of course, your game will only be as optimized as you make it. If something looks like it should be attached to a more infrequent event then it is often a good idea to break it out of the main loop (but not always). Building a main loop in JavaScript ---------------------------------- JavaScript works best with events and callback functions. Modern browsers strive to call methods right as they are needed and idle (or do their other tasks) in the gaps. It is an excellent idea to attach your code to the moments that are appropriate for them. Think about whether your function really needs to be called on a strict interval of time, every frame, or only after something else happens. Being more specific with the browser about when your function needs to be called allows the browser to optimize when it is called. Also, it will probably make your job easier. Some code needs to be run frame-by-frame so why attach that function to anything other than the browser's redraw schedule? On the Web, `window.requestAnimationFrame()` will be the foundation of most well-programmed per-frame main loops. A callback function must be passed in to it when it is called. That callback function will be executed at a suitable time before the next repaint. Here is an example of a simple main loop: ```js window.main = () => { window.requestAnimationFrame(main); // Whatever your main loop needs to do }; main(); // Start the cycle ``` **Note:** In each of the `main()` methods discussed here, we schedule a new `requestAnimationFrame` before performing our loop contents. That is not by accident and it is considered best practice. Calling the next `requestAnimationFrame` early ensures the browser receives it on time to plan accordingly even if your current frame misses its VSync window. The above chunk of code has two statements. The first statement creates a function as a global variable called `main()`. This function does some work and also tells the browser to call itself next frame with `window.requestAnimationFrame()`. The second statement calls the `main()` function, defined in the first statement. Because `main()` is called once in the second statement and every call of it places itself in the queue of things to do next frame, `main()` is synchronized to your frame rate. Of course this loop is not perfect. Before we discuss ways to change it, let us discuss what it already does well. Timing the main loop to when the browser paints to the display allows you to run your loop as frequently as the browser wants to paint. You are given control over each frame of animation. It is also very simple because `main()` is the only function getting looped. A First-Person Shooter (or a similar game) presents a new scene once every frame. You cannot really get more smooth and responsive than that. But do not immediately assume animations require frame-by-frame control. Simple animations can be easily performed, even GPU-accelerated, with CSS animations and other tools included in the browser. There are a lot of them and they will make your life easier. Building a better main loop in JavaScript ----------------------------------------- There are two obvious issues with our previous main loop: `main()` pollutes the `window` object (where all global variables are stored) and the example code did not leave us with a way to *stop* the loop unless the whole tab is closed or refreshed. For the first issue, if you want the main loop to just run and you do not need easy (direct) access to it, you could create it as an Immediately-Invoked Function Expression (IIFE). ```js /\* \* Starting with the semicolon is in case whatever line of code above this example \* relied on automatic semicolon insertion (ASI). The browser could accidentally \* think this whole example continues from the previous line. The leading semicolon \* marks the beginning of our new line if the previous one was not empty or terminated. \*/ ;(() => { function main() { window.requestAnimationFrame(main); // Your main loop contents } main(); // Start the cycle })(); ``` When the browser comes across this IIFE, it will define your main loop and immediately queue it for the next frame. It will not be attached to any object and `main` (or `main()` for methods) will be a valid unused name in the rest of the application, free to be defined as something else. **Note:** In practice, it is more common to prevent the next `requestAnimationFrame()` with an if-statement, rather than calling `cancelAnimationFrame()`. For the second issue, stopping the main loop, you will need to cancel the call to `main()` with `window.cancelAnimationFrame()`. You will need to pass `cancelAnimationFrame()` the ID token given by `requestAnimationFrame()` when it was last called. Let us assume that your game's functions and variables are built on a namespace that you called `MyGame`. Expanding our last example, the main loop would now look like: ```js /\* \* Starting with the semicolon is in case whatever line of code above this example \* relied on automatic semicolon insertion (ASI). The browser could accidentally \* think this whole example continues from the previous line. The leading semicolon \* marks the beginning of our new line if the previous one was not empty or terminated. \* \* Let us also assume that MyGame is previously defined. \*/ ;(() => { function main() { MyGame.stopMain = window.requestAnimationFrame(main); // Your main loop contents } main(); // Start the cycle })(); ``` We now have a variable declared in our `MyGame` namespace, which we call `stopMain`, that contains the ID returned from our main loop's most recent call to `requestAnimationFrame()`. At any point, we can stop the main loop by telling the browser to cancel the request that corresponds to our token. ```js window.cancelAnimationFrame(MyGame.stopMain); ``` The key to programming a main loop, in JavaScript, is to attach it to whatever event should be driving your action and pay attention to how the different systems involved interplay. You may have multiple components driven by multiple different types of events. This feels like unnecessary complexity but it might just be good optimization (not necessarily, of course). The problem is that you are not programming a typical main loop. In JavaScript, you are using the browser's main loop and you are trying to do so effectively. Building a more optimized main loop in JavaScript ------------------------------------------------- Ultimately, in JavaScript, the browser is running its own main loop and your code exists in some of its stages. The above sections describe main loops which try not to wrestle away control from the browser. These main methods attach themselves to `window.requestAnimationFrame()`, which asks the browser for control over the upcoming frame. It is up to the browser how to relate these requests to their main loop. The W3C spec for requestAnimationFrame does not really define exactly when the browsers must perform the requestAnimationFrame callbacks. This can be a benefit because it leaves browser vendors free to experiment with the solutions that they feel are best and tweak it over time. Modern versions of Firefox and Google Chrome (and probably others) *attempt* to connect `requestAnimationFrame` callbacks to their main thread at the very beginning of a frame's timeslice. The browser's main thread thus *tries* to look like the following: 1. Start a new frame (while the previous frame is handled by the display). 2. Go through the list of `requestAnimationFrame` callbacks and invoke them. 3. Perform garbage collection and other per-frame tasks when the above callbacks stop controlling the main thread. 4. Sleep (unless an event interrupts the browser's nap) until the monitor is ready for your image (VSync) and repeat. You can think about developing realtime applications as having a budget of time to do work. All of the above steps must take place every 16-and-a-half milliseconds to keep up with a 60 Hz display. Browsers invoke your code as early as possible to give it maximum computation time. Your main thread will often start workloads that are not even on the main thread (such as rasterization or shaders in WebGL). Long calculations can be performed on a Web Worker or a GPU at the same time as the browser uses its main thread to manage garbage collection, its other tasks, or handle asynchronous events. While we are on the topic of budgeting time, many web browsers have a tool called *High Resolution Time*. The `Date` object is no longer the recognized method for timing events because it is very imprecise and can be modified by the system clock. High Resolution Time, on the other hand, counts the number of milliseconds since `navigationStart` (when the previous document is unloaded). This value is returned as a decimal number accurate to a thousandth of a millisecond. It is known as a `DOMHighResTimeStamp` but, for all intents and purposes, consider it a floating point number. **Note:** Systems (hardware or software) that are not capable of microsecond accuracy are allowed to provide millisecond accuracy as a minimum. They should provide 0.001ms accuracy if they are capable of it, however. This value is not too useful alone, since it is relative to a fairly uninteresting event, but it can be subtracted from another timestamp to accurately and precisely determine how much time elapsed between those two points. To acquire one of these timestamps, you can call `window.performance.now()` and store the result as a variable. ```js const tNow = window.performance.now(); ``` Back to the topic of the main loop. You will often want to know when your main function was invoked. Because this is common, `window.requestAnimationFrame()` always provides a `DOMHighResTimeStamp` to callbacks as an argument when they are executed. This leads to another enhancement to our previous main loops. ```js /\* \* Starting with the semicolon is in case whatever line of code above this example \* relied on automatic semicolon insertion (ASI). The browser could accidentally \* think this whole example continues from the previous line. The leading semicolon \* marks the beginning of our new line if the previous one was not empty or terminated. \* \* Let us also assume that MyGame is previously defined. \*/ ;(() => { function main(tFrame) { MyGame.stopMain = window.requestAnimationFrame(main); // Your main loop contents // tFrame, from "function main(tFrame)", is now a DOMHighResTimeStamp provided by rAF. } main(); // Start the cycle })(); ``` Several other optimizations are possible and it really depends on what your game attempts to accomplish. Your game genre will obviously make a difference but it could even be more subtle than that. You could draw every pixel individually on a canvas or you could layer DOM elements (including multiple WebGL canvases with transparent backgrounds if you want) into a complex hierarchy. Each of these paths will lead to different opportunities and constraints. It is decision… time -------------------- You will need to make hard decisions about your main loop: how to simulate the accurate progress of time. If you demand per-frame control then you will need to determine how frequently your game will update and draw. You might even want update and draw to occur at different rates. You will also need to consider how gracefully your game will fail if the user's system cannot keep up with the workload. Let us start by assuming that you will handle user input and update the game state every time you draw. We will branch out later. **Note:** Changing how your main loop deals with time is a debugging nightmare, everywhere. Think about your needs carefully before working on your main loop. ### What most browser games should look like If your game can hit the maximum refresh rate of any hardware you support then your job is fairly easy. You can update, render, and then do nothing until VSync. ```js /\* \* Starting with the semicolon is in case whatever line of code above this example \* relied on automatic semicolon insertion (ASI). The browser could accidentally \* think this whole example continues from the previous line. The leading semicolon \* marks the beginning of our new line if the previous one was not empty or terminated. \* \* Let us also assume that MyGame is previously defined. \*/ ;(() => { function main(tFrame) { MyGame.stopMain = window.requestAnimationFrame(main); update(tFrame); // Call your update method. In our case, we give it rAF's timestamp. render(); } main(); // Start the cycle })(); ``` If the maximum refresh rate cannot be reached, quality settings could be adjusted to stay under your time budget. The most famous example of this concept is the game from id Software, RAGE. This game removed control from the user in order to keep its calculation time at roughly 16ms (or roughly 60fps). If computation took too long then rendered resolution would decrease, textures and other assets would fail to load or draw, and so forth. This (non-web) case study made a few assumptions and tradeoffs: * Each frame of animation accounts for user input. * No frame needs to be extrapolated (guessed) because each draw has its own update. * Simulation systems can basically assume that each full update is ~16ms apart. * Giving the user control over quality settings would be a nightmare. * Different monitors input at different rates: 30 FPS, 75 FPS, 100 FPS, 120 FPS, 144 FPS, etc. * Systems that are unable to keep up with 60 FPS lose visual quality to keep the game running at optimal speed (eventually it outright fails, if quality becomes too low.) ### Other ways to handle variable refresh rate needs Other methods of tackling the problem exist. One common technique is to update the simulation at a constant frequency and then draw as much (or as little) of the actual frames as possible. The update method can continue looping without care about what the user sees. The draw method can view the last update and when it happened. Since draw knows when it represents, and the simulation time for the last update, it can predict a plausible frame to draw for the user. It does not matter whether this is more frequent than the official update loop (or even less frequent). The update method sets checkpoints and, as frequently as the system allows, the render method draws instants of time around them. There are many ways to separate the update method in web standards: * Draw on `requestAnimationFrame` and update on a `setInterval()` or `setTimeout()`. + This uses processor time even when unfocused or minimized, hogs the main thread, and is probably an artifact of traditional game loops (but it is simple.) * Draw on `requestAnimationFrame` and update on a `setInterval` or `setTimeout` in a Web Worker. + This is the same as above, except update does not hog the main thread (nor does the main thread hog it). This is a more complex solution, and might be too much overhead for simple updates. * Draw on `requestAnimationFrame` and use it to poke a Web Worker containing the update method with the number of ticks to compute, if any. + This sleeps until `requestAnimationFrame` is called and does not pollute the main thread, plus you are not relying on old-fashioned methods. Again, this is a bit more complex than the previous two options, and *starting* each update will be blocked until the browser decides to fire rAF callbacks. Each of these methods have similar tradeoffs: * Users can skip rendering frames or interpolate extra ones depending on their performance. * You can count on all users updating non-cosmetic variables at the same constant frequency minus hiccups. * Much more complicated to program than the basic loops we saw earlier. * User input is completely ignored until the next update (even if the user has a fast device). * The mandatory interpolation has a performance penalty. A separate update and draw method could look like the following example. For the sake of demonstration, the example is based on the third bullet point, just without using Web Workers for readability (and, let's be honest, writability). **Warning:** This example, specifically, is in need of technical review. ```js /\* \* Starting with the semicolon is in case whatever line of code above this example \* relied on automatic semicolon insertion (ASI). The browser could accidentally \* think this whole example continues from the previous line. The leading semicolon \* marks the beginning of our new line if the previous one was not empty or terminated. \* \* Let us also assume that MyGame is previously defined. \* \* MyGame.lastRender keeps track of the last provided requestAnimationFrame timestamp. \* MyGame.lastTick keeps track of the last update time. Always increments by tickLength. \* MyGame.tickLength is how frequently the game state updates. It is 20 Hz (50ms) here. \* \* timeSinceTick is the time between requestAnimationFrame callback and last update. \* numTicks is how many updates should have happened between these two rendered frames. \* \* render() is passed tFrame because it is assumed that the render method will calculate \* how long it has been since the most recently passed update tick for \* extrapolation (purely cosmetic for fast devices). It draws the scene. \* \* update() calculates the game state as of a given point in time. It should always \* increment by tickLength. It is the authority for game state. It is passed \* the DOMHighResTimeStamp for the time it represents (which, again, is always \* last update + MyGame.tickLength unless a pause feature is added, etc.) \* \* setInitialState() Performs whatever tasks are leftover before the main loop must run. \* It is just a generic example function that you might have added. \*/ ;(() => { function main(tFrame) { MyGame.stopMain = window.requestAnimationFrame(main); const nextTick = MyGame.lastTick + MyGame.tickLength; let numTicks = 0; // If tFrame < nextTick then 0 ticks need to be updated (0 is default for numTicks). // If tFrame = nextTick then 1 tick needs to be updated (and so forth). // Note: As we mention in summary, you should keep track of how large numTicks is. // If it is large, then either your game was asleep, or the machine cannot keep up. if (tFrame > nextTick) { const timeSinceTick = tFrame - MyGame.lastTick; numTicks = Math.floor(timeSinceTick / MyGame.tickLength); } queueUpdates(numTicks); render(tFrame); MyGame.lastRender = tFrame; } function queueUpdates(numTicks) { for (let i = 0; i < numTicks; i++) { MyGame.lastTick += MyGame.tickLength; // Now lastTick is this tick. update(MyGame.lastTick); } } MyGame.lastTick = performance.now(); MyGame.lastRender = MyGame.lastTick; // Pretend the first draw was on first update. MyGame.tickLength = 50; // This sets your simulation to run at 20Hz (50ms) setInitialState(); main(performance.now()); // Start the cycle })(); ``` Another alternative is to do certain things less often. If a portion of your update loop is difficult to compute but insensitive to time, you might consider scaling back its frequency and, ideally, spreading it out into chunks throughout that lengthened period. An implicit example of this was found over at The Artillery Blog for Artillery Games, where they adjust their rate of garbage generation to optimize garbage collection. Obviously, cleaning up resources is not time sensitive (especially if tidying is more disruptive than the garbage itself). This may also apply to some of your own tasks. Those are good candidates to throttle when available resources become a concern. Summary ------- I want to be clear that any of the above, or none of them, could be best for your game. The correct decision entirely depends on the trade-offs that you are willing (and unwilling) to make. The concern is mostly with switching to another option. Fortunately, I do not have any experience with this, but I have heard it is an excruciating game of Whack-a-Mole. An important thing to remember for managed platforms, like the web, is that your loop may stop execution for significant periods of time. This could occur when the user unselects your tab and the browser sleeps (or slows) its `requestAnimationFrame` callback interval. You have many ways to deal with this situation and this could depend on whether your game is single player or multiplayer. Some choices are: * Consider the gap "a pause" and skip the time. + You can probably see how this is problematic for most multiplayer games. * You can simulate the gap to catch up. + This can be a problem for long drops and/or complex updates. * You can recover the game state from a peer or the server. + This is ineffective if your peers or server are out-of-date too, or they don't exist because the game is single player and doesn't have a server. Once your main loop has been developed and you have decided on a set of assumptions and tradeoffs which suit your game, it is now just a matter of using your decisions to calculate any applicable physics, AI, sounds, network synchronization, and whatever else your game may require.
Introduction to HTML Game Development - Game development
Introduction to HTML Game Development ===================================== Advantages ---------- 1. Games built with HTML work on smartphones, tablets, PCs and Smart TVs. 2. Advertise and promote your game all over the Web as well as other media. 3. Payments. Charge what you want and use whatever payment processing service you like. 4. Update your game whenever you want. 5. Collect your own analytics! 6. Connect with your customers more closely, 7. Players can play the game anywhere, anytime. Web Technologies ---------------- Web technologies in game development and their function| **Function** | **Technology** | | --- | --- | | **Audio** | Web Audio API | | **Graphics** | WebGL (OpenGL ES 2.0) | | **Input** | Touch events, Gamepad API, device sensors, WebRTC, Full Screen API, Pointer Lock API | | **Language** | JavaScript (or C/C++ using Emscripten to compile to JavaScript) | | **Networking** | WebRTC and/or WebSockets | | **Storage** | IndexedDB or the "cloud" | | **Web** | HTML, CSS, SVG (and much more!) | Fetch API Send and receive any kind of data you want from a Web server like downloading new game levels and artwork to transmitting non-real-time game status information back and forth. Full Screen API Full screen gameplay. Gamepad API Use gamepads or other game controllers. HTML and CSS Build, style, and lay out your game's user interface. HTML audio Easily play simple sound effects and music. IndexedDB Store user data on their own computer or device. JavaScript Fast web programming language to write the code for your game. To easily port your existing games Emscripten or Asm.js Pointer Lock API Lock the mouse or other pointing device within your game's interface. SVG (Scalable Vector Graphics) Build vector graphics that scale smoothly regardless of the size or resolution of the user's display. Typed Arrays Access raw binary data from within JavaScript; Manipulate GL textures, game data, or anything else. Web Audio API Control the playback, synthesis, and manipulation of audio in real time. WebGL Create high-performance, hardware-accelerated 3D (and 2D) graphics. OpenGL ES 2.0. WebRTC Real-Time Communications to control audio and video data, including teleconferencing and transmitting other application data back and forth between two users like chat. WebSockets Connect your app or site to a server to transmit data back and forth in real-time. Perfect for multiplayer gaming action, chat services, and so forth. Web Workers Spawn background threads running their own JavaScript code for multicore processors.
Tutorials - Game development
Tutorials ========= This page contains multiple tutorial series that highlight different workflows for effectively creating different types of web games. 2D breakout game using pure JavaScript In this step-by-step tutorial you'll implement a simple breakout clone using pure JavaScript. Along the way you will learn the basics of using the `<canvas>` element to implement fundamental game mechanics like rendering and moving images, collision detection, control mechanisms, and winning and losing states. 2D breakout game using Phaser In this step-by-step tutorial you'll implement the same breakout clone as the previous tutorial series, except that this time you'll do it using the Phaser HTML game framework. This idea here is to teach some of the fundamentals (and advantages) of working with frameworks, along with fundamental game mechanics. 2D maze game with device orientation This tutorial shows how to create a 2D maze game using HTML, incorporating fundamentals such as collision detection and sprite placement on a `<canvas>`. This is a mobile game that uses the Device Orientation and Vibration **APIs** to enhance the gameplay and is built using the Phaser framework. 2D platform game with Phaser This tutorial series shows how to create a simple platform game using Phaser, covering fundamentals such as sprites, collisions, physics, collectables, and more.
Techniques for game development - Game development
Techniques for game development =============================== This page lists essential core techniques for anyone wanting to develop games using open web technologies. Using async scripts for asm.js Especially when creating medium to large-sized games, async scripts are an essential technique to take advantage of, so that your game's JavaScript can be compiled off the main thread and be cached for future game running, resulting in a significant performance improvement for your users. This article explains how. Optimizing startup performance How to make sure your game starts up quickly, smoothly, and without appearing to lock up the user's browser or device. Using WebRTC peer-to-peer data channels In addition to providing support for audio and video communication, WebRTC lets you set up peer-to-peer data channels to exchange text or binary data actively between your players. This article explains what this can do for you, and shows how to use libraries that make this easy. Audio for Web Games Audio is an important part of any game — it adds feedback and atmosphere. Web-based audio is maturing fast, but there are still many browser differences to negotiate. This article provides a detailed guide to implementing audio for web games, looking at what works currently across as wide a range of platforms as possible. 2D collision detection A concise introduction to collision detection in 2D games. Tilemaps Tiles are a very popular technique in 2D games for building the game world. These articles provide an introduction to tilemaps and how to implement them with the Canvas API.
Game promotion - Game development
Game promotion ============== Developing and publishing your game is not enough. You have to let the world know that you have something interesting available that people will enjoy playing. There are many ways to promote your game — most of them being free, so even if you're struggling to make a living as an indie dev with zero budget you can still do a lot to let people know about your great new game. Promoting the game helps a lot when monetizing it later on too, so it's important to do it correctly. Competitions ------------ Taking part in competitions will not only level up your gamedev skills and let you meet new devs to befriend and learn from — and it will also get you involved in the community. If you make a good game for a competition and win some prizes in the process your game will automatically be promoted by the organizers and other attendees. You'll be rich and famous, or so they say. Many great games get started as a quick, sloppy demo submitted to a competition. If both the idea and the execution are good enough, you will succeed. Plus competitions generally require games to follow a mandatory theme, so you can get creative around a theme if you are stuck for ideas. Website and blog ---------------- You should definitely create your own website containing all the information about your games, so people can see what you've worked on. The more information you can include the better — you should include screenshots, description, trailer, press kit, requirements, available platforms, support details and more. You'll get bonus points for allowing your users to directly play your games online — at least in demo form. Also, you should do some work on SEO to allow people to find your games more easily. You should also blog about everything related to your gamedev activities. Write about your development process, nasty bugs you encounter, funny stories, lessons learned, and the ups and downs of being a game developer. Continually publishing information about your games will help educate others, increase your reputation in the community, and further improve SEO. A further option is to publish monthly reports that summarize all your progress — it helps you see what you've accomplished throughout the month and what's still left to do, and it keeps reminding people that your game is coming out soon — building buzz is always good. While you can create your website from scratch, there are also tools that can help make the process easier. ManaKeep is a website builder made for indie game developers and provides a great starting point to create your website. Presskit() is a press kit builder that helps you create a press page to share with the media. Social media ------------ Your social media presence is very important — hashtags can help find friends and allow you to engage with the community and help other devs in need. Honesty is key and you should be authentic, because nobody likes boring press releases or pushy advertisements. When the time comes, your community will help you spread the word about your shiny new game! Keep an eye on gamers who stream on YouTube and Twitch, engage with Twitter circles and be active on forums such as HTML5GameDevs.com. Share your news and answer questions so that people will value what you're doing and will know that you're trustworthy. Remember to not be too pushy when it comes to telling everyone about your games — you're not a walking advertisement. Grow your audience by talking to them, sharing tips, offering discounts, giving away prizes in competitions, or just complaining at the weather or buggy browser you have to deal with. Be generous, be yourself and be there for others, and you'll be treated with respect. Game portals ------------ Using game portals is mostly concerned with monetization, but if you're not planning to sell licenses to allow people to purchase your game and are intending to implement adverts or in-app purchases instead, promoting your game across free portals can be effective. There are a number of different game portals to which you can send your games for publication. Some portals have their own APIs that allow you to authorize users, save their progress and process in-app purchases. You can also sell a full version of the game from inside your browser demo version, which will be a great move considering high competition, some developers even manage to make full browser versions. Most portals offer revenue share deals or will buy nonexclusive license. Free portals offer traffic, but only the best ones are popular enough to generate revenues from advertisements on in-app purchases. On the other hand they are a perfect tool to make games visible to a broader audience if you have no budget and limited time. Press ----- You can try and reach the press about your game, but bear in mind that they get a tonne of requests like this every single day, so be humble and patient if they don't answer right away, and be polite when talking to them. Be sure to check first if they are dealing with specific genres of games or platforms, so you don't send them something that is not relevant to them in the first place. If you're honest with your approach and your game is good, then you've got more of a chance of success. If you want to learn more about the etiquette of contacting the press you should definitely check out How To Contact Press - a great guide from Pixel Prospector. Tutorials --------- It's good to share your knowledge with other devs — after all you probably learned a thing or two from online articles, so you take the time to pay that knowledge forward. Talking or writing about something you achieved or problems you overcame is something people would be interested it. And you can use your own game as an example, especially in a tutorial when you're showing how to do something you've implemented already. That way everyone benefits — people learn new skills, your game gets promoted, and if you're lucky you can even get paid for writing a tutorial if it's good enough. There are portals like Tuts+ Game Development which will be more than happy if you write for them - they pay for the content, but not all topic ideas will be accepted. When writing a tutorial remember to focus on delivering something valuable to the reader. They want to learn something - offer your expertise and use your game as a case study. Focus on one aspect and try to explain it throughout and in detail. Also remember to follow up discussion in comments if people have any questions. If portals you contact are not interested in your content because you don't have any experience yet, try writing tutorials and publish them on your own blog first. It's the easiest way to train your writing skills on your own. Events ------ If you've gone through all the options listed above you can still find new, creative ways to promote your game — events are another good example. Attending events, both local and global, gives you the ability to meet your fans face to face, as well as other members of the development community. Value the fact that they spent their time seeing you. ### Conferences There are many conferences where you can give a talk explaining some technical difficulties you overcame, or how you implemented specific APIs; again — use your games as examples for that. It's important to focus on the knowledge part and tone down the marketing — devs are sensitive on this matter and you may end up with an angry crowd if you just try to sell them something. ### Fairs The other event-related option is fairs (or expos) — at such an event you can get a booth among other devs and promote your game to all the attendees passing by. If you do so, try to be unique and original, so you easily stand from the crowd. Do it the right way and everybody will be talking about you and your game. Having a booth gives you the possibility to interact with your fans directly — besides the promotion part you can also test new builds of your game on regular people and fix any bugs (or incorporate any feedback) they uncover. You can't imagine what people may come up with when playing your game, and what obvious issues you've missed while spending hours polishing it. Promo codes ----------- If you're selling the game, then create the ability to distribute promo codes allowing people to access your game for free (or at least a demo or time-limited version), and send them all over the place — to press, YouTubers, as competition prizes, etc. If the game reaches certain people you'll get a free advert to thousands of players. It can boost interest in your game more than anything else if you get lucky. Fostering the community ----------------------- You can help community grow and promote yourself and your games at the same time. Sending out weekly newsletters and organizing online competitions or local meetups will show others that you're passionate about what you do and that they can rely on you. Then when you need any help they will be there for you. Summary ------- Any way of promoting your game is good. You have a lot of options to chose from with most of them being free, so it's only about your enthusiasm and available time. Sometimes you have to spend more time promoting a game than actually developing it. Remember that it's no use to have the best game in the world if no one knows it exists. Now lets get on with that monetization part, and earn something for a living.
Game monetization - Game development
Game monetization ================= When you've spent your time building a game, distributing it and promoting it you should consider earning some money out of it. If your work is a serious endeavour on the path to becoming an independent game developer able to make a living, read on and see what your options are. The technology is mature enough; now it's just about choosing the right approach. Paid games ---------- The first, most obvious choice that may come to your mind might be selling the games the way it is done for huge AAA titles — with a fixed, up front price. Even though the digital market is key and you don't need to print covers and put your game in a physical store in boxes, to earn decent money on selling your games for a fixed price you have to invest your time and money in marketing. Only the best games will break even or earn more than they cost to make, and you still need a lot of luck for that. How much you charge for your game depends on the market, quality of your game and a lot of other small factors. An arcade iOS title can be sold for 0.99 USD, but a longer RPG-style desktop game on Steam can cost 20 USD; both prices are OK. You have to follow the market and do your own research — learning from your mistakes quickly is important. In-app purchases ---------------- Instead of having people pay for your game up front, you can offer a free game with in-app purchases (IAPs.) In this case the game can be acquired without spending a dime — give the game to the players, but offer in-game currency, bonuses or benefits for real money. Specific examples can include bonus levels, better weapons or spells, or refilling the energy needed to play. Designing a good IAP system is an art of its own. Remember that you need thousands of downloads of your game to make IAPs effective — only a small fraction of players will actually pay for IAPs. How small? It varies, but around one person in every thousand is about average. The more people that play your game, the higher the chance someone will pay, so your earnings heavily depend on your promotion activities. ### Freemium Games that feature IAPs are often referred to a **freemium** — a freemium game can be acquired and played for free, but you can pay for extra (premium) features, virtual goods or other benefits. The word itself acquired negative connotations after big companies focused on creating games, the main purpose of which was to get as much money from the players as possible instead of delivering a fun experience. The worst cases were when you could use real money to pay for getting advantages over other players, or when they restricted access to the next stages of the game unless the players paid. The term "pay to win" was coined and this approach is disliked by many players and devs. If you want to implement IAPs try to add value to the game with something players will enjoy instead of taking it out and then charging for it. ### Add-ons and DLCs Add-ons and downloadable content are a good way to provide extra value to an already released game, but remember that you'll have to offer decent, entertaining content to attract people to buy it. A totally new set of levels with new characters, weapons and story is a good material for DLC, but to have enough sales the game itself has to be popular, or else there won't be any players interested in spending their hard-earned money on it. Advertisements -------------- Instead of actively selling the games you can also try to get yourself a passive income — showing adverts and relying on previous activities related to promoting your game may benefit, but your game has to be addictive, which isn't as easy as it sounds. You still need to plan it out, and at some point you'll need a bit of luck too. If your game goes viral and people start sharing it, you can get a lot of downloads and money out of adverts. There are many companies offering advert systems — you sign up and allow them to show adverts in exchange for a percentage of the earnings. Google AdSense is said to be the most effective one, but it's not designed for games and it's a pretty bad practice to use it for that purpose. Instead of risking of having your account closed and all the money blocked try to use the usual, gamedev targeted portals like LeadBolt. They offer easy to implement systems to show the adverts in your games and split the earnings with you. Video ads are getting more and more popular, especially in the form of a pre-roll — they are shown at the beginning of your game while it's still loading. And on the topic of where to put the advertisements in your game it really depends on you. It should be as subtle as possible to not annoy the players too much, but visible enough to make them click it or at least take notice. Adding adverts between game sessions on game over screens is a popular approach. Licensing --------- There's an approach that can work as a monetization model on its own, and that's selling licenses for distribution of your game. There are more and more portals interested in showing your games on their websites. They follow various strategies to earn money via your games, but you don't have to worry about all that as selling the license is usually a one-time deal. You get the money and they can get creative with using your game to make money. Finding publishers might be hard at first — try to look for them at the HTML5 Gamedevs forums. If you're well known they may reach out to you. Most of the deals are done through emails when talking to a dedicated person on the publisher side. Some publisher websites have that information easily available, while some others are harder to find. When reaching a publisher try to be nice and straight to the point — they are busy people. ### Exclusive licenses The exclusive license is a type of license for one publisher — you've built a game and you're selling all the rights to it to a single entity along with the rights to redistribute it — Softgames are an example of such a publisher. You can't sell it again in any form while that publisher has the rights — that's why exclusive deals are worth quite a lot of money. How much exactly? It depends on the quality of the game, it's genre, its publisher, and many others, but usually it will be something between 2000 and 5000 USD. Once you've sold an exclusive license you can forget about promoting that particular game as you won't earn more, so go into such a deal only if you're sure it's profitable enough. ### Non-exclusive licenses This approach is less strict — you can sell a license to multiple publishers. This is the most popular approach as with every new publisher (and they are constantly showing up) you can sell your games on non-exclusive terms. Remember that with this license the publisher can't redistribute it further — it's often called a site-locked deal as they buy the right to publish the game on their own given portal. The usual cost of a non-exclusive license is around 500 USD. ### Subscriptions There's also an option to get a passive, monthly revenue via a subscription deal. Instead of getting a one-time payment you can get a small amount of money per game, per month — it can be something around 20-50 USD per month, per game. It's normally up to you if you want to get all the money in a lump sum or get it per month. Remember that it can be cancelled, so it's not an indefinitely working solution. ### Ad revenue You can implement advertisements in your game on your own and try to find the traffic to earn a bit, but you can also do a revenue share deal with a publisher. They will take care of driving the traffic and will split the earnings — usually in a 70/30 or 50/50 deal, collected per month. Remember that many new, low quality publishers will want to get your game for ad revenue instead of licensing because it will be cheaper for them and you might end up with earnings around 2 USD per game for the whole deal. Be careful when dealing with new publishers — sometimes it's better to lower the license cost for a known one rather than risking fraud with an unknown publisher for more money. Publishers taking your games for revenue share, and/or licensing may require implementing their own APIs, which could take extra work, so consider that in your rates too. ### Branding You can sell rights to use your game for branding, or do it yourself. In the first case it's almost like non-exclusive licensing, but the client will usually buy rights for the code and implement their own graphics. In the second case it's like a freelance deal, but you're reusing the code and adding graphics provided by the client, sometimes implementing them as they instruct you. As an example if you've got a game where a player taps items of food, you could change the food to the client's products to give them advertising. Prices in this model vary greatly depending on the brand, client, and amount of work you put in. Other non-game focused monetization strategies ---------------------------------------------- There are other ways you can earn money when building HTML games, and it doesn't even have to be game-related. ### Selling resources If you're a graphic designer, you can sell the assets from the games you've created, or something brand new exclusively for that purpose at online shops like Envato Market. It's not much, but if you're a known designer it can be an extra passive stream of income. ### Writing articles and tutorials It is possible to write articles about your games and even get paid for them. Game promotion and monetization at the same time is a win-win, and if you don't abuse it with too much advertising the readers will enjoy reading them and as well as learning a thing or two. If you focus on sharing the knowledge first and use your games just as the examples it should be OK. Check out Tuts+ Game Development or similar websites for writing opportunities. ### Merchandise You can sell t-shirts, stickers or other gadgets — some devs make more money from the merchandise than from the games themselves, but it only works on very popular and recognizable games like Angry Birds. Still, it could be another small stream of passive income. The more diversified your earnings are, the better your business stability. ### Donations When all else fails you can try putting a donate button on your game's page and asking for support from the community. Sometimes it works, but only if the player knows you and feels that it will help you in your situation. That's why carefully managing your community is so important. It worked with the js13kGames competition — every participant got a free t-shirt, and some even gave back a few bucks to help keep it going in years to come. Summary ------- There are many ways to earn money — everything that applies to the "normal" AAA gaming world can be, more or less, applied to casual HTML games. You might however also focus on selling licenses, doing branding, or earning on a revenue share basis from the advertisements. It's totally up to you which path you're going to follow.
Game distribution - Game development
Game distribution ================= You've followed a tutorial or two and created an HTML game — that's great! This article covers all you need to know about the ways in which you can distribute your newly created game into the wild. This includes hosting it yourself online, submitting it to open marketplaces, and submitting it to closed ones like Google Play or the iOS App Store. Benefits of HTML over native ---------------------------- Building games with HTML gives you extra advantages, such as: ### Multiplatform bliss The technology itself is multiplatform, so you can write the code once and target multiple devices. This can range from low-end smartphones or tablets, through laptops and desktop computers, to smart TVs, watches or even a fridge if it can handle a modern enough browser. You don't need to have separate teams to work on the same title targeting different platforms with only one code base to worry about. You can spend more time and money on Promotion and Monetization. ### Instant updates You don't have to wait several days to have your game's code updated. If your user finds a bug, you can quickly fix it, update the system and refresh the game on your server to provide players with the updated code almost instantly. ### Direct link distribution and instant play You don't have to tell people to search for your game in an app store with HTML games. You can just send them a direct URL to access the game, which they can then click to play the game right away without the need to use third party plugins or download and install a large package. Bear in mind that downloading the game might still take a bit of time depending on the size of the game and your network speed. In any case, it's a lot easier to promote the game if you can drive traffic directly where you want it and don't have to jump through lots of hoops to play. Desktop vs. mobile ------------------ The vast majority of the traffic we are interested in — people playing HTML games — comes from mobile devices so that's something you will have to focus on if you truly want to succeed. Mobile devices are where HTML technology can truly shine and show its advantages. There's no Flash, and HTML is fully multiplatform. Trying to compete with desktop games directly is very difficult. You can put your HTML games into the same arena (see Native desktop, later on) and you should because it's good to diversify the platforms you support, but you have to remember that developers creating desktop games have years of experience, great tools and stable distribution channels. Many HTML games will target different market segments than native desktop games, e.g. simple time killer games to be played while on the move rather than huge immersive experiences. Such games are often designed to be played with two, or even one finger, so you can hold the device, play the game and be able to use the second hand for whatever you currently need. Saying this, desktop platforms can be used for distribution quite easily with the availability of wrappers that can help you prepare native builds of your game see Packaging games. It's also nice to provide desktop controls for your games even if you're mostly targeting mobile. Players are enjoying your games on any platform available, and desktop is one of them. Plus, it is usually easier to build and test the game first on desktop, and then move on to debugging mobile. Publishing the game ------------------- There are three main options when it comes to publishing a game: * Self-hosting * Publishers * Stores Remember that the name of your game should be unique enough to be quickly promoted later on, but also catchy enough, so people don't forget it. ### Self-hosting If you are a front-end developer, you may already know what to do. An HTML game is just another website. You can upload it to a remote server, grab a catchy domain name, and host it yourself. If you want to make money out of game dev, you should secure your source code one way or another against people who could easily take it and sell it as their own. You can concatenate and minify the code to make it smaller and uglify it so it's a lot harder to reverse engineer your game. Another good measure to take is to provide an online demo if you're planning on packaging it and selling it in a closed store like iTunes or Steam. If you're working on a side project just for fun, then leaving the source open will benefit those who would like to learn from what you've created. You don't even have to worry about looking for a hosting provider as it's possible to host games on GitHub Pages. You'll get free hosting, version control and possible contributors if your project is interesting enough. ### Publishers and portals As the name may suggest, publishers can handle the publishing of your game for you. Whether you should go that way or not depends on what your plan is for having your game distributed: Do you want to send it wherever possible, or do you want to restrict its presence to those who've bought an exclusive license? It's up to you. Consider various options, experiment and conclude. Publishers will be explained in more detail in the monetization article. There are also independent portals collecting interesting games like HTML5Games.com, GameArter.com, MarketJS.com, GameFlare, GameDistribution.com, Poki, or CrazyGames where you can send your game in and it will get some natural promotion because of the big traffic those sites attract. Some of these take your files and host them on their server, whereas others only link to your website or embed your game on their site. Such exposure may just provide promotion for your game, or if you have adverts shown beside your game (or other money making options) it may also provide monetization. ### Web and native stores You can also upload and publish your game directly to different types of stores, or marketplaces. To do that you'll have to prepare and package it to a build format specific for every app ecosystem you want to target it at. See Marketplaces — distribution platforms for more details of what marketplace types are available. Marketplaces — Distribution platforms ------------------------------------- Let's see what the available options are regarding the marketplaces/stores available for different platforms and operating systems. **Note:** These are the most popular distribution platforms, but this is not to say these are the only options. Instead of trying to add your game to the thousands of others in the iOS store say, you can also try to find a niche and promote directly to the audience who would be interested in your games. Your creativity is critical here. ### Web stores The best platforms for HTML games are Web-based stores. You can prepare games for web stores by adding a manifest file and other data, such as resources, in a zipped package. Not many modifications of the game itself are required. * The Chrome Web Store is also an attractive option — again, having a manifest file ready, zipping your game and filling in the online submission form is about all that's required. ### Native mobile stores When it comes to the mobile market, there's the Apple App Store for iOS, Google Play for Android and all the rest of the competition. Native stores are already filled with established devs selling great games, so you have to be talented and lucky to get noticed. * The iOS App Store is quite hard to get into as there are strict requirements games have to meet, and you'll have to wait a week or two to get accepted. Plus, it's the most prominent mobile store, with hundreds of thousands of apps, so it's extremely hard to stand out from the crowd. * Google Play's requirements are less strict, so the store is polluted with low quality games. It's still quite hard to be noticed there as the number of apps submitted daily is huge. It's harder to earn money here too — most of the paid games from iOS are published as free games on Android, with monetization coming from in-app purchases (IAPs) or ads. * Other stores for native mobile platforms like Windows Phone or Blackberry are working hard to get a piece of the cake, and are way behind the competition. It can be good to submit your game there as it will be a lot easier to be noticed. If you're looking for more information about the different types of app stores you can check the List of mobile software distribution platforms article on Wikipedia. ### Native desktop To broaden your audience you can hit the desktop ecosystem with your HTML games too — just remember all the popular AAA games that take most of the market share, and think carefully about whether this suits your strategy. To do the desktop thing properly you should support all three operating systems: Windows, macOS and Linux. The biggest desktop store for games is definitely Steam — indie developers can get on Steam via the Steam Direct program. Remember that you have to deal with the cross-platform issues yourself by uploading separate versions for different platforms. After you've covered Steam, there's plenty of buzz around initiatives like Humble Bundle where the most popular indie games get presented to a broader audience. It's more like an excellent promotional opportunity than a way to earn a lot of money, however, as the prices paid for the games in a bundle are usually quite low. Packaging games --------------- The web is the first and the best choice for HTML games, but if you want to reach a broader audience and distribute your game in a closed ecosystem, you still can do that by packaging it. The good thing is that you don't need a few separate teams working on the same game for different platforms — you can build it once and use tools like Phonegap or CocoonIO to package the game for native stores. The resulting packages are usually pretty reliable, but you should still test them and be on the lookout for small issues or bugs to fix. ### Available tools There are various tools to choose from depending on your skills, preferred frameworks or target platforms. It's all about picking the best tool for your particular task. * Ejecta — a tool specifically for packaging games created with the ImpactJS framework for iOS, built by the ImpactJS author. It provides seamless integration with ImpactJS, but it supports only one framework and app store. * NW.js — formerly known as Node-Webkit, this is the first choice when it comes to building a desktop game that works on Windows, Mac and Linux. The distributions are packaged with the WebKit engine to provide rendering on any platform. Other alternative tools are: * Intel XDK — an exciting alternative, similar to CocoonIO. * Electron — known as Atom Shell — is an open-sourced and cross-platform tool from GitHub. * Manifold.js — this tool from the Microsoft team can create native distributions of HTML games from iOS, Android, and Windows. Summary ------- Distribution is the way to give the world access to your game. There are many options available and there's no single good answer as to which is the best. When you've published the game it's time to focus on promotion — letting people know your game exists. Without promotion, they wouldn't even be able to learn about it and play it.
3D games on the Web - Game development
3D games on the Web =================== For rich gaming experiences on the web, the weapon of choice is WebGL, which is rendered on HTML `<canvas>`. WebGL is basically an OpenGL ES 2.0 for the Web — it's a JavaScript API providing tools to build rich interactive animations and of course, also games. You can generate and render dynamic 3D graphics with JavaScript that is hardware accelerated. Documentation and browser support --------------------------------- The WebGL project documentation and specification is maintained by the Khronos Group, not the W3C as with most of the web APIs. Support on modern browsers is very good, even on mobile, so you don't have to worry about that too much. The main browsers are all supporting WebGL and all you need to focus on is optimizing the performance on the devices you use. There's an ongoing effort on releasing WebGL 2.0 (based on OpenGL ES 3.0) in the near future, which will bring many improvements and will help developers build games for the modern web using current, powerful hardware. Explaining the basic 3D theory ------------------------------ The basics of 3D theory centers around shapes represented in a 3D space, with a coordinate system being used to calculate their positions. See our Explaining basic 3D theory article for all the information you need. Advanced concepts ----------------- You can do a lot more with WebGL. There are some advanced concepts which you should dive into and learn more about — like shaders, collision detection, or the latest hot topic: virtual reality on the web. ### Shaders It's worth mentioning shaders, which are a separate story on their own. Shaders use GLSL, a special OpenGL shading language, with syntax similar to C, that is executed directly by the graphics pipeline. They can be split into vertex shaders and fragment shaders (or pixel shaders) — the former transforms shape positions to real 3D drawing coordinates, while the latter computes rendering colors and other attributes. You should definitely check out GLSL Shaders article to learn more about them. ### Collision detection It's hard to imagine a game without collision detection — we always need to work out when something is hitting something else. We have information available for you to learn from: * 2D collision detection * 3D collision detection ### WebXR The concept of virtual reality is not new, but it's storming onto the web thanks to hardware advancements such as the Meta Quest, and the (currently experimental) WebXR API for capturing information from XR hardware and making it available for use in JavaScript applications. For more, read WebXR — Virtual and Augmented Reality for the Web. There's also the Building up a basic demo with A-Frame article showing you how easy it is to build 3D environments for virtual reality using the A-Frame framework. The rise of libraries and frameworks ------------------------------------ Coding raw WebGL is fairly complex, but you'll want to get to grips with it in the long run, as your projects get more advanced (see our WebGL documentation to get started.) For real-world projects you'll probably also make use of a framework to speed up development and help you manage the project you're working on. Using a framework for 3D games also helps optimize the performance as a lot is taken care of by the tools you use, so you can focus on building the game itself. The most popular JavaScript 3D library is Three.js, a multipurpose tool that makes common 3D techniques simpler to implement. There are other popular game development libraries and frameworks worth checking too; A-Frame, PlayCanvas and Babylon.js are among the most recognizable ones with rich documentation, online editors and active communities. ### Building up a basic demo with A-Frame A-Frame is a web framework for building 3D and VR experiences. Under the hood, it is a Three.js framework with a declarative entity-component pattern, meaning we can build scenes with just HTML. See the Building up a basic demo with A-Frame subpage for the step-by-step process of creating the demo. ### Building up a basic demo with Babylon.js Babylon.js is one of the most popular 3D game engines used by developers. As with any other 3D library, it provides built-in functions to help you implement common 3D functionality more quickly. See the Building up a basic demo with Babylon.js subpage for the basics of using Babylon.js, including setting up a development environment, structuring the necessary HTML, and writing the JavaScript code. ### Building up a basic demo with PlayCanvas PlayCanvas is a popular 3D WebGL game engine open-sourced on GitHub, with an editor available online and good documentation. See the Building up a basic demo with PlayCanvas subpage for higher-level details, and further articles showing how to create demos using the PlayCanvas library, and the online editor. ### Building up a basic demo with Three.js Three.js, like any other library, gives you a huge advantage: instead of writing hundreds of lines of WebGL code to build anything interesting you can use built-in helper functions to do it a lot easier and faster. See the Building up a basic demo with Three.js subpage for the step-by-step process of creating the demo. ### Other tools Both Unity and Unreal can export your game to WebGL with asm.js, so you're free to use their tools and techniques to build games that will be exported to the web. ![Illustration of three 3D geometry shapes: a grey torus, a blue cube, and a yellow cylinder.](/en-US/docs/Games/Techniques/3D_on_the_web/shapes.png) Where to go next ---------------- With this article we just scratched the surface of what's possible with currently available technologies. You can build immersive, beautiful and fast 3D games on the Web using WebGL, and the libraries and frameworks build on top of it. ### Source code You can find all the source code for this series demos on GitHub. ### APIs * Canvas API * WebGL API * WebVR API ### Frameworks * Three.js * PlayCanvas * Babylon.js * A-Frame ### Tutorials * Building up a basic demo with Three.js * Building up a basic demo with PlayCanvas * Building up a basic demo with Babylon.js * Building up a basic demo with A-Frame
Crisp pixel art look with image-rendering - Game development
Crisp pixel art look with image-rendering ========================================= This article discusses a useful technique for giving your canvas/WebGL games a crisp pixel art look, even on high definition monitors. The concept ----------- Retro pixel art aesthetics are getting popular, especially in indie games or game jam entries. But since today's screens render content at high resolutions, there is a problem with making sure the pixel art does not look blurry. Developers have been manually scaling up graphics so they are shown with blocks that represent pixels. Two downsides to this method are larger file sizes and compression artifacts. | | | | | --- | --- | --- | | small pixelated man | small pixelated man | larger pixelated man | | original size | 4x size | 4x size (scaled with an image editor) | | none | vendor's algorithm | nearest-neighbor algorithm | A CSS-based solution -------------------- The good news is that you can use CSS to automatically do the up-scaling, which not only solves the blur problem, but also allows you to use the images in their original, smaller size, thus saving download time. Also, some game techniques require algorithms that analyze images, which also benefit from working with smaller images. The CSS property to achieve this scaling is `image-rendering`. The steps to achieve this effect are: * Create a `<canvas>` element and set its `width` and `height` attributes to the original, smaller resolution. * Set its CSS `width` and `height` properties to be 2x or 4x the value of the HTML `width` and `height`. If the canvas was created with a 128 pixel width, for example, we would set the CSS `width` to `512px` if we wanted a 4x scale. * Set the `<canvas>` element's `image-rendering` CSS property to `pixelated`, which does not make the image blurry. There are also the `crisp-edges` and `-webkit-optimize-contrast` values that work on some browsers. Check out the `image-rendering` article for more information on the differences between these values, and which values to use depending on the browser. An example ---------- Let's have a look at an example. The original image we want to upscale looks like this: ![Pixelated night scenery of a cat on the edge off a cliff with little hearts above his head, behind him a big full moon. With a black background, white text is displayed at the bottom of the image saying: in love with the moon.](/en-US/docs/Games/Techniques/Crisp_pixel_art_look/cat.png) Here's some HTML to create a simple canvas: ```html <canvas id="game" width="128" height="128">A cat</canvas> ``` CSS to size the canvas and render a crisp image: ```css canvas { width: 512px; height: 512px; image-rendering: pixelated; } ``` And some JavaScript to set up the canvas and load the image: ```js // Get canvas context const ctx = document.getElementById("game").getContext("2d"); // Load image const image = new Image(); image.onload = () => { // Draw the image into the canvas ctx.drawImage(image, 0, 0); }; image.src = "cat.png"; ``` This code used together produces the following result: **Note:** Canvas content is not accessible to screen readers. Include descriptive text as the value of the `aria-label` attribute directly on the canvas element itself or include fallback content placed within the opening and closing canvas tag. Canvas content is not part of the DOM, but nested fallback content is.
Tiles and tilemaps overview - Game development
Tiles and tilemaps overview =========================== Tilemaps are a very popular technique in 2D game development, consisting of building the game world or level map out of small, regular-shaped images called **tiles**. This results in performance and memory usage gains — big image files containing entire level maps are not needed, as they are constructed by small images or image fragments multiple times. This set of articles covers the basics of creating tile maps using JavaScript and Canvas (although the same high level techniques could be used in any programming language.) Besides the performance gains, tilemaps can also be mapped to a logical grid, which can be used in other ways inside the game logic (for example creating a path-finding graph, or handling collisions) or to create a level editor. Some popular games that use this technique are *Super Mario Bros*, *Pacman*, *Zelda: Link's Awakening*, *Starcraft*, and *Sim City 2000*. Think about any game that uses regularly repeating squares of background, and you'll probably find it uses tilemaps. The tile atlas -------------- The most efficient way to store the tile images is in an atlas or spritesheet. This is all of the required tiles grouped together in a single image file. When it's time to draw a tile, only a small section of this bigger image is rendered on the game canvas. The below images shows a tile atlas of 8 x 4 tiles: ![Tile atlas image](/en-US/docs/Games/Techniques/Tilemaps/tile_atlas.png) Using an atlas also has the advantage of naturally assigning every tile an **index**. This index is perfect to use as the tile identifier when creating the tilemap object. The tilemap data structure -------------------------- It is common to group all the information needed to handle tilemaps into the same data structure or object. These data objects (map object example) should include: * **Tile size**: The size of each tile in pixels across / pixels down. * **Image atlas**: The Image atlas that will be used (one or many.) * **Map dimensions**: The dimensions of the map, either in tiles across / tiles down, or pixels across / pixels down. * **Visual grid**: Includes indices showing what type of tile should be placed on each position in the grid. * **Logic grid**: This can be a collision grid, a path-finding grid, etc., depending on the type of game. **Note:** For the visual grid, a special value (usually a negative number, `0` or `null`) is needed to represent empty tiles. Square tiles ------------ Square-based tilemaps are the most simple implementation. A more generic case would be rectangular-based tilemaps — instead of square — but they are far less common. Square tiles allow for two **perspectives**: * Top-down (like many RPG's or strategy games like *Warcraft 2* or *Final Fantasy*'s world view.) * Side-view (like platformers such as *Super Mario Bros*.) ### Static tilemaps A tilemap can either fit into the visible screen area screen or be larger. In the first case, the tilemap is **static** — it doesn't need to be scrolled to be fully shown. This case is very common in arcade games like *Pacman*, *Arkanoid*, or *Sokoban*. Rendering static tilemaps is easy, and can be done with a nested loop iterating over columns and rows. A high-level algorithm could be: ```js for (let column = 0; column < map.columns; column++) { for (let row = 0; row < map.rows; row++) { const tile = map.getTile(column, row); const x = column \* map.tileSize; const y = row \* map.tileSize; drawTile(tile, x, y); } } ``` You can read more about this and see an example implementation in Square tilemaps implementation: Static maps. ### Scrolling tilemaps **Scrolling** tilemaps only show a small portion of the world at a time. They can follow a character — like in platformers or RPGs — or allow the player to control the camera — like in strategy or simulation games. #### Positioning and camera In all scrolling games, we need a translation between **world coordinates** (the position where sprites or other elements are located in the level or game world) and **screen coordinates** (the actual position where those elements are rendered on the screen). The world coordinates can be expressed in terms of tile position (row and column of the map) or in pixels across the map, depending on the game. To be able to transform world coordinates into screen coordinates, we need the coordinates of the camera, since they determine which section of the world is being displayed. Here are examples showing how to translate from world coordinates to screen coordinates and back again: ```js // these functions assume that the camera points to the top left corner function worldToScreen(x, y) { return { x: x - camera.x, y: y - camera.y }; } function screenToWorld(x, y) { return { x: x + camera.x, y: y + camera.y }; } ``` #### Rendering A trivial method for rendering would just be to iterate over all the tiles (like in static tilemaps) and draw them, subtracting the camera coordinates (like in the `worldToScreen()` example shown above) and letting the parts that fall outside the view window sit there, hidden. Drawing all the tiles that can not be seen is wasteful, however, and can take a toll on performance. **Only tiles that are at visible should be rendered** ideally — see the Performance section for more ideas on improving rendering performance. You can read more about implementing scrolling tilemaps and see some example implementations in Square tilemaps implementation: Scrolling maps. ### Layers The visual grid is often made up of several layers. This allows us to have a richer game world with fewer tiles, since the same image can be used with different backgrounds. For instance, a rock that could appear on top of several terrain types (like grass, sand or brick) could be included on its own separate tile which is then rendered on a new layer, instead of several rock tiles, each with a different background terrain. If characters or other game sprites are drawn in the middle of the layer stack, this allows for interesting effects such as having characters walking behind trees or buildings. The following screenshot shows an example of both points: a character appearing *behind* a tile (the knight appearing behind the top of a tree) and a tile (the bush) being rendered over different terrain types. ![A grid of layered background terrains. A bush tile is rendered at the top, over a large grass terrain, and again over a layered rectangular terrain with brown sand at the bottom. A tree tile is rendered over the grass terrain at the bottom left and again at the bottom right. A knight tile appears behind the tree tile that is rendered at the bottom left.](/en-US/docs/Games/Techniques/Tilemaps/screen_shot_2015-10-06_at_15.56.05.png) ### The logic grid Since tilemaps are an actual grid of visual tiles, it is common to create a mapping between this visual grid and a logic grid. The most common case is to use this logic grid to handle collisions, but other uses are possible as well: character spawning points, detecting whether some elements are placed together in the right way to trigger a certain action (like in *Tetris* or *Bejeweled*), path-finding algorithms, etc. **Note:** You can take a look at our demo that shows how to use a logic grid to handle collisions. Isometric tilemaps ------------------ Isometric tilemaps create the illusion of a 3D environment, and are extremely popular in 2D simulation, strategy, or RPG games. Some of these games include *SimCity 2000*, *Pharaoh*, or *Final Fantasy Tactics*. The below image shows an example of an atlas for an isometric tileset. ![A 3x4 map of variously colored tiles in isometric projection](/en-US/docs/Games/Techniques/Tilemaps/iso_tiles.png) Performance ----------- Drawing scrolling tile maps can take a toll on performance. Usually, some techniques need to be implemented so scrolling can be smooth. The first approach, as discussed above, is to **only draw tiles that will be visible**. But sometimes, this is not enough. One simple technique consists of pre-rendering the map in a canvas on its own (when using the Canvas API) or on a texture (when using WebGL), so tiles don't need to be re-drawn every frame and rendering can be done in just one blitting operation. Of course, if the map is large this doesn't really solve the problem — and some systems don't have a very generous limit on how big a texture can be. One way consists of drawing the section that will be visible off-canvas (instead of the entire map.) That means that as long as there is no scrolling, the map doesn't need to be rendered. A caveat of that approach is that when there *is* a scrolling, that technique is not very efficient. A better way would be to create a canvas that is 2x2 tiles bigger than the visible area, so there is one tile of "bleeding" around the edges. That means that the map only needs to be redrawn on the canvas when the scrolling has advanced one full tile — instead of every frame — while scrolling. In fast games that might still not be enough. An alternative method would be to split the tilemap into big sections (like a full map split into 10 x 10 chunks of tiles), pre-render each one off-canvas and then treat each rendered section as a "big tile" in combination with one of the algorithms discussed above. See also -------- * Related articles on the MDN: + Static square tile maps implementation with Canvas API + Scrolling square tile maps implementation with Canvas API * External resources: + Demos and source code + Amit's thoughts on grids + Isometric graphics in videogames (Wikipedia)
Implementing controls using the Gamepad API - Game development
Implementing controls using the Gamepad API =========================================== This article looks at implementing an effective, cross-browser control system for web games using the Gamepad API, allowing you to control your web games using console game controllers. It features a case study game — Hungry Fridge, created by Enclave Games. Controls for web games ---------------------- Historically playing games on a console connected to your TV was always a totally different experience to gaming on the PC, mostly because of the unique controls. Eventually, extra drivers and plugins allowed us to use console gamepads with desktop games — either native games or those running in the browser. Now we have the Gamepad API, which gives us the ability to play browser-based games using gamepad controllers without any plugins. The Gamepad API achieves this by providing an interface exposing button presses and axis changes that can be used inside JavaScript code to handle the input. These are good times for browser gaming. API status and browser support ------------------------------ The Gamepad API is still at the Working Draft stage in the W3C process, which means its implementation might still change, but saying that the browser support is already quite good. Firefox 29+ and Chrome 35+ support it out of the box. Opera supports the API in version 22+ (not surprising given that they now use Chrome's Blink engine.) And Microsoft implemented support for the API in Edge recently, which means four main browsers now supporting the Gamepad API. Which gamepads are best? ------------------------ The most popular gamepads right now are those from the Xbox 360, Xbox One, PS3 and PS4 — they have been heavily tested and work well with the Gamepad API implementation in browsers across Windows and macOS. There's also a number of other devices with various different button layouts that more or less work across browser implementations. The code discussed in this article was tested with a few gamepads, but the author's favorite configuration is a wireless Xbox 360 controller and the Firefox browser on macOS. Case Study: Hungry Fridge ------------------------- The GitHub Game Off II competition ran in November 2013 and Enclave Games decided to take part in it. The theme for the competition was "change", so they submitted a game where you have to feed the Hungry Fridge by tapping the healthy food (apples, carrots, lettuces) and avoid the "bad" food (beer, burgers, pizza.) A countdown changes the type of food the Fridge wants to eat every few seconds, so you have to be careful and act quickly. The second, hidden "change" implementation is the ability to transform the static Fridge into a full-blown moving, shooting and eating machine. When you connect the controller, the game significantly changes (Hungry Fridge turns into the Super Turbo Hungry Fridge) and you're able to control the armored fridge using the Gamepad API. You have to shoot down the food, but once again you also have to find the type of food the Fridge wants to eat at each point, or else you'll lose energy. The game encapsulates two totally different types of "change" — good food vs. bad food, and mobile vs. desktop. Demo ---- The full version of the Hungry Fridge game was built first, and then to showcase the Gamepad API in action and show the JavaScript source code, a simple demo was created. It's part of the Gamepad API Content Kit available on GitHub where you can dive deep into the code and study exactly how it works. The code explained below is from the full version of the Hungry Fridge game, but it's almost identical to the one from the demo — the only difference is that the full version uses the `turbo` variable to decide whether the game will be launched using Super Turbo mode. It works independently, so it could be turned on even if the gamepad is not connected. **Note:** Easter Egg time: There's a hidden option to launch Super Turbo Hungry Fridge on the desktop without having a gamepad connected — click the gamepad icon in the top right corner of the screen. It will launch the game in the Super Turbo mode and you'll be able to control the Fridge with the keyboard: A and D for turning the turret left and right, W for shooting and arrow keys for movement. Implementation -------------- There are two important events to use along with the Gamepad API — `gamepadconnected` and `gamepaddisconnected`. The first one is fired when the browser detects the connection of a new gamepad while the second one is fired when a gamepad is disconnected (either physically by the user or due to inactivity.) In the demo, the `gamepadAPI` object is used to store everything related to the API: ```js const gamepadAPI = { controller: {}, turbo: false, connect() {}, disconnect() {}, update() {}, buttonPressed() {}, buttons: [], buttonsCache: [], buttonsStatus: [], axesStatus: [], }; ``` The `buttons` array contains the Xbox 360 button layout: ```js buttons: [ 'DPad-Up','DPad-Down','DPad-Left','DPad-Right', 'Start','Back','Axis-Left','Axis-Right', 'LB','RB','Power','A','B','X','Y', ], ``` This can be different for other types of gamepads like the PS3 controller (or a no-name, generic one), so you have to be careful and not just assume the button you're expecting will be the same button you'll actually get. Next, we set up two event listeners to get the data: ```js window.addEventListener("gamepadconnected", gamepadAPI.connect); window.addEventListener("gamepaddisconnected", gamepadAPI.disconnect); ``` Due to security policy, you have to interact with the controller first while the page is visible for the event to fire. If the API worked without any interaction from the user it could be used to fingerprint them without their knowledge. Both functions are fairly simple: ```js connect(evt) { gamepadAPI.controller = evt.gamepad; gamepadAPI.turbo = true; console.log('Gamepad connected.'); }, ``` The `connect()` function takes the event as a parameter and assigns the `gamepad` object to the `gamepadAPI.controller` variable. We are using only one gamepad for this game, so it's a single object instead of an array of gamepads. We then set the `turbo` property to `true`. (We could use the `gamepad.connected` boolean for this purpose, but we wanted to have a separate variable for turning on Turbo mode without needing to have a gamepad connected, for reasons explained above.) ```js disconnect(evt) { gamepadAPI.turbo = false; delete gamepadAPI.controller; console.log('Gamepad disconnected.'); }, ``` The `disconnect` function sets the `gamepad.turbo property` to `false` and removes the variable containing the gamepad object. ### Gamepad object There's lots of useful information contained in the `gamepad` object, with the states of buttons and axes being the most important: * `id`: A string containing information about the controller. * `index`: A unique identifier for the connected device. * `connected`: A boolean variable, `true` if the device is connected. * `mapping`: The layout type of the buttons; `standard` is the only available option for now. * `axes`: The state of each axis, represented by an array of floating-point values. * `buttons` : The state of each button, represented by an array of `GamepadButton` objects containing `pressed` and `value` properties. The `index` variable is useful if we're connecting more than one controller and want to identify them to act accordingly — for example when we have a two-player game requiring two devices to be connected. ### Querying the gamepad object Beside `connect()` and `disconnect()`, there are two more methods in the `gamepadAPI` object: `update()` and `buttonPressed()`. `update()` is executed on every frame inside the game loop, to update the actual status of the gamepad object regularly: ```js update() { // Clear the buttons cache gamepadAPI.buttonsCache = []; // Move the buttons status from the previous frame to the cache for (let k = 0; k < gamepadAPI.buttonsStatus.length; k++) { gamepadAPI.buttonsCache[k] = gamepadAPI.buttonsStatus[k]; } // Clear the buttons status gamepadAPI.buttonsStatus = []; // Get the gamepad object const c = gamepadAPI.controller || {}; // Loop through buttons and push the pressed ones to the array const pressed = []; if (c.buttons) { for (let b = 0; b < c.buttons.length; b++) { if (c.buttons[b].pressed) { pressed.push(gamepadAPI.buttons[b]); } } } // Loop through axes and push their values to the array const axes = []; if (c.axes) { for (let a = 0; a < c.axes.length; a++) { axes.push(c.axes[a].toFixed(2)); } } // Assign received values gamepadAPI.axesStatus = axes; gamepadAPI.buttonsStatus = pressed; // Return buttons for debugging purposes return pressed; }, ``` On every frame, `update()` saves buttons pressed during the previous frame to the `buttonsCache` array and takes fresh ones from the `gamepadAPI.controller` object. Then it loops through buttons and axes to get their actual states and values. ### Detecting button presses The `buttonPressed()` method is also placed in the main game loop to listen for button presses. It takes two parameters — the button we want to listen to and the (optional) way to tell the game that holding the button is accepted. Without it you'd have to release the button and press it again to have the desired effect. ```js buttonPressed(button, hold) { let newPress = false; // Loop through pressed buttons for (let i = 0; i < gamepadAPI.buttonsStatus.length; i++) { // If we found the button we're looking for if (gamepadAPI.buttonsStatus[i] === button) { // Set the boolean variable to true newPress = true; // If we want to check the single press if (!hold) { // Loop through the cached states from the previous frame for (let j = 0; j < gamepadAPI.buttonsCache.length; j++) { // If the button was already pressed, ignore new press newPress = (gamepadAPI.buttonsCache[j] !== button); } } } } return newPress; }, ``` There are two types of action to consider for a button: a single press and a hold. The `newPress` boolean variable will indicate whether there's a new press of a button or not. Next, we loop through the array of pressed buttons — if the given button is the same as the one we're looking for, the `newPress` variable is set to `true`. To check if the press is a new one, so the player is not holding the key, we loop through the cached states of the buttons from the previous frame of the game loop. If we find it there it means that the button is being held, so there's no new press. In the end the `newPress` variable is returned. The `buttonPressed` function is used in the update loop of the game like this: ```js if (gamepadAPI.turbo) { if (gamepadAPI.buttonPressed("A", "hold")) { this.turbo\_fire(); } if (gamepadAPI.buttonPressed("B")) { this.managePause(); } } ``` If `gamepadAPI.turbo` is `true` and the given buttons are pressed (or held), we execute the proper functions assigned to them. In this case, pressing or holding `A` will fire the bullet and pressing `B` will pause the game. ### Axis threshold The buttons have only two states: `0` or `1`, but the analog sticks can have many values — they have a float range between `-1` and `1` along both the `X` and `Y` axes. Gamepads can get dusty from lying around inactive, meaning that checking for exact -1 or 1 values can be a problem. For this reason, it can be good to set a threshold for the value of the axis to take effect. For example, the Fridge tank will turn right only when the `X` value is bigger than `0.5`: ```js if (gamepadAPI.axesStatus[0].x > 0.5) { this.player.angle += 3; this.turret.angle += 3; } ``` Even if we move it a little by mistake or the stick doesn't make it back to its original position, the tank won't turn unexpectedly. Specification update -------------------- After more than a year of stability, in April 2015 the W3C Gamepad API spec was updated (see the latest.) It hasn't changed much, but it's good to know what is going on — the updates are as follows. ### Getting the gamepads The `Navigator.getGamepads()` method has been updated with a longer explanation and an example piece of code. Now the length of the array of gamepads has to be `n+1` where `n` is the number of connected devices — when there's one device connected and it has the index of 1, the array's length is 2 and it will look like this: `[null, [object Gamepad]]`. If the device is disconnected or unavailable, the value for it is set to `null`. ### Mapping standard The mapping type is now an enumerable object instead of a string: ```ts enum GamepadMappingType { "", "standard", } ``` This enum defines the set of known mappings for a Gamepad. For now, there's only the `standard` layout available, but new ones may appear in the future. If the layout is unknown, it is set to an empty string. ### Events There were more events available in the spec than just `gamepadconnected` and `gamepaddisconnected` available, but they were removed from the specification as they were thought to not be very useful. The discussion is still ongoing whether they should be put back, and in what form. Summary ------- The Gamepad API is very easy to develop with. Now it's easier than ever to deliver a console-like experience to the browser without the need for any plugins. You can play the full version of the Hungry Fridge game directly in your browser. Check the other resources on the Gamepad API Content Kit.
2D collision detection - Game development
2D collision detection ====================== Algorithms to detect collision in 2D games depend on the type of shapes that can collide (e.g. Rectangle to Rectangle, Rectangle to Circle, Circle to Circle). Generally you will have a simple generic shape that covers the entity known as a "hitbox" so even though collision may not be pixel perfect, it will look good enough and be performant across multiple entities. This article provides a review of the most common techniques used to provide collision detection in 2D games. Axis-Aligned Bounding Box ------------------------- One of the simpler forms of collision detection is between two rectangles that are axis aligned — meaning no rotation. The algorithm works by ensuring there is no gap between any of the 4 sides of the rectangles. Any gap means a collision does not exist. ``` <div id="cr-stage"></div> <p> Move the rectangle with arrow keys. Green means collision, blue means no collision. </p> <script src="https://cdnjs.cloudflare.com/ajax/libs/crafty/0.5.4/crafty-min.js"></script> ``` ```js Crafty.init(200, 200); const dim1 = { x: 5, y: 5, w: 50, h: 50 }; const dim2 = { x: 20, y: 10, w: 60, h: 40 }; const rect1 = Crafty.e("2D, Canvas, Color").attr(dim1).color("red"); const rect2 = Crafty.e("2D, Canvas, Color, Keyboard, Fourway") .fourway(2) .attr(dim2) .color("blue"); rect2.bind("EnterFrame", function () { if ( rect1.x < rect2.x + rect2.w && rect1.x + rect1.w > rect2.x && rect1.y < rect2.y + rect2.h && rect1.y + rect1.h > rect2.y ) { // Collision detected! this.color("green"); } else { // No collision this.color("blue"); } }); ``` **Note:** Another example without Canvas or external libraries. Circle Collision ---------------- Another simple shape for collision detection is between two circles. This algorithm works by taking the center points of the two circles and ensuring the distance between the center points are less than the two radii added together. ``` <div id="cr-stage"></div> <p> Move the circle with arrow keys. Green means collision, blue means no collision. </p> <script src="https://cdnjs.cloudflare.com/ajax/libs/crafty/0.5.4/crafty-min.js"></script> ``` ``` #cr-stage { position: static !important; height: 200px !important; } ``` ```js Crafty.init(200, 200); const dim1 = { x: 5, y: 5 }; const dim2 = { x: 20, y: 20 }; Crafty.c("Circle", { circle(radius, color) { this.radius = radius; this.w = this.h = radius \* 2; this.color = color || "#000000"; this.bind("Move", Crafty.DrawManager.drawAll); return this; }, draw() { const ctx = Crafty.canvas.context; ctx.save(); ctx.fillStyle = this.color; ctx.beginPath(); ctx.arc( this.x + this.radius, this.y + this.radius, this.radius, 0, Math.PI \* 2, ); ctx.closePath(); ctx.fill(); ctx.restore(); }, }); const circle1 = Crafty.e("2D, Canvas, Circle").attr(dim1).circle(15, "red"); const circle2 = Crafty.e("2D, Canvas, Circle, Fourway") .fourway(2) .attr(dim2) .circle(20, "blue"); circle2.bind("EnterFrame", function () { const dx = circle1.x - circle2.x; const dy = circle1.y - circle2.y; const distance = Math.sqrt(dx \* dx + dy \* dy); const colliding = distance < circle1.radius + circle2.radius; this.color = colliding ? "green" : "blue"; }); ``` **Note:** Here is another example without Canvas or external libraries. Separating Axis Theorem ----------------------- This is a collision algorithm that can detect a collision between any two *convex* polygons. It's more complicated to implement than the above methods but is more powerful. The complexity of an algorithm like this means we will need to consider performance optimization, covered in the next section. Implementing SAT is out of scope for this page so see the recommended tutorials below: 1. Separating Axis Theorem (SAT) explanation 2. Collision detection and response 3. Collision detection Using the Separating Axis Theorem 4. SAT (Separating Axis Theorem) 5. Separating Axis Theorem Collision Performance --------------------- While some of these algorithms for collision detection are simple enough to calculate, it can be a waste of cycles to test *every* entity with every other entity. Usually games will split collision into two phases, broad and narrow. ### Broad Phase Broad phase should give you a list of entities that *could* be colliding. This can be implemented with a spacial data structure that will give you a rough idea of where the entity exists and what exist around it. Some examples of spacial data structures are Quad Trees, R-Trees or a Spacial Hashmap. ### Narrow Phase When you have a small list of entities to check you will want to use a narrow phase algorithm (like the ones listed above) to provide a certain answer as to whether there is a collision or not.
Async scripts for asm.js - Game development
Async scripts for asm.js ======================== Every medium or large game should compile asm.js code as part of an async script to give the browser the maximum flexibility to optimize the compilation process. In Gecko, async compilation allows the JavaScript engine to compile the asm.js off the main thread when the game is loading and cache the generated machine code so that the game doesn't need to be compiled on subsequent loads (starting in Firefox 28). To see the difference, toggle `javascript.options.parallel_parsing` in `about:config`. Putting async into action ------------------------- Getting async compilation is easy: when writing your JavaScript, just use the `async` attribute like so: ```html <script async src="file.js"></script> ``` or, to do the same thing via script: ```js const script = document.createElement("script"); script.src = "file.js"; document.body.appendChild(script); ``` (Scripts created from script default to `async`.) The default HTML shell Emscripten generates produces the latter. When is async not async? ------------------------ Two common situations in which a script is \*not\* async (as defined by the HTML spec) are: ```html <script async> code(); </script> ``` and ```js const script = document.createElement("script"); script.textContent = "code()"; document.body.appendChild(script); ``` Both are counted as 'inline' scripts and get compiled and then run immediately. What if your code is in a JS string? Instead of using `eval` or `innerHTML`, both of which trigger synchronous compilation, you should use a Blob with an object URL: ```js const blob = new Blob([codeString]); const script = document.createElement("script"); const url = URL.createObjectURL(blob); script.onload = script.onerror = () => URL.revokeObjectURL(url); script.src = url; document.body.appendChild(script); ``` The setting of `src` rather than `innerHTML` is what makes this script async.
Audio for Web games - Game development
Audio for Web games =================== Audio is an important part of any game; it adds feedback and atmosphere. Web-based audio is maturing fast, but there are still many browser differences to navigate. We often need to decide which audio parts are essential to our games' experience and which are nice to have but not essential, and devise a strategy accordingly. This article provides a detailed guide to implementing audio for web games, looking at what works currently across as wide a range of platforms as possible. Mobile audio caveats -------------------- By far the most difficult platforms to provide web audio support for are mobile platforms. Unfortunately these are also the platforms that people often use to play games. There are a couple of differences between desktop and mobile browsers that may have caused browser vendors to make choices that can make web audio difficult for game developers to work with. Let's look at these now. ### Autoplay Browser autoplay policy now affects desktop *and* mobile browsers. There is further information about it here from the Google Developers site. It is worth noting that autoplay with sound is allowed if: * the User has interacted with the domain. * on mobile the user has made the application installable. Many browsers will ignore any requests made by your game to automatically play audio; instead playback for audio needs to be started by a user-initiated event, such as a click or tap. This means you will have to structure your audio playback to take account of that. This is usually mitigated against by loading the audio in advance and priming it on a user-initiated event. For more passive audio autoplay, for example background music that starts as soon as a game loads, one trick is to detect *any* user initiated event and start playback then. For other more active sounds that are to be used during the game we could consider priming them as soon as something like a *Start* button is pressed. To prime audio like this we want to play a part of it; for this reason it is useful to include a moment of silence at the end of your audio sample. Jumping to, playing, and then pausing that silence will mean we can now use JavaScript to play that file at arbitrary points. You can find out more about best practices with the autoplay policy here. **Note:** Playing part of your file at zero volume could also work if the browser allows you to change volume (see below). Also note that playing and immediately pausing your audio does not guarantee that a small piece of audio won't be played. **Note:** Adding a web app to your mobile's homescreen may change its capabilities. In the case of autoplay on iOS, this appears to be the case currently. If possible, you should try your code on several devices and platforms to see how it works. ### Volume Programmatic volume control may be disabled in mobile browsers. The reason often given is that the user should be in control of the volume at the OS level and this shouldn't be overridden. ### Buffering and preloading Likely as an attempt to mitigate runaway mobile network data use, we also often find that buffering is disabled before playback has been initiated. Buffering is the process of the browser downloading the media in advance, which we often need to do to ensure smooth playback. The `HTMLMediaElement` interface comes with lots of properties to help determine whether a track is in a state to be playable. **Note:** In many ways the concept of buffering is an outdated one. As long as byte-range requests are accepted (which is the default behavior), we should be able to jump to a specific point in the audio without having to download the preceding content. However, preloading is still useful — without it, there would always need to be some client-server communication required before playing can commence. ### Concurrent audio playback A requirement of many games is the need to play more than one piece of audio at the same time; for example, there might be background music playing along with sound effects for various things happening in the game. Although the situation is soon going to get better with the adoption of the Web Audio API, the current most widely-supported method — using the vanilla `<audio>` element — leads to patchy results on mobile devices. ### Testing and support Here's a table that shows what mobile platforms support the features talked about above. Mobile support for web audio features| Mobile browser | Version | Concurrent play | Autoplay | Volume adjusting | Preload | | --- | --- | --- | --- | --- | --- | | Chrome (Android) | 69+ | Y | Y | Y | Y | | Firefox (Android) | 62+ | Y | Y | Y | Y | | Edge Mobile | | Y | Y | Y | Y | | Opera Mobile | 46+ | Y | Y | Y | Y | | Safari (iOS) | 7+ | Y/N\* | N | N | Y | | Android Browser | 67+ | Y | Y | Y | Y | There's a full compatibility chart for mobile and desktop HTMLMediaElement support here. **Note:** Concurrent audio playback is tested using our concurrent audio test example, where we attempt to play three pieces of audio at the same time using the standard audio API. **Note:** Simple autoplay functionality is tested with our autoplay test example. **Note:** Volume changeability is tested with our volume test example. Mobile workarounds ------------------ Although mobile browsers can present problems, there are ways to work around the issues detailed above. ### Audio sprites Audio sprites borrow their name from CSS sprites, which is a visual technique for using CSS with a single graphic resource to break it into a series of sprites. We can apply the same principle to audio so that rather than having a bunch of small audio files that take time to load and play, we have one larger audio file containing all the smaller audio snippets we need. To play a specific sound from the file, we just use the known start and stop times for each audio sprite. The advantage is that we can prime one piece of audio and have our sprites ready to go. To do this we can just play and instantly pause the larger piece of audio. You'll also reduce the number of server requests and save bandwidth. ```js const myAudio = document.createElement("audio"); myAudio.src = "mysprite.mp3"; myAudio.play(); myAudio.pause(); ``` You'll need to sample the current time to know when to stop. If you space your individual sounds by at least 500ms then using the `timeUpdate` event (which fires every 250ms) should be sufficient. Your files may be slightly longer than they strictly need to be, but silence compresses well. Here's an example of an audio sprite player — first let's set up the user interface in HTML: ```html <audio id="myAudio" src="http://jPlayer.org/tmp/countdown.mp3"></audio> <button data-start="18" data-stop="19">0</button> <button data-start="16" data-stop="17">1</button> <button data-start="14" data-stop="15">2</button> <button data-start="12" data-stop="13">3</button> <button data-start="10" data-stop="11">4</button> <button data-start="8" data-stop="9">5</button> <button data-start="6" data-stop="7">6</button> <button data-start="4" data-stop="5">7</button> <button data-start="2" data-stop="3">8</button> <button data-start="0" data-stop="1">9</button> ``` Now we have buttons with start and stop times in seconds. The "countdown.mp3" MP3 file consists of a number being spoken every 2 seconds, the idea being that we play back that number when the corresponding button is pressed. Let's add some JavaScript to make this work: ```js const myAudio = document.getElementById("myAudio"); const buttons = document.getElementsByTagName("button"); let stopTime = 0; for (const button of buttons) { button.addEventListener( "click", () => { myAudio.currentTime = button.getAttribute("data-start"); stopTime = button.getAttribute("data-stop"); myAudio.play(); }, false, ); } myAudio.addEventListener( "timeupdate", () => { if (myAudio.currentTime > stopTime) { myAudio.pause(); } }, false, ); ``` **Note:** You can try out our audio sprite player live on JSFiddle. **Note:** On mobile we may need to trigger this code from a user-initiated event such as a start button being pressed, as described above. **Note:** Watch out for bit rates. Encoding your audio at lower bit rates means smaller file sizes but lower seeking accuracy. ### Background music Music in games can have a powerful emotional effect. You can mix and match various music samples and assuming you can control the volume of your audio element you could cross-fade different musical pieces. Using the `playbackRate()` method you can even adjust the speed of your music without affecting the pitch, to sync it up better with the action. All this is possible using the standard `<audio>` element and associated `HTMLMediaElement`, but it becomes much easier and more flexible with the more advanced Web Audio API. Let's look at this next. ### Web Audio API for games The Web Audio API is supported across all modern desktop and mobile browsers, except for Opera Mini. With that in mind, it's an acceptable approach for many situations to use the Web Audio API (see the Can I use Web Audio API page for more on browser compatibility). The Web Audio API is an advanced audio JavaScript API that is ideal for game audio. Developers can generate audio and manipulate audio samples as well as positioning sound in 3D game space. A feasible cross-browser strategy would be to provide basic audio using the standard `<audio>` element and, where supported, enhance the experience using the Web Audio API. **Note:** Significantly, iOS Safari now supports the Web Audio API, which means it's now possible to write web-based games with native-quality audio for iOS. As the Web Audio API allows precise timing and control of audio playback, we can use it to play samples at specific moments, which is a crucial immersive aspect of gaming. You want those explosions to be accompanied by a thundering boom, not followed by one, after all. ### Background music with the Web Audio API Although we can use the `<audio>` element to deliver linear background music that doesn't change in reaction to the game environment, the Web Audio API is ideal for implementing a more dynamic musical experience. You may want music to change depending on whether you are trying to build suspense or encourage the player in some way. Music is an important part of the gaming experience and depending on the type of game you are making you may wish to invest significant effort into getting it right. One way you can make your music soundtrack more dynamic is by splitting it up into component loops or tracks. This is often the way that musicians compose music anyway, and the Web Audio API is extremely good at keeping these parts in sync. Once you have the various tracks that make up your piece you can bring tracks in and out as appropriate. You can also apply filters or effects to music. Is your character in a cave? Increase the echo. Maybe you have underwater scenes, during which you could apply a filter that muffles the sound. Let's look at some Web Audio API techniques for dynamically adjusting music from its base tracks. ### Loading your tracks With the Web Audio API you can load separate tracks and loops individually using the Fetch API or `XMLHttpRequest`, which means you can load them synchronously or in parallel. Loading synchronously might mean parts of your music are ready earlier and you can start playing them while others load. Either way you may want to synchronize tracks or loops. The Web Audio API contains the notion of an internal clock that starts ticking the moment you create an audio context. You'll need to take account of the time between creating an audio context and when the first audio track starts playing. Recording this offset and querying the playing track's current time gives you enough information to synchronize separate pieces of audio. To see this in action, let's lay out some separate tracks: ```html <section id="tracks"> <ul> <li data-loading="true"> <a href="leadguitar.mp3" class="track">Lead Guitar</a> <p class="loading-text">Loading…</p> <button data-playing="false" aria-describedby="guitar-play-label"> <span id="guitar-play-label">Play</span> </button> </li> <li data-loading="true"> <a href="bassguitar.mp3" class="track">Bass Guitar</a> <p class="loading-text">Loading…</p> <button data-playing="false" aria-describedby="bass-play-label"> <span id="bass-play-label">Play</span> </button> </li> <li data-loading="true"> <a href="drums.mp3" class="track">Drums</a> <p class="loading-text">Loading…</p> <button data-playing="false" aria-describedby="drums-play-label"> <span id="drums-play-label">Play</span> </button> </li> <li data-loading="true"> <a href="horns.mp3" class="track">Horns</a> <p class="loading-text">Loading…</p> <button data-playing="false" aria-describedby="horns-play-label"> <span id="horns-play-label">Play</span> </button> </li> <li data-loading="true"> <a href="clav.mp3" class="track">Clavi</a> <p class="loading-text">Loading…</p> <button data-playing="false" aria-describedby="clavi-play-label"> <span id="clavi-play-label">Play</span> </button> </li> </ul> <p class="sourced"> All tracks sourced from <a href="https://jplayer.org/">jplayer.org</a> </p> </section> ``` All of these tracks are the same tempo and are designed to be synchronized with each other, so we need to make sure they are loaded and available to the API *before* we are able to play them. We can do this with JavaScript's `async`/`await` functionality. Once they are available to play, we need to make sure they start at the correct point that other tracks might be playing at, so they sync up. Let's create our audio context: ```js const audioCtx = new AudioContext(); ``` Now let's select all the `<li>` elements; later we can harness these elements to give us access to the track file path and each individual play button. ```js const trackEls = document.querySelectorAll("li"); ``` We want to make sure each file has loaded and been decoded into a buffer before we use it, so let's create an `async` function to allow us to do this: ```js async function getFile(filepath) { const response = await fetch(filepath); const arrayBuffer = await response.arrayBuffer(); const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer); return audioBuffer; } ``` We can then use the `await` operator when calling this function, which ensures that we can run subsequent code when it has finished executing. Let's create another `async` function to set up the sample — we can combine the two async functions in a nice promise pattern to perform further actions when each file is loaded and buffered: ```js async function loadFile(filePath) { const track = await getFile(filePath); return track; } ``` Let's also create a `playTrack()` function, which we can call once a file has been fetched. We need an offset here, so if we have started one file playing, we have a record of how far through to start another file. `start()` takes two optional parameters. The first is when to commence playback and the second is where, which is our offset. ```js let offset = 0; function playTrack(audioBuffer) { const trackSource = audioCtx.createBufferSource(); trackSource.buffer = audioBuffer; trackSource.connect(audioCtx.destination); if (offset === 0) { trackSource.start(); offset = audioCtx.currentTime; } else { trackSource.start(0, audioCtx.currentTime - offset); } return trackSource; } ``` Finally, let's loop over our `<li>` elements, grab the correct file for each one and then allow playback by hiding the "loading" text and displaying the play button: ```js trackEls.forEach((el, i) => { // Get children const anchor = el.querySelector("a"); const loadText = el.querySelector("p"); const playButton = el.querySelector("button"); // Load file loadFile(anchor.href).then((track) => { // Set loading to false el.dataset.loading = "false"; // Hide loading text loadText.style.display = "none"; // Show button playButton.style.display = "inline-block"; // Allow play on click playButton.addEventListener("click", () => { // Check if context is in suspended state (autoplay policy) if (audioCtx.state === "suspended") { audioCtx.resume(); } playTrack(track); playButton.dataset.playing = true; }); }); }); ``` **Note:** You can see this demo in action here and view the source code here. In the context of your game world you may have loops and samples that are played in different circumstances, and it can be useful to be able to synchronize with other tracks for a more seamless experience. **Note:** This example does not wait for the beat to end before introducing the next piece; we could do this if we knew the BPM (Beats Per Minute) of the tracks. You may find that the introduction of a new track sounds more natural if it comes in on the beat/bar/phrase or whatever units you want to chunk your background music into. To do this before playing the track you want to sync, you should calculate how long it is until the start of the next beat/bar etc. Here's a bit of code that given a tempo (the time in seconds of your beat/bar) will calculate how long to wait until you play the next part — you feed the resulting value to the `start()` function with the first parameter, which takes the absolute time of when that playback should commence. Note the second parameter (where to start playing from in the new track) is relative: ```js if (offset === 0) { source.start(); offset = context.currentTime; } else { const relativeTime = context.currentTime - offset; const beats = relativeTime / tempo; const remainder = beats - Math.floor(beats); const delay = tempo - remainder \* tempo; source.start(context.currentTime + delay, relativeTime + delay); } ``` **Note:** You can try our wait calculator code here, on JSFiddle (I've synched to the bar in this case). **Note:** If the first parameter is 0 or less than the context `currentTime`, playback will commence immediately. ### Positional audio Positional audio can be an important technique in making audio a key part of an immersive gaming experience. The Web Audio API not only enables us to position a number of audio sources in three-dimensional space but it can also allow us to apply filters that make that audio appear more realistic. The `pannerNode` harnesses the positional capabilities of the Web Audio API so we can relate further information about the game world to the player. There's a tutorial here to help understand the `pannerNode` in better detail. We can relate: * The position of objects * The direction and movement of objects * The environment (cavernous, underwater, etc.) This is especially useful in a three-dimensional environment rendered using WebGL, where the Web Audio API makes it possible to tie audio to the objects and viewpoints. See also -------- * Web Audio API on MDN * `<audio>` on MDN * Songs of Diridum: Pushing the Web Audio API to Its Limits * Making HTML5 Audio Actually Work on Mobile * Audio Sprites (and fixes for iOS)
WebRTC data channels - Game development
WebRTC data channels ==================== The WebRTC (Web Real-Time Communications) API is primarily known for its support for audio and video communications; however, it also offers peer-to-peer data channels. This article explains more about this, and shows you how to use libraries to implement data channels in your game. What is a data channel? ----------------------- A WebRTC data channel lets you send text or binary data over an active connection to a peer. In the context of a game, this lets players send data to each other, whether text chat or game status information. Data channels come in two flavors. **Reliable channels** guarantee that messages you send arrive at the other peer and in the same order in which they're sent. This is analogous to a TCP socket. **Unreliable channels** make no such guarantees; messages aren't guaranteed to arrive in any particular order and, in fact, aren't guaranteed to arrive at all. This is analogous to a UDP socket. We have documentation for using WebRTC. This article, however, will take advantage of some libraries that can help trivialize the work, and will demonstrate ways to use abstraction to work around implementation differences between browsers. Hopefully, of course, those differences will fade away in time. Using the p2p library --------------------- One library you can use is the p2p library. This library provides a simple API for creating peer connections and setting up streams and data channels. There's also a broker server component and a hosted broker you can use instead of having to set one up for yourself. **Note:** We will continue to add content here soon; there are some organizational issues to sort out. Original Document Information ----------------------------- * Author(s): Alan Kligman * Source Article: WebRTC Data Channels for Great Multiplayer * Other Contributors: Robert Nyman * Copyright Information: Alan Kligman, 2013
3D collision detection - Game development
3D collision detection ====================== This article provides an introduction to the different bounding volume techniques used to implement collision detection in 3D environments. Followup articles will cover implementations in specific 3D libraries. Axis-aligned bounding boxes --------------------------- As with 2D collision detection, **axis-aligned bounding boxes** (AABB) are the quickest algorithm to determine whether the two game entities are overlapping or not. This consists of wrapping game entities in a non-rotated (thus axis-aligned) box and checking the positions of these boxes in the 3D coordinate space to see if they are overlapping. ![Two 3-D non-square objects floating in space encompassed by virtual rectangular boxes.](/en-US/docs/Games/Techniques/3D_collision_detection/screen_shot_2015-10-16_at_15.11.21.png) The **axis-aligned constraint** is there because of performance reasons. The overlapping area between two non-rotated boxes can be checked with logical comparisons alone, whereas rotated boxes require additional trigonometric operations, which are slower to calculate. If you have entities that will be rotating, you can either modify the dimensions of the bounding box so it still wraps the object, or opt to use another bounding geometry type, such as spheres (which are invariant to rotation.) The animated GIF below shows a graphic example of an AABB that adapts its size to fit the rotating entity. The box constantly changes dimensions to snugly fit the entity contained inside. ![Animated rotating knot showing the virtual rectangular box shrink and grow as the knots rotates within it. The box does not rotate.](/en-US/docs/Games/Techniques/3D_collision_detection/rotating_knot.gif) **Note:** Check out the Bounding Volumes with Three.js article to see a practical implementation of this technique. ### Point vs. AABB Checking if a point is inside an AABB is pretty simple — we just need to check whether the point's coordinates fall inside the AABB; considering each axis separately. If we assume that *Px*, *Py* and *Pz* are the point's coordinates, and *BminX*–*BmaxX*, *BminY*–*BmaxY*, and *BminZ*–*BmaxZ* are the ranges of each axis of the AABB, we can calculate whether a collision has occurred between the two using the following formula: f ( P , B ) = ( P x ≥ B m i n X ∧ P x ≤ B m a x X ) ∧ ( P y ≥ B m i n Y ∧ P y ≤ B m a x Y ) ∧ ( P z ≥ B m i n Z ∧ P z ≤ B m a x Z ) f(P, B)= (P\_x \ge B\_{minX} \wedge P\_x \le B\_{maxX}) \wedge (P\_y \ge B\_{minY} \wedge P\_y \le B\_{maxY}) \wedge (P\_z \ge B\_{minZ} \wedge P\_z \le B\_{maxZ}) Or in JavaScript: ```js function isPointInsideAABB(point, box) { return ( point.x >= box.minX && point.x <= box.maxX && point.y >= box.minY && point.y <= box.maxY && point.z >= box.minZ && point.z <= box.maxZ ); } ``` ### AABB vs. AABB Checking whether an AABB intersects another AABB is similar to the point test. We just need to do one test per axis, using the boxes' boundaries. The diagram below shows the test we'd perform over the X-axis — basically, do the ranges *AminX*–*AmaxX* and *BminX*–*BmaxX* overlap? ![Hand drawing of two rectangles showing the upper right corner of A overlapping the bottom left corner of B, as A's largest x coordinate is greater than B's smallest x coordinate.](/en-US/docs/Games/Techniques/3D_collision_detection/aabb_test.png) Mathematically this would look like so: f ( A , B ) = ( A m i n X ≤ B m a x X ∧ A m a x X ≥ B m i n X ) ∧ ( A m i n Y ≤ B m a x Y ∧ A m a x Y ≥ B m i n Y ) ∧ ( A m i n Z ≤ B m a x Z ∧ A m a x Z ≥ B m i n Z ) f(A, B) = (A\_{minX} \le B\_{maxX} \wedge A\_{maxX} \ge B\_{minX}) \wedge ( A\_{minY} \le B\_{maxY} \wedge A\_{maxY} \ge B\_{minY}) \wedge (A\_{minZ} \le B\_{maxZ} \wedge A\_{maxZ} \ge B\_{minZ}) And in JavaScript, we'd use this: ```js function intersect(a, b) { return ( a.minX <= b.maxX && a.maxX >= b.minX && a.minY <= b.maxY && a.maxY >= b.minY && a.minZ <= b.maxZ && a.maxZ >= b.minZ ); } ``` Bounding spheres ---------------- Using bounding spheres to detect collisions is a bit more complex than AABB, but still fairly quick to test. The main advantage of spheres is that they are invariant to rotation, so if the wrapped entity rotates, the bounding sphere would still be the same. Their main disadvantage is that unless the entity they are wrapping is actually spherical, the wrapping is usually not a good fit (i.e. wrapping a person with a bounding sphere will cause a lot of false positives, whereas an AABB would be a better match). ### Point vs. sphere To check whether a sphere contains a point we need to calculate the distance between the point and the sphere's center. If this distance is smaller than or equal to the radius of the sphere, the point is inside the sphere. ![Hand drawing of a 2D projection of a sphere and a point in a Cartesian coordinate system. The point is outside of the circle, to the lower right of it. The distance is denoted by a dashed line, labeled D, from the circle's center to the point. A lighter line shows the radius, labeled R, going from the center of the circle to the border of the circle.](/en-US/docs/Games/Techniques/3D_collision_detection/point_vs_sphere.png) Taking into account that the Euclidean distance between two points *A* and *B* is ( A x − B x ) 2 + ( A y − B y ) 2 + ( A z − B z ) 2 \sqrt{(A\_x - B\_x)^2 + (A\_y - B\_y)^2 + (A\_z - B\_z)^2} , our formula for point vs. sphere collision detection would work out like so: f ( P , S ) = S r a d i u s ≥ ( P x − S x ) 2 + ( P y − S y ) 2 + ( P z − S z ) 2 f(P,S) = S\_{radius} \ge \sqrt{(P\_x - S\_x)^2 + (P\_y - S\_y)^2 + (P\_z - S\_z)^2} Or in JavaScript: ```js function isPointInsideSphere(point, sphere) { // we are using multiplications because is faster than calling Math.pow const distance = Math.sqrt( (point.x - sphere.x) \* (point.x - sphere.x) + (point.y - sphere.y) \* (point.y - sphere.y) + (point.z - sphere.z) \* (point.z - sphere.z), ); return distance < sphere.radius; } ``` **Note:** The code above features a square root, which can be expensive to calculate. An easy optimization to avoid it consists of comparing the squared distance with the squared radius, so the optimized equation would instead involve `distanceSqr < sphere.radius * sphere.radius`. ### Sphere vs. sphere The sphere vs. sphere test is similar to the point vs. sphere test. What we need to test here is that the distance between the sphere's centers is less than or equal to the sum of their radii. ![Hand drawing of two partially overlapping circles. Each circle (of different sizes) has a light radius line going from its center to its border, labeled R. The distance is denoted by a dotted line, labeled D, connecting the center points of both circles.](/en-US/docs/Games/Techniques/3D_collision_detection/sphere_vs_sphere.png) Mathematically, this looks like: f ( A , B ) = ( A x − B x ) 2 + ( A y − B y ) 2 + ( A z − B z ) 2 ≤ A r a d i u s + B r a d i u s f(A,B) = \sqrt{(A\_x - B\_x)^2 + (A\_y - B\_y)^2 + (A\_z - B\_z)^2} \le A\_{radius} + B\_{radius} Or in JavaScript: ```js function intersect(sphere, other) { // we are using multiplications because it's faster than calling Math.pow const distance = Math.sqrt( (sphere.x - other.x) \* (sphere.x - other.x) + (sphere.y - other.y) \* (sphere.y - other.y) + (sphere.z - other.z) \* (sphere.z - other.z), ); return distance < sphere.radius + other.radius; } ``` ### Sphere vs. AABB Testing whether a sphere and an AABB are colliding is slightly more complicated, but still simple and fast. A logical approach would be to check every vertex of the AABB, doing a point vs. sphere test for each one. This is overkill, however — testing all the vertices is unnecessary, as we can get away with just calculating the distance between the AABB's *closest point* (not necessarily a vertex) and the sphere's center, seeing if it is less than or equal to the sphere's radius. We can get this value by clamping the sphere's center to the AABB's limits. ![Hand drawing of a square partially overlapping the top of a circle. The radius is denoted by a light line labeled R. The distance line goes from the circle's center to the closest point of the square.](/en-US/docs/Games/Techniques/3D_collision_detection/sphere_vs_aabb.png) In JavaScript, we'd do this test like so: ```js function intersect(sphere, box) { // get box closest point to sphere center by clamping const x = Math.max(box.minX, Math.min(sphere.x, box.maxX)); const y = Math.max(box.minY, Math.min(sphere.y, box.maxY)); const z = Math.max(box.minZ, Math.min(sphere.z, box.maxZ)); // this is the same as isPointInsideSphere const distance = Math.sqrt( (x - sphere.x) \* (x - sphere.x) + (y - sphere.y) \* (y - sphere.y) + (z - sphere.z) \* (z - sphere.z), ); return distance < sphere.radius; } ``` Using a physics engine ---------------------- **3D physics engines** provide collision detection algorithms, most of them based on bounding volumes as well. The way a physics engine works is by creating a **physical body**, usually attached to a visual representation of it. This body has properties such as velocity, position, rotation, torque, etc., and also a **physical shape**. This shape is the one that is considered in the collision detection calculations. We have prepared a live collision detection demo (with source code) that you can take a look at to see such techniques in action — this uses the open-source 3D physics engine cannon.js. See also -------- Related articles on MDN: * Bounding volumes collision detection with Three.js * 2D collision detection External resources: * Simple intersection tests for games on Game Developer * Bounding volume on Wikipedia
Implementing game control mechanisms - Game development
Implementing game control mechanisms ==================================== One of HTML5's main advantages as a game development platform is the ability to run on various platforms and devices. Streamlining cross device differences creates multiple challenges, not least when providing appropriate controls for different contexts. In this series of articles we will show you how you can approach building a game that can be played using touchscreen smartphones, mouse and keyboard, and also less common mechanisms such as gamepads. Case study ---------- We'll be using the Captain Rogers: Battle at Andromeda demo as an example. ![Captain Rogers: Battle at Andromeda - cover of the game containing Enclave Games and Blackmoon Design logos, Roger's space ship and title of the game.](/en-US/docs/Games/Techniques/Control_mechanisms/captainrogers2-cover.png) Captain Rogers was created using the Phaser framework, the most popular tool for simple 2D game development in JavaScript right now, but it should be fairly easy to reuse the knowledge contained within these articles when building games in pure JavaScript or any other framework. If you're looking for a good introduction to Phaser, then check the 2D breakout game using Phaser tutorial. In the following articles we will show how to implement various different control mechanisms for Captain Rogers to support different platforms — from touch on mobile, through keyboard/mouse/gamepad on desktop, to more unconventional ones like TV remote, shouting to or waving your hand in front of the laptop, or squeezing bananas. Setting up the environment -------------------------- Let's start with a quick overview of the game's folder structure, JavaScript files and in-game states, so we know what's happening where. The game's folders look like this: ![Captain Rogers: Battle at Andromeda - folder structure of the games' project containing JavaScript sources, images and fonts.](/en-US/docs/Games/Techniques/Control_mechanisms/captainrogers2-folderstructure.png) As you can see there are folders for images, JavaScript files, fonts and sound effects. The `src` folder contains the JavaScript files split as a separate states — `Boot.js`, `Preloader.js`, `MainMenu.js` and `Game.js` — these are loaded into the index file in this exact order. The first one initializes Phaser, the second preloads all the assets, the third one controls the main menu welcoming the player, and the fourth controls the actual gameplay. Every state has its own default methods: `preload()`, `create()`, and `update()`. The first one is needed for preloading required assets, `create()` is executed once the state had started, and `update()` is executed on every frame. For example, you can define a button in the `create()` function: ```js create() { // … const buttonEnclave = this.add.button(10, 10, 'logo-enclave', this.clickEnclave, this); // … } ``` It will be created once at the start of the game, and will execute `this.clickEnclave()` action assigned to it when clicked, but you can also use the mouse's pointer value in the `update()` function to make an action: ```js update() { // … if (this.game.input.mousePointer.isDown) { // do something } // … } ``` This will be executed whenever the mouse button is pressed, and it will be checked against the input's `isDown` boolean variable on every frame of the game. That should give you some understanding of the project structure. We'll be playing mostly with the `MainMenu.js` and `Game.js` files, and we'll explain the code inside the `create()` and `update()` methods in much more detail in later articles. Pure JavaScript demo -------------------- There's also a small online demo with full source code available on GitHub where the basic support for the control mechanisms described in the articles is implemented in pure JavaScript. It will be explained in the given articles themselves below, but you can play with it already, and use the code however you want for learning purposes. The articles ------------ JavaScript is the perfect choice for mobile gaming because of HTML being truly multiplatform; all of the following articles focus on the APIs provided for interfacing with different control mechanisms: 1. Mobile touch controls — The first article will kick off with touch, as the mobile first approach is very popular. 2. Desktop mouse and keyboard controls — When playing on a desktop/laptop computer, providing keyboard and mouse controls is essential to provide an acceptable level of accessibility for the game. 3. Desktop gamepad controls — The Gamepad API rather usefully allows gamepads to be used for controlling web apps on desktop/laptop, for that console feel. 4. Unconventional controls — The final article showcases some unconventional control mechanisms, from the experimental to the slightly crazy, which you might not believe could be used to play the game.
Square tilemaps implementation: Static maps - Game development
Square tilemaps implementation: Static maps =========================================== This article covers how to implement static square tilemaps using the Canvas API. **Note:** When writing this article, we assumed previous reader knowledge of canvas basics such as how get a 2D canvas context, load images, etc., which is all explained in the Canvas API tutorial, as well as the basic information included in our Tilemaps introduction article. The tile atlas -------------- A tilemap might use one or several atlases — or spritesheets — that contain all of the tile images. This is the atlas we will be using as an example, which features five different tiles: ![Tiles packaged in an atlas](/en-US/docs/Games/Techniques/Tilemaps/Square_tilemaps_implementation:_Static_maps/tiles.png) To draw a tile from the atlas into the canvas we make use of the `drawImage()` method in a canvas 2D context. We need to supply the atlas image, the coordinates and dimensions of the tile inside the atlas, and the target coordinates and size (a different tile size in here would scale the tile.) So, for instance, to draw the tree tile, which is the third in the atlas, at the screen coordinates `(128, 320)`, we would call `drawImage()` with these values: ```js context.drawImage(atlasImage, 192, 0, 64, 64, 128, 320, 64, 64); ``` In order to support atlases with multiple rows and columns, you would need to know how many rows and columns there are to be able to compute the source `x` and `y`. The tilemap data structure -------------------------- To store that map data, we can use a plain object or a custom class. For the sake of simplicity, in the example code a plain object has been used. It contains the basic map properties: * `cols`: The width of the map, in columns. * `rows`: The height of the map, in rows. * `tsize`: The tile size, in pixels. * `tiles`: A 1-dimensional array containing the visual grid. * `getTile()`: A helper method that gets the tile index in a certain position. `tiles` contains the actual visual map data. We are representing the tiles with indices, assigned to the tiles dependent on their position in the atlas (e.g. `0` for the left-most tile.) However, we must account for **empty tiles**, since they are crucial for implementing layers — empty tiles are usually assigned a negative index value, `0`, or a null value. In these examples, empty tiles will be represented by index `0`, so we will shift the indices of the atlases by one (and thus the first tile of the atlas will be assigned index `1`, the second index `2`, etc.) The `getTile()` helper method returns the tile contained at the specified column and row. If `tiles` were a 2D matrix, then the returned value would just be `tiles[column][row]`. However, it's usually more common to represent the grid with a 1-dimensional array. In this case, we need to map the column and row to an array index: ```js const index = row \* map.cols + column; ``` Wrapping up, an example of a tilemap object could look like the following. This features an 8 x 8 map with tiles 64 x 64 pixels in size: ```js const map = { cols: 8, rows: 8, tsize: 64, tiles: [ 1, 3, 3, 3, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, ], getTile(col, row) { return this.tiles[row \* map.cols + col]; }, }; ``` Rendering the map ----------------- We can render the map by iterating over its columns and rows. This snippet assumes the following definitions: * `context`: A 2D canvas context. * `tileAtlas`: An image object containing the tile atlas. * `map`: The tilemap object discussed above. ```js for (let c = 0; c < map.cols; c++) { for (let r = 0; r < map.rows; r++) { const tile = map.getTile(c, r); if (tile !== 0) { // 0 => empty tile context.drawImage( tileAtlas, // image (tile - 1) \* map.tsize, // source x 0, // source y map.tsize, // source width map.tsize, // source height c \* map.tsize, // target x r \* map.tsize, // target y map.tsize, // target width map.tsize, // target height ); } } } ``` Demo ---- Our static tilemap implementation demo pulls the above code together to show what an implementation of this map looks like. You can see a live demo and grab the full source code. ![Aerial view of a field with trees, grass, and ground made from repeated sections of the tilemap.](/en-US/docs/Games/Techniques/Tilemaps/Square_tilemaps_implementation:_Static_maps/no-scroll.png)
Square tilemaps implementation: Scrolling maps - Game development
Square tilemaps implementation: Scrolling maps ============================================== This article covers how to implement scrolling square tilemaps using the Canvas API. **Note:** When writing this article, we assumed previous reader knowledge of canvas basics such as how get a 2D canvas context, load images, etc., which is all explained in the Canvas API tutorial, as well as the basic information included in our Tilemaps introduction article. This article also builds upon implementing static square tilemaps — you should read that too if you've not done so already. The camera ---------- The camera is an object that holds information about which section of the game world or level is currently being shown. Cameras can either be free-form, controlled by the player (such as in strategy games) or follow an object (such as the main character in platform games.) Regardless of the type of camera, we would always need information regarding its current position, viewport size, etc. In the demo provided along with this article, these are the parameters the camera has: * `x` and `y`: The current position of the camera. In this implementation, we are assuming that `(x,y)` points to the top left corner of visible portion of the map. * `width` and `height`: The size of the camera's viewport. * `maxX` and `maxY`: The limit for the camera's position — The lower limit will nearly always be (0,0), and in this case the upper limit is equal to the size of the world minus the size of the camera's viewport. Rendering the map ----------------- There are two main differences between rendering scrolling maps vs. static maps: * **Partial tiles might be shown**. In static maps, usually the rendering starts in the top left corner of a tile situated in the top left corner of a viewport. While rendering scrolling tilemaps, the first tile will often be clipped. * **Only a section of the map will be rendered**. If the map is bigger than the viewport, we can obviously only display a part of it at a time, whereas non-scrolling maps are usually rendered wholly. To handle these issues, we need to slightly modify the rendering algorithm. Let's imagine that we have the camera pointing at `(5,10)`. That means that the first tile would be `0x0`. In the demo code, the starting point is stored at `startCol` and `startRow`. It's convenient to also pre-calculate the last tile to be rendered. ```js const startCol = Math.floor(this.camera.x / map.tsize); const endCol = startCol + this.camera.width / map.tsize; const startRow = Math.floor(this.camera.y / map.tsize); const endRow = startRow + this.camera.height / map.tsize; ``` Once we have the first tile, we need to calculate how much its rendering (and therefore the rendering of the other tiles) is offset by. Since the camera is pointing at `(5, 10)`, we know that the first tile should be shifted by `(-5,-10)` pixels. In our demo the shifting amount is stored in the `offsetX` and `offsetY` variables. ```js const offsetX = -this.camera.x + startCol \* map.tsize; const offsetY = -this.camera.y + startRow \* map.tsize; ``` With these values in place, the loop that renders the map is quite similar to the one used for rendering static tilemaps. The main difference is that we are adding the `offsetX` and `offsetY` values to the target `x` and `y` coordinates, and these values are rounded, to avoid artifacts that would result from the camera pointing at positions with floating point numbers. ```js for (let c = startCol; c <= endCol; c++) { for (let r = startRow; r <= endRow; r++) { const tile = map.getTile(c, r); const x = (c - startCol) \* map.tsize + offsetX; const y = (r - startRow) \* map.tsize + offsetY; if (tile !== 0) { // 0 => empty tile this.ctx.drawImage( this.tileAtlas, // image (tile - 1) \* map.tsize, // source x 0, // source y map.tsize, // source width map.tsize, // source height Math.round(x), // target x Math.round(y), // target y map.tsize, // target width map.tsize, // target height ); } } } ``` Demo ---- Our scrolling tilemap implementation demo pulls the above code together to show what an implementation of this map looks like. You can take a look at a live demo, and see its source code. ![Animated gif of a section grass, dirt areas, and trees made from repeated sections of a tilemap showing how you see different sections of the area when you scroll.](/en-US/docs/Games/Techniques/Tilemaps/Square_tilemaps_implementation:_Scrolling_maps/untitled.gif) There's another demo available, that shows how to make the camera follow a character.
WebXR — Virtual and Augmented Reality for the Web - Game development
WebXR — Virtual and Augmented Reality for the Web ================================================= The concepts of virtual reality (VR) and augmented reality (AR) aren't new, but the technology is more accessible than ever. We can also use a JavaScript API to make use of it in web applications. This article introduces WebXR from the perspective of its use in games. **Note:** You may see references to the non-standard WebVR API. WebVR was never ratified as a standard, was implemented and enabled by default in very few browsers, and supported only a few devices. The **WebVR** API is replaced by the **WebXR** Device API. VR devices ---------- With the popularity of existing VR headsets such as Meta Quest, Valve Index, and PlayStation VR, the future looks bright — we already have sufficient technology to create meaningful VR gaming experiences. ![Three different VR devices: the Meta Quest 3, the Valve Index, and the Sony PSVR2.](/en-US/docs/Games/Techniques/3D_on_the_web/WebXR/hmds.jpg) ### Development of WebVR The WebVR spec, led by Vladimir Vukicevic from Mozilla and Brandon Jones from Google, is being replaced by the WebXR Device API. WebVR may still be available in some browsers while WebXR is finalized. For more info, see the WebVR.info website. The WebXR API ------------- The core of any WebXR experience is built on top of two foundational concepts: 1. The application must receive real-time data about your headset's position and your controllers' positions in three-dimensional space 2. The application must render a real-time, stereoscopic view to the headset's display(s) according to that positional data The WebXR API is the central API for capturing information about XR devices connected to a computer. The API can capture headset and controller position, orientation, velocity, acceleration, and other information that you can use in your games. There are other APIs useful for creating games such as the Gamepad API for non-XR controller inputs and the Device Orientation API for handling display orientation. ### Using the WebXR API The best place to start with the WebXR API is with our Fundamentals of WebXR guide. After that, see Starting up and shutting down a WebXR session. Tools and techniques -------------------- A-Frame is a web framework that offers simple building blocks for WebXR, so you can rapidly build and experiment with VR websites and games. You can read MDN's Building up a basic demo with A-Frame tutorial for more details. Separately, Three.js is one of the most popular 3D engines for the web, and it can be used for WebXR games. Check out Three.js' How to create VR content documentation to help you make WebXR games with Three.js. ![A 3D representation of a landscape: it's a pinkish sunset, with a blue mountainous land in the background surrounded by a mirror sea and a darker blue island in the second plan.](/en-US/docs/Games/Techniques/3D_on_the_web/WebXR/sechelt.jpg) Immersion takes priority over gameplay and graphics - you must feel part of the experience. It's not easy to achieve, but it doesn't require realistic images. On the contrary, even basic shapes soaring past at high frame rates can be thrilling if the experience is immersive. Remember: experimenting is key - feel free to go with what works well for your project. The future of WebXR ------------------- Consumer devices are available on the market, and we have JavaScript APIs to support them on the web. As hardware becomes more affordable and the ecosystem matures, developers can focus on building experiences through good UX and UI. It's the perfect time to dive in and experiment with WebXR. See also -------- * WebVR Device API * Fundamentals of WebXR * Building up a basic demo with A-Frame
GLSL Shaders - Game development
GLSL Shaders ============ Shaders use GLSL (OpenGL Shading Language), a special OpenGL Shading Language with syntax similar to C. GLSL is executed directly by the graphics pipeline. There are several kinds of shaders, but two are commonly used to create graphics on the web: Vertex Shaders and Fragment (Pixel) Shaders. Vertex Shaders transform shape positions into 3D drawing coordinates. Fragment Shaders compute the renderings of a shape's colors and other attributes. GLSL is not as intuitive as JavaScript. GLSL is strongly typed and there is a lot of math involving vectors and matrices. It can get very complicated — very quickly. In this article we will make a simple code example that renders a cube. To speed up the background code we will be using the Three.js API. As you may remember from the basic theory article, a vertex is a point in a 3D coordinate system. Vertices may, and usually do, have additional properties. The 3D coordinate system defines space and the vertices help define shapes in that space. Shader types ------------ A shader is essentially a function required to draw something on the screen. Shaders run on a GPU (graphics processing unit), which is optimized for such operations. Using a GPU to deal with shaders offloads some of the number crunching from the CPU. This allows the CPU to focus its processing power on other tasks, like executing code. ### Vertex shaders Vertex shaders manipulate coordinates in a 3D space and are called once per vertex. The purpose of the vertex shader is to set up the `gl_Position` variable — this is a special, global, and built-in GLSL variable. `gl_Position` is used to store the position of the current vertex. The `void main()` function is a standard way of defining the `gl_Position` variable. Everything inside `void main()` will be executed by the vertex shader. A vertex shader yields a variable containing how to project a vertex's position in 3D space onto a 2D screen. ### Fragment shaders Fragment (or texture) shaders define RGBA (red, green, blue, alpha) colors for each pixel being processed — a single fragment shader is called once per pixel. The purpose of the fragment shader is to set up the `gl_FragColor` variable. `gl_FragColor` is a built-in GLSL variable like `gl_Position`. The calculations result in a variable containing the information about the RGBA color. Demo ---- Let's build a simple demo to explain those shaders in action. Be sure to read Three.js tutorial first to grasp the concept of the scene, its objects, and materials. **Note:** Remember that you don't have to use Three.js or any other library to write your shaders — pure WebGL (Web Graphics Library) is more than enough. We've used Three.js here to make the background code a lot simpler and clearer to understand, so you can just focus on the shader code. Three.js and other 3D libraries abstract a lot of things for you — if you wanted to create such an example in raw WebGL, you'd have to write a lot of extra code to actually make it work. ### Environment setup To start with the WebGL shaders you don't need much. You should: * Make sure you are using a modern browser with good WebGL support, such as the latest Firefox or Chrome. * Create a directory to store your experiments in. * Save a copy of the latest minimized Three.js library inside your directory. ### HTML structure Here's the HTML structure we will use. ```html <!doctype html> <html lang="en-US"> <head> <meta charset="utf-8" /> <title>MDN Games: Shaders demo</title> <style> body { margin: 0; padding: 0; font-size: 0; } canvas { width: 100%; height: 100%; } </style> <script src="three.min.js"></script> </head> <body> <script id="vertexShader" type="x-shader/x-vertex"> // vertex shader's code goes here </script> <script id="fragmentShader" type="x-shader/x-fragment"> // fragment shader's code goes here </script> <script> // scene setup goes here </script> </body> </html> ``` It contains some basic information like the document `<title>`, and some CSS to set the `width` and `height` of the `<canvas>` element that Three.js will insert on the page to be the full size of the viewport. The `<script>` element in the `<head>` includes the Three.js library in the page; we will write our code into three script tags in the `<body>` tag: 1. The first one will contain the vertex shader. 2. The second one will contain the fragment shader. 3. The third one will contain the actual JavaScript code generating the scene. Before reading on, copy this code to a new text file and save it in your working directory as `index.html`. We'll create a scene featuring a simple cube in this file to explain how the shaders work. ### The cube's source code Instead of creating everything from scratch we can reuse the Building up a basic demo with Three.js source code of the cube. Most of the components like the renderer, camera, and lights will stay the same, but instead of the basic material we will set the cube's color and position using shaders. Go to the cube.html file on GitHub, copy all the JavaScript code from inside the second `<script>` element, and paste it into the third `<script>` element of the current example. Save and load `index.html` in your browser — you should see a blue cube. ### The vertex shader code Let's continue by writing a simple vertex shader — add the code below inside the body's first `<script>` tag: ```glsl void main() { gl_Position = projectionMatrix \* modelViewMatrix \* vec4(position.x+10.0, position.y, position.z+5.0, 1.0); } ``` The resulting `gl_Position` is calculated by multiplying the model-view and the projection matrices by each vector to get the final vertex position, in each case. **Note:** You can learn more about *model*, *view*, and *projection transformations* from the vertex processing paragraph, and you can also check out the links at the end of this article to learn more about it. Both `projectionMatrix` and `modelViewMatrix` are provided by Three.js and the vector is passed with the new 3D position, which results in the original cube moving 10 units along the `x` axis and 5 units along the `z` axis, translated via a shader. We can ignore the fourth parameter and leave it with the default `1.0` value; this is used to manipulate the clipping of the vertex position in the 3D space, but we don't need in our case. ### The texture shader code Now we'll add the texture shader to the code — add the code below to the body's second `<script>` tag: ```glsl void main() { gl_FragColor = vec4(0.0, 0.58, 0.86, 1.0); } ``` This will set an RGBA color to recreate the current light blue one — the first three float values (ranging from `0.0` to `1.0`) represent the red, green, and blue channels while the fourth one is the alpha transparency (ranging from `0.0` — fully transparent — to 1.0 — fully opaque). ### Applying the shaders To actually apply the newly created shaders to the cube, comment out the `basicMaterial` definition first: ```js // const basicMaterial = new THREE.MeshBasicMaterial({color: 0x0095DD}); ``` Then, create the `shaderMaterial`: ```js const shaderMaterial = new THREE.ShaderMaterial({ vertexShader: document.getElementById("vertexShader").textContent, fragmentShader: document.getElementById("fragmentShader").textContent, }); ``` This shader material takes the code from the scripts and applies it to the object the material is assigned to. Then, in the line that defines the cube we need to replace the `basicMaterial` with the newly created `shaderMaterial`: ```js // const cube = new THREE.Mesh(boxGeometry, basicMaterial); const cube = new THREE.Mesh(boxGeometry, shaderMaterial); ``` Three.js compiles and runs the shaders attached to the mesh to which this material is given. In our case the cube will have both vertex and texture shaders applied. That's it — you've just created the simplest possible shader, congratulations! Here's what the cube should look like: ![Three.js blue cube demo](/en-US/docs/Games/Techniques/3D_on_the_web/GLSL_Shaders/cube.png) It looks exactly the same as the Three.js cube demo but the slightly different position and the same blue color are both achieved using the shader. Final code ---------- ### HTML ```html <script src="https://end3r.github.io/MDN-Games-3D/Shaders/js/three.min.js"></script> <script id="vertexShader" type="x-shader/x-vertex"> void main() { gl\_Position = projectionMatrix \* modelViewMatrix \* vec4(position.x+10.0, position.y, position.z+5.0, 1.0); } </script> <script id="fragmentShader" type="x-shader/x-fragment"> void main() { gl\_FragColor = vec4(0.0, 0.58, 0.86, 1.0); } </script> ``` ### JavaScript ```js const WIDTH = window.innerWidth; const HEIGHT = window.innerHeight; const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(WIDTH, HEIGHT); renderer.setClearColor(0xdddddd, 1); document.body.appendChild(renderer.domElement); const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT); camera.position.z = 50; scene.add(camera); const boxGeometry = new THREE.BoxGeometry(10, 10, 10); const shaderMaterial = new THREE.ShaderMaterial({ vertexShader: document.getElementById("vertexShader").textContent, fragmentShader: document.getElementById("fragmentShader").textContent, }); const cube = new THREE.Mesh(boxGeometry, shaderMaterial); scene.add(cube); cube.rotation.set(0.4, 0.2, 0); function render() { requestAnimationFrame(render); renderer.render(scene, camera); } render(); ``` ### CSS ```css body { margin: 0; padding: 0; font-size: 0; } canvas { width: 100%; height: 100%; } ``` ### Result Conclusion ---------- This article has taught the very basics of shaders. Our example doesn't do much but there are many more cool things you can do with shaders — check out some really cool ones on ShaderToy for inspiration and to learn from their sources. See also -------- * Learning WebGL — for general WebGL knowledge * WebGL Shaders and GLSL at WebGL Fundamentals — for GLSL specific information
Explaining basic 3D theory - Game development
Explaining basic 3D theory ========================== This article explains all of the basic theory that's useful to know when you are getting started working with 3D. Coordinate system ----------------- 3D essentially is all about representations of shapes in a 3D space, with a coordinate system used to calculate their position. ![Coordinate system](/en-US/docs/Games/Techniques/3D_on_the_web/Basic_theory/mdn-games-3d-coordinate-system.png) WebGL uses the right-hand coordinate system — the `x` axis points to the right, the `y` axis points up, and the `z` axis points out of the screen, as seen in the above diagram. Objects ------- Different types of objects are built using vertices. A **Vertex** is a point in space having its own 3D position in the coordinate system and usually some additional information that defines it. Every vertex is described by these attributes: * **Position**: Identifies it in a 3D space (`x`, `y`, `z`). * **Color**: Holds an RGBA value (R, G and B for the red, green, and blue channels, alpha for transparency — all values range from `0.0` to `1.0`). * **Normal:** A way to describe the direction the vertex is facing. * **Texture**: A 2D image that the vertex can use to decorate the surface it is part of instead of a simple color. You can build geometry using this information — here is an example of a cube: ![Cube](/en-US/docs/Games/Techniques/3D_on_the_web/Basic_theory/mdn-games-3d-cube.png) A face of the given shape is a plane between vertices. For example, a cube has 8 different vertices (points in space) and 6 different faces, each constructed out of 4 vertices. A normal defines which way the face is directed in. Also, by connecting the points we're creating the edges of the cube. The geometry is built from a vertex and the face, while material is a texture, which uses a color or an image. If we connect the geometry with the material we will get a mesh. Rendering pipeline ------------------ The rendering pipeline is the process by which images are prepared and output onto the screen. The graphics rendering pipeline takes the 3D objects built from **primitives** described using **vertices**, applies processing, calculates the **fragments** and renders them on the 2D screen as **pixels**. ![Rendering pipeline](/en-US/docs/Games/Techniques/3D_on_the_web/Basic_theory/mdn-games-3d-rendering-pipeline.png) Terminology used in the diagram above is as follows: * A **Primitive**: An input to the pipeline — it's built from vertices and can be a triangle, point or line. * A **Fragment**: A 3D projection of a pixel, which has all the same attributes as a pixel. * A **Pixel**: A point on the screen arranged in the 2D grid, which holds an RGBA color. Vertex and fragment processing are programmable — you can write your own shaders that manipulate the output. Vertex processing ----------------- Vertex processing is about combining the information about individual vertices into primitives and setting their coordinates in the 3D space for the viewer to see. It's like taking a photo of the given scenery you have prepared — you have to place the objects first, configure the camera, and then take the shot. ![Vertex processing](/en-US/docs/Games/Techniques/3D_on_the_web/Basic_theory/mdn-games-3d-vertex-processing.png) There are four stages to this processing: the first one involves arranging the objects in the world, and is called **model transformation**. Then there's **view transformation** which takes care of positioning and setting the orientation of the camera in the 3D space. The camera has three parameters — location, direction, and orientation — which have to be defined for the newly created scene. ![Camera](/en-US/docs/Games/Techniques/3D_on_the_web/Basic_theory/mdn-games-3d-camera.png) **Projection transformation** (also called perspective transformation) then defines the camera settings. It sets up what can be seen by the camera — the configuration includes *field of view*, *aspect ratio* and optional *near* and *far planes*. read the Camera paragraph in the Three.js article to learn about those. ![Camera settings](/en-US/docs/Games/Techniques/3D_on_the_web/Basic_theory/mdn-games-3d-camera-settings.png) The last step is **viewport transformation**, which involves outputting everything for the next step in the rendering pipeline. Rasterization ------------- Rasterization converts primitives (which are connected vertices) to a set of fragments. ![Rasterization](/en-US/docs/Games/Techniques/3D_on_the_web/Basic_theory/mdn-games-3d-rasterization.png) Those fragments — which are 3D projections of the 2D pixels — are aligned to the pixel grid, so eventually they can be printed out as pixels on a 2D screen display during the output merging stage. Fragment processing ------------------- Fragment processing focuses on textures and lighting — it calculates final colors based on the given parameters. ![Fragment processing](/en-US/docs/Games/Techniques/3D_on_the_web/Basic_theory/mdn-games-3d-fragment-processing.png) ### Textures Textures are 2D images used in the 3D space to make the objects look better and more realistic. Textures are combined from single texture elements called texels the same way picture elements are combined from pixels. Applying textures onto objects during the fragment processing stage of the rendering pipeline allows us to adjust it by wrapping and filtering it if necessary. Texture wrapping allows us to repeat the 2D image around the 3D object. Texture filtering is applied when the original resolution or the texture image is different from the displayed fragment — it will be minified or magnified accordingly. ### Lighting The colors we see on the screen is a result of the light source interacting with the surface colors of the object's material. Light might be absorbed or reflected. The standard **Phong Lighting Model** implemented in WebGL has four basic types of lighting: * **Diffuse**: A distant directional light, like the sun. * **Specular**: A point of light, just like a light bulb in a room or a flashlight. * **Ambient**: The constant light applied to everything on the scene. * **Emissive**: The light emitted directly by the object. Output merging -------------- During the output manipulation stage all the fragments of the primitives from the 3D space are transformed into a 2D grid of pixels that are then printed out on the screen display. ![Output merging](/en-US/docs/Games/Techniques/3D_on_the_web/Basic_theory/mdn-games-3d-output-merging.png) During output merging some processing is also applied to ignore information that is not needed — for example the parameters of objects that are outside the screen or behind other objects, and thus not visible, are not calculated. Conclusion ---------- Now you know the basic theory behind 3D manipulation. If you want to move on to practice and see some demos in action, follow up with the tutorials below: * Building up a basic demo with Three.js * Building up a basic demo with Babylon.js * Building up a basic demo with PlayCanvas * Building up a basic demo with A-Frame Go ahead and create some cool cutting-edge 3D experiments yourself!
Building up a basic demo with A-Frame - Game development
Building up a basic demo with A-Frame ===================================== The WebXR and WebGL APIs already enable us to start creating virtual reality (VR) and augmented reality (AR) experiences inside web browsers, but the community is still waiting for tools and libraries to appear, to make this easier. Mozilla's A-Frame framework provides a markup language allowing us to build 3D VR landscapes using a system familiar to web developers, which follows game development coding principles; this is useful for quickly and successfully building prototypes and demos, without having to write a lot of JavaScript or GLSL. This article explains how to get up and running with A-Frame, and how to use it to build up a simple demo. High level overview ------------------- The current version of A-Frame is 0.3.2, which means it's highly experimental, but it already works and you can test it right away in the browser. It runs on desktop, mobile (iOS and Android), and Oculus Rift, Gear VR and HTC Vive. A-Frame is built on top of WebGL, and provides pre-built components to use in applications — models, video players, skyboxes, geometries, controls, animations, cursors, etc. It is based on the entity component system, which is known in the game development world, but it targets web developers with a familiar markup structure, manipulable with JavaScript. The end result is 3D web experiences, which are VR-enabled by default. Environment setup ----------------- Let's start by setting up an environment to create something with A-Frame. We'll then build up a demo and run it. You should start off by: * Making sure you are using a modern browser with good WebGL support (and WebVR support if you have available VR hardware) such as the latest Firefox or Chrome — download Firefox Nightly or Chrome (v54 or higher). * (Optional) set up a VR device such as Oculus Rift or Google Cardboard. * Create a new directory to store your project in. * Save a copy of the latest A-Frame JavaScript library file inside your directory (check the GitHub repository for latest stable a dev builds). * Open the A-Frame documentation in a separate tab — it is useful to refer to. HTML structure -------------- The first step is to create an HTML document — inside your project directory, create a new `index.html` file, and save the follow HTML inside it: ```html <!doctype html> <html lang="en-US"> <head> <meta charset="utf-8" /> <title>MDN Games: A-Frame demo</title> <script src="aframe.min.js"></script> </head> <body> <!-- HTML goes here --> </body> </html> ``` This contains some basic information like the document `charset` and `<title>`. The `<script>` element includes the A-Frame framework in the page; we will write our example code inside the `<body>` element. ### Initializing the scene A scene is the place where everything happens. When creating new objects in the demo, we will be adding them all to the scene to make them visible on the screen. In A-Frame, the scene is represented by a Scene entity. **Note:** An Entity is any element — it can be an object like a box, cylinder or cone, but it can also be a camera, light or sound source. Let's create the scene by adding an `<a-scene>` element inside the `<body>` element: ```html <a-scene></a-scene> ``` ### Adding a cube Adding the cube to the scene is done by adding a simple `<a-box>` element inside the `<a-scene>` element. Add it now: ```html <a-box color="#0095DD" position="0 1 0" rotation="20 40 0"></a-box> ``` It contains a few parameters already defined: `color`, `position` and `rotation` — these are fairly obvious, and define the base color of the cube, the position inside the 3D scene, and the rotation of the cube. **Note:** The distance values (e.g. for the cube y position) are unitless, and can basically be anything you deem suitable for your scene — millimeters, meters, feet, or miles — it's up to you. ### Adding a background: Sky box A sky box is a background for the 3D world, represented by an `<a-sky>` element. In our case we will use a simple color, but it could also be an image, etc. Looking around would give an impression of being inside an open sky, a wooden barn — wherever you like! Add the following HTML before the `<a-cube>` element: ```html <a-sky color="#DDDDDD"></a-sky> ``` At this point, if you save the code and refresh your browser you can already see the cube on the screen with our custom background: ![A 3D representation's illustration of a blue cube displayed on a lighter grey background.](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_A-Frame/cube.png) Here's the code we have created so far: You can also check it out on GitHub. A-Frame takes care of setting up everything you need: * A default light source and camera are included, so the cube is visible. * The controls are already working: you can use the mouse for looking around and the keyboard for movement (try the `W`, `A`, `S`, and `D` keys). * There's even an "Enter VR mode" button in the bottom right corner of the screen, to allow you to shift to full screen, stereoscopic image viewing if you have the necessary VR hardware set up and ready. ### Specifying a camera A camera entity can be created by adding an `<a-camera>` element to the scene. We can set the position of the camera explicitly and move it back a little bit from the center of the scene, so we'll be able to see the shapes. Add this just before the closing `</a-scene>` element: ```html <a-camera position="0 1 4" cursor-visible="true" cursor-scale="2" cursor-color="#0095DD" cursor-opacity="0.5"> </a-camera> ``` We've also defined a cursor for the given camera, using the `cursor-*` attributes (by default it is invisible.) — we've set its scale so it will more easily visible, its color, and some opacity so it won't completely cover the objects behind it. ### Adding lights The basic light types in A-Frame are directional and ambient. The first type is a directional light placed somewhere on the scene while the second one reflects the light from the first type, so it looks more natural; this can be set globally. Add the new code below your previous additions — this uses the standard `<a-light>` element: ```html <a-light type="directional" color="#FFF" intensity="0.5" position="-1 1 2"> </a-light> <a-light type="ambient" color="#FFF"></a-light> ``` The directional light has a white color, its intensity is set to `0.5`, and it is placed at position `-1 1 2`. The ambient light only needs a color, which is also white. ### Adding some advanced geometry We have a cube on the scene already; now let's try adding more shapes. We are not limited to the default entities like `<a-cube>` — using `<a-entity>` we can create custom advanced shapes. Let's try adding a torus — add this element below the previous code: ```html <a-entity geometry=" primitive: torus; radius: 1; radiusTubular: 0.1; segmentsTubular: 12;" rotation="10 0 0" position="-3 1 0"> </a-entity> ``` Our entity has a torus primitive, which represents its shape. We are passing some initial variables to that shape: the radius of the outer edge of the torus, the radius of the tube, and number of segments along the circumference of the tube face respectively. Rotation and position are set in the same way as we saw earlier. ### Defining a material The torus is now visible on the scene, but its color doesn't look very good — this is because we have to create a material to define the appearance of the entity. Edit the `<a-entity>` defining the torus to look like the following: ```html <a-entity geometry=" primitive: torus; radius: 1; radiusTubular: 0.1; segmentsTubular: 12;" material=" color: #EAEFF2; roughness: 0.1; metalness: 0.5;" rotation="10 0 0" position="-3 1 0"> </a-entity> ``` In the new `material` attribute, we set up the `color` of the material, then its `roughness` (a rougher material will scatter reflected light in more directions than a smooth material) and `metalness` (how metallic the material is). Adding some JavaScript to the mix --------------------------------- It is possible to populate the scene with entities created using JavaScript too, so let's use it to add a third shape, a cylinder. Add a new `<script>` element at the end of the `<body>` element, just after the `<a-scene>` element, then add the following JavaScript code inside it: ```js const scene = document.querySelector("a-scene"); const cylinder = document.createElement("a-cylinder"); cylinder.setAttribute("color", "#FF9500"); cylinder.setAttribute("height", "2"); cylinder.setAttribute("radius", "0.75"); cylinder.setAttribute("position", "3 1 0"); scene.appendChild(cylinder); ``` We're getting a reference to the scene handler first, then we create the cylinder element as an A-Frame entity. After that it's all about setting the proper attributes: `color`, `height`, `radius` and `position`. The last line adds the newly created cylinder to the scene. That's it — you've created three different shapes with A-Frame! Here's how it looks right now: ![An illustration of 3D representation of three different geometry shapes displayed on a grey background: the first one is a darker grey torus, the second is a blue cube and the last one is a yellow cylinder.](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_A-Frame/shapes.png) It is impressive to be able to create such a scene with just a few lines of HTML and JavaScript. Animation --------- We've already used `rotation` and `position` to move the shapes on the scene, and we can also scale them. These attributes can be manipulated to create the illusion of animation. ### Rotation There's a special `<a-animation>` entity that can help us animate elements. Add the `<a-animation>` element seen below to the `<a-box>` element as a child, as shown: ```html <a-box color="#0095DD" rotation="20 40 0" position="0 1 0"> <a-animation attribute="rotation" from="20 0 0" to="20 360 0" direction="alternate" dur="4000" repeat="indefinite" easing="ease"> </a-animation> </a-box> ``` As with any other entities, you can define key properties for the animation. We'll be animating the `rotation` attribute from `20 0 0` to `20 360 0`, so it will do a full spin. The animation direction is set to alternate so the animation will be played forward, and then back. The duration is set to 4 seconds, and it will be repeated indefinitely. The animation uses `ease` for easing, with tween.js being implemented internally. ### Scaling We can also add animation to entities with custom geometry like the torus, in much the same way. Add the following `<a-animation>` element to your torus: ```html <a-entity geometry=" primitive: torus; radius: 1; radiusTubular: 0.1; segmentsTubular: 12;" material=" color: #EAEFF2; roughness: 0.1; metalness: 0.5;" rotation="10 0 0" position="-3 1 0"> <a-animation attribute="scale" to="1 0.5 1" direction="alternate" dur="2000" repeat="indefinite" easing="linear"> </a-animation> </a-entity> ``` The attribute we want to animate for the torus is `scale`. The initial, default scale is `1 1 1`, and we're going to animate it to `1 0.5 1`, so the `y` axis will be scaled from `1` to `0.5`. The easing we're going to use is `linear`. By setting the direction to `alternate` the scale will be animated to `0.5`, and then animated back to `1` during 2 seconds. Again, the animation is being repeated indefinitely. ### Moving We could use the `<a-animation>` to change the position of the third shape, or we could use JavaScript instead. Add this code at the end of the `<script>` tag: ```js let t = 0; function render() { t += 0.01; requestAnimationFrame(render); cylinder.setAttribute("position", `3 ${Math.sin(t \* 2) + 1} 0`); } render(); ``` We're using the `render()` function to update the cylinder's position on every frame. Try changing the given values on the `y` axis and see how it affects the movement. Conclusion ---------- Everything is rendered properly and animating — congratulations on building your first A-Frame scene! Here's how the final version looks and works: If you have a VR device available, now is a good time to try out your scene with it too. **Note:** You can also check it out on GitHub. That was easier than you thought, right? A-Frame targets web developers by offering easy to use web markup and all the advantages that brings, such as JavaScript manipulation. It is easy to start with, but also provides a powerful API for advanced concepts, as well as dealing with cross browser differences and suchlike. The community is growing, just like the number of supported VR devices — it's a great time to start experimenting with such frameworks. See also -------- * A-Frame website * Introducing A-Frame 0.1.0 article * Made with A-Frame Tumblr * A-Frame physics plugin * A-Frame gamepad controls plugin
Building up a basic demo with Babylon.js - Game development
Building up a basic demo with Babylon.js ======================================== Babylon.js is one of the most popular 3D game engines used by developers. As with any other 3D library it provides built-in functions to help you implement common 3D functionality more quickly. In this article we'll take you through the real basics of using Babylon.js, including setting up a development environment, structuring the necessary HTML, and writing the JavaScript code. We will try to create a simple demo first — a cube rendered on the screen. If you have already worked through our *Building up a basic demo* series with Three.js, PlayCanvas or A-Frame (or you are familiar with other 3D libraries) you'll notice that Babylon.js works on similar concepts: camera, light and objects. Environment setup ----------------- To start developing with Babylon.js, you don't need much. You should start off by: * Making sure you are using a modern browser with good WebGL support, such as the latest Firefox or Chrome. * Creating a directory to store your experiments in. * Saving a copy of the latest Babylon.js engine inside your directory. * Opening the Babylon.js documentation in a separate tab — it is useful to refer to. HTML structure -------------- Here's the HTML structure we will use: ```html <!doctype html> <html lang="en-GB"> <head> <meta charset="utf-8" /> <title>MDN Games: Babylon.js demo</title> <style> html, body, canvas { margin: 0; padding: 0; width: 100%; height: 100%; font-size: 0; } </style> </head> <body> <script src="babylon.js"></script> <canvas id="render-canvas"></canvas> <script> const canvas = document.getElementById("render-canvas"); /\* all our JavaScript code goes here \*/ </script> </body> </html> ``` It contains some basic information like the document `<title>`, and some CSS to set the width and height of the `<canvas>` element (which Babylon.js will use to render the content on) to fill the entire available viewport space. The first `<script>` element includes the Babylon.js library in the page; we will write our example code in the second one. There is one helper variable already included, which will store a reference to the `<canvas>` element. Before reading on, copy this code to a new text file and save it in your working directory as `index.html`. Initializing the Babylon.js engine ---------------------------------- We have to create a Babylon.js engine instance first (passing it the `<canvas>` element to render on) before we start developing our game. Add the following code to the bottom of your second `<script>` element: ```js const engine = new BABYLON.Engine(canvas); ``` The `BABYLON` global object contains all the Babylon.js functions available in the engine. Creating a scene ---------------- A scene is the place where all the game content is displayed. While creating new objects in the demo, we will be adding them all to the scene to make them visible on the screen. Let's create a scene by adding the following lines just below our previous code: ```js const scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color3(0.8, 0.8, 0.8); ``` Thus, the scene is created and the second line sets the background color to light gray. Creating a rendering loop ------------------------- To make the scene actually visible we have to render it. Add these lines at the end of the `<script>` element, just before the closing `</script>`. ```js function renderLoop() { scene.render(); } engine.runRenderLoop(renderLoop); ``` We're using the engine's `runRenderLoop()` method to execute the `renderLoop()` function repeatedly on every frame — the loop will continue to render indefinitely until told to stop. Creating a camera ----------------- Now the setup code is in place we need to think about implementing the standard scene components: camera, light and objects. Let's start with the camera — add this line to your code below the scene creation and the line where we defined the `clearColor`. ```js const camera = new BABYLON.FreeCamera( "camera", new BABYLON.Vector3(0, 0, -10), scene, ); ``` There are many cameras available in Babylon.js; `FreeCamera` is the most basic and universal one. To initialize it you need to pass it three parameters: any name you want to use for it, the coordinates where you want it to be positioned in the 3D space, and the scene you want to add it to. **Note:** You probably noticed the `BABYLON.Vector3()` method in use here — this defines a 3D position on the scene. Babylon.js is bundled with a complete math library for handling vectors, colors, matrices etc. Let there be light ------------------ There are various light sources available in Babylon.js. The most basic one is the `PointLight`, which works like a flashlight — shining a spotlight in a given direction. Add the following line below your camera definition: ```js const light = new BABYLON.PointLight( "light", new BABYLON.Vector3(10, 10, 0), scene, ); ``` The parameters are very similar to the previously defined camera: the name of the light, a position in 3D space and the scene to which the light is added. Geometry -------- Now the scene is properly rendering we can start adding 3D shapes to it. To speed up development Babylon.js provides a bunch of predefined primitives that you can use to create shapes instantly in a single line of code. There are cubes, spheres, cylinders and more complicated shapes available. Let's start by defining the geometry for a box shape — add the following new code below your previous additions: ```js const box = BABYLON.Mesh.CreateBox("box", 2, scene); ``` A mesh is a way the engine creates geometric shapes, so material can be easily applied to them later on. In this case we're creating a box using the `Mesh.CreateBox` method with its own name, a size of 2, and a declaration of which scene we want it added to. **Note:** The size or position values (e.g. for the box size) are unitless, and can basically be anything you deem suitable for your scene — millimeters, meters, feet, or miles — it's up to you. If you save and refresh now, your object will look like a square, because it's facing the camera. The good thing about objects is that we can move them on the scene however we want, for example rotating and scaling. Let's apply a little rotation to the box, so we can see more than one face — again, add these lines below the previous one: ```js box.rotation.x = -0.2; box.rotation.y = -0.4; ``` The box looks black at the moment, because we haven't defined any material to apply to its faces. Let's deal with that next. Material -------- Material is that thing covering the object — the colors or texture on its surface. In our case we will use a simple blue color to paint our box. There are many types of materials that can be used, but for now the standard one should be enough for us. Add these lines below the previous ones: ```js const boxMaterial = new BABYLON.StandardMaterial("material", scene); boxMaterial.emissiveColor = new BABYLON.Color3(0, 0.58, 0.86); box.material = boxMaterial; ``` The `StandardMaterial` takes two parameters: a name, and the scene you want to add it to. The second line defines an `emissiveColor` — the one that will be visible for us. We can use the built-in `Color3` function to define it. The third line assigns the newly created material to our box. Congratulations, you've created your first object in a 3D environment using Babylon.js! It was easier than you thought, right? Here's how it should look: ![Blue Babylon.js 3D box on the gray background.](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_Babylon.js/cube.png) And here's the code we have created so far: You can also check it out on GitHub. More shapes ----------- We have a box on the scene already; now let's try adding more shapes. ### Torus Let's try adding a torus — add the following lines below the previous code: ```js const torus = BABYLON.Mesh.CreateTorus("torus", 2, 0.5, 15, scene); torus.position.x = -5; torus.rotation.x = 1.5; ``` This will create a torus and add it to the scene; the parameters are: name, diameter, thickness, tessellation (number of segments) and the scene to add it to. We also position it a bit to the left and rotate it on the `x` axis so it can be seen better. Now let's add a material: ```js const torusMaterial = new BABYLON.StandardMaterial("material", scene); torusMaterial.emissiveColor = new BABYLON.Color3(0.4, 0.4, 0.4); torus.material = torusMaterial; ``` It looks similar to the box element — we're creating the standard material, giving it a grayish color and assigning it to the torus. ### Cylinder Creating a cylinder and its material is done in almost exactly the same way as we did for the torus. Add the following code, again at the bottom of your script: ```js const cylinder = BABYLON.Mesh.CreateCylinder("cylinder", 2, 2, 2, 12, 1, scene); cylinder.position.x = 5; cylinder.rotation.x = -0.2; const cylinderMaterial = new BABYLON.StandardMaterial("material", scene); cylinderMaterial.emissiveColor = new BABYLON.Color3(1, 0.58, 0); cylinder.material = cylinderMaterial; ``` The cylinder parameters are: name, height, diameter at the top, diameter at the bottom, tessellation, height subdivisions and the scene to add it to. It is then positioned to the right of the cube, rotated a bit so its 3D shape can be seen, and given a yellow material. Here's how the scene should look right now: ![Light gray torus, blue box and yellow cylinder created with Babylon.js on the gray background.](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_Babylon.js/shapes.png) This works, but it is a bit boring. In a game something is usually happening — we can see animations and such — so let's try to breathe a little life into those shapes by animating them. Animation --------- We already used `position` and `rotation` to adjust the position of the shapes; we could also scale them. To show actual animation, we need to make changes to these values inside the rendering loop at the end of our code, so they are updated on every frame. Define a helper variable — `t` — that we will use for animations, just before the `renderLoop`, and decrement it on every frame inside the loop, like this: ```js let t = 0; function renderLoop() { scene.render(); t -= 0.01; // animation code goes here } engine.runRenderLoop(renderLoop); ``` The `t` variable will be incremented on every rendered frame. ### Rotation Applying rotation is as easy as adding this line at the end of the `renderLoop` function: ```js box.rotation.y = t \* 2; ``` It will rotate the box along the `y` axis. ### Scaling Add this line below the previous one to scale the torus: ```js torus.scaling.z = Math.abs(Math.sin(t \* 2)) + 0.5; ``` There's a little bit of adjustment made to make the animation look and feel nice. You can experiment with the values and see how it affects the animation. ### Moving By changing the position of the cylinder directly we can move it on the scene — add this line below the previous one: ```js cylinder.position.y = Math.sin(t \* 3); ``` The cylinder will float up and down on the `y` axis thanks to the `Math.sin()` function. Conclusion ---------- Here's the final code listing, along with a viewable live example: You can also see it on GitHub and fork the repository if you want to play with it yourself locally. Now you know the basics of Babylon.js engine; happy experimentation!
Building up a basic demo with PlayCanvas - Game development
Building up a basic demo with PlayCanvas ======================================== **PlayCanvas** is a popular 3D WebGL game engine, originally created by Will Eastcott and Dave Evans. It is open sourced on GitHub, with an editor available online and good documentation. The online editor is free for public projects with up to two team members, but there are also paid plans if you'd like to run a commercial private project with more developers. ![PlayCanvas website.](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/playcanvas-cover.png) Games and demos --------------- PlayCanvas has a few well-known demos published that showcase its possibilities. * Tanx is a multiplayer tank game where you can drive your tank around, shooting at other players as you go. * Swooop is a flying game where you pilot your plane around a magical island, collecting jewels and fuel as you go. * Visualizations like the Star Lord and BMW i8 also take advantage of the engine and showcase what's possible. ![A list of PlayCanvas demos: Tanx, Swooop, Star Lord, BMW i8.](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/playcanvas-demos.png) **Note:** Check out the list of featured demos to find more examples. Engine vs. editor ----------------- The engine itself can be used as a standard library by including its JavaScript file directly in your HTML, so you can start coding right away; in addition the PlayCanvas toolset comes with an online editor that you can use to drag and drop components onto the scene — a great way to create games and other apps requiring scenes if you're more of a designer than a coder. Those approaches are different but work equally well regarding achieving end goals. PlayCanvas engine ----------------- Built for modern browsers, PlayCanvas is a fully-featured 3D game engine with resource loading, an entity and component system, advanced graphics manipulation, collision and physics engine (built with ammo.js), audio, and facilities to handle control inputs from various devices (including gamepads). That's quite an impressive list of features — let's see some in action, check out the Building up a basic demo with PlayCanvas engine for details. PlayCanvas editor ----------------- Instead of coding everything from the beginning you can also use the online editor. This can be a more pleasant working environment if you are not someone who likes to code. See the Building up a basic demo with PlayCanvas editor for details. Summary ------- Of course, it depends on your approach — designers may favor the online editor while programmers will prefer having the full control over the coding environment and will probably use the engine's source files. The good thing is that you have a choice and can pick whatever tools suit you best.
Building up a basic demo with Three.js - Game development
Building up a basic demo with Three.js ====================================== A typical 3D scene in a game — even the simplest one — contains standard items like shapes located in a coordinate system, a camera to actually see them, lights and materials to make it look better, animations to make it look alive, etc. **Three.js**, as with any other 3D library, provides built-in helper functions to help you implement common 3D functionality more quickly. In this article we'll take you through the real basics of using Three, including setting up a development environment, structuring the necessary HTML, the fundamental objects of Three, and how to build up a basic demo. **Note:** We chose Three because it is one of the most popular WebGL libraries, and it is easy to get started with. We are not trying to say it is better than any other WebGL library available, and you should feel free to try another library, such as CopperLicht or PlayCanvas. Environment setup ----------------- To start developing with Three.js, you don't need much. You should: * Make sure you are using a modern browser with good WebGL support, such as the latest Firefox or Chrome. * Create a directory to store your experiments in. * Save a copy of the latest minimized Three.js library inside your directory. * Open the Three.js documentation in a separate tab — it is useful to refer to. HTML structure -------------- Here's the HTML structure we will use: ```html <!doctype html> <html lang="en-GB"> <head> <meta charset="utf-8" /> <title>MDN Games: Three.js demo</title> <style> body { margin: 0; padding: 0; } canvas { width: 100%; height: 100%; } </style> </head> <body> <script src="three.min.js"></script> <script> const WIDTH = window.innerWidth; const HEIGHT = window.innerHeight; /\* all our JavaScript code goes here \*/ </script> </body> </html> ``` It contains some basic information like the document `<title>`, and some CSS to set the `width` and `height` of the `<canvas>` element, that Three.js will insert on the page to 100% to fill the entire available viewport space. The first `<script>` element includes the Three.js library in the page, and we will write our example code inside the second. There are two helper variables already included, which store the window's `width` and `height`. Before reading further, copy this code to a new text file, and save it in your working directory as `index.html`. Renderer -------- A renderer is a tool which displays scenes right in your browser. There are a few different renderers: WebGL is the default, and others you can use are Canvas, SVG, CSS, and DOM. They differ in how everything is rendered, so the WebGL implementation will implement differently than the CSS one. Despite the variety of ways they achieve the goal, the experience will look the same for the user. Thanks to this approach, a fallback can be used, if a desired technology is not supported by the browser. ```js const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(WIDTH, HEIGHT); renderer.setClearColor(0xdddddd, 1); document.body.appendChild(renderer.domElement); ``` We are creating a new WebGL renderer, setting its size to fit the whole available space on the screen, and appending the DOM structure to the page. You might have noticed the `antialias` parameter in the first line — this renders the edges of shapes more smoothly. The `setClearColor()` method sets our background to a light gray color, instead of the default black one. Add this code into our second `<script>` element, just below the JavaScript comment. Scene ----- A scene is the place where everything happens. When creating new objects in the demo, we add them all inside the scene to become visible on the screen. In three.js, the scene is represented by a `Scene` object. Let's create it, by adding the following line below our previous lines: ```js const scene = new THREE.Scene(); ``` Later, we will be using the `.add()` method, to add objects to this scene. Camera ------ We have the rendered scene, but we still need to add a camera to view our handiwork — imagine a movie set without any cameras. The following lines put the camera in place in the 3D coordinate system, and point it in the direction of our scene, so we can finally see something: ```js const camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT); camera.position.z = 50; scene.add(camera); ``` Add the above lines to your code, below those previously added. There are other types of camera available (Cube, Orthographic), but the simplest is Perspective. To initialize it, we have to set its field of view and aspect ratio: the former is used to set how much is seen, and the latter is important for the objects on the screen to have the right proportions when rendered, and not look stretched. Let's explain values we are setting for the code above: * The value we set for the field of view, 70, is something we can experiment with: the higher the value, the greater the amount of scene the camera will show. Imagine a normal camera view, versus a fish eye effect, which allows a lot more to be seen. The default value is 50. * The aspect ratio is set to the current width and height of the window so it will be dynamically adjusted. We could set a fixed ratio — for example 16 ⁄ 9, which is the aspect ratio of a widescreen TV. The default value is 1. * The `z` position, with the value of 50 units, is the distance between the camera and the center of the scene on the `z` axis. Here we're moving the camera back, so the objects in the scene can be viewed. 50 feels about right. It's not too near, or too far, and the sizes of the objects allow them to stay on the scene, within the given field of view. The `x` and `y` values, if not specified, will default to 0. You should experiment with these values and see how they change what you see in the scene. **Note:** The distance values (e.g. for the camera z position) are unitless, and can be anything you deem suitable for your scene: millimeters, meters, feet, or miles. It's up to you. Rendering the scene ------------------- Everything is ready, but we still can't see anything. Although we've set up the renderer, we still need to render everything. Our `render()` function will do this job, with a little help from `requestAnimationFrame()`, which causes the scene to be re-rendered constantly on every frame: ```js function render() { requestAnimationFrame(render); renderer.render(scene, camera); } render(); ``` On every new frame the `render` function is invoked, and the `renderer` renders the `scene` and the `camera`. Right after the function declaration, we're invoking it for the first time to start the loop, after which it will be used indefinitely. Again, add this new code below your previous additions. Try saving the file and opening it in your browser. You should now see a gray window. Congratulations! Geometry -------- Now our scene is properly rendering, we can start adding 3D shapes. To speed up development, Three.js provides a bunch of predefined primitives, which you can use to create shapes instantly in a single line of code. There's cubes, spheres, cylinders, and more complicated shapes available. Detail like drawing required vertices and faces, for a given shape, is handled by the Three framework, so we can focus on higher level coding. Let's start, by defining the geometry for a cube shape, adding the following just above the `render()` function: ```js const boxGeometry = new THREE.BoxGeometry(10, 10, 10); ``` In this case, we define a simple cube that is 10 x 10 x 10 units. The geometry itself is not enough though, we also need a material that will be used for our shape. Material -------- A material is what covers an object, the colors, or textures on its surface. In our case, we will choose a simple blue color to paint our box. There are a number of predefined materials which can be used: Basic, Phong, Lambert. Let's play with the last two later, but for now, the Basic one should be enough: ```js const basicMaterial = new THREE.MeshBasicMaterial({ color: 0x0095dd }); ``` Add this line below the previously added. Our material is now ready, what next? Mesh ---- To apply the material to a geometry, a mesh is used. This takes on a shape, and adds the specified material to every face: ```js const cube = new THREE.Mesh(boxGeometry, basicMaterial); ``` Again, add this line below the one you previously added. Adding the cube to the scene ---------------------------- We've now created a cube, using the geometry and material defined earlier. The last thing to do is to place the cube to our scene. Add this line below the previous one: ```js scene.add(cube); ``` If you save, and refresh your Web browser, our object will now look like a square, because it's facing the camera. The good thing about objects, is that we can move them on the scene, however we want. For example, rotating and scaling as we like. Let's apply a little rotation to the cube, so we can see more than one face. Again, adding our code below the previous: ```js cube.rotation.set(0.4, 0.2, 0); ``` Congratulations, you've created an object in a 3D environment! This might have proven easier than you first thought? Here's how it should look: ![Blue cube on a gray background rendered with Three.js.](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_Three.js/cube.png) And here's the code we have created so far: You can also check it out on GitHub. More shapes and materials ------------------------- Now we will add more shapes to the scene, and explore other shapes, materials, lighting, and more. Let's move the cube to the left, to make space for some friends. Adding the following line just below the previous one: ```js cube.position.x = -25; ``` Now onto more shapes and materials. What might happen when you add a torus, wrapped in the Phong material? Try adding the following lines, just below the lines defining the cube. ```js const torusGeometry = new THREE.TorusGeometry(7, 1, 6, 12); const phongMaterial = new THREE.MeshPhongMaterial({ color: 0xff9500 }); const torus = new THREE.Mesh(torusGeometry, phongMaterial); scene.add(torus); ``` These lines will add a torus geometry; the `TorusGeometry()` method's parameters define, and the parameters are `radius`, `tube diameter`, `radial segment count`, and `tubular segment count`. The Phong material should look more glossy than the box's simple Basic material, though right now our torus will just look black. We can choose more fun predefined shapes. Let's play some more. Add the following lines, below those defining the torus: ```js const dodecahedronGeometry = new THREE.DodecahedronGeometry(7); const lambertMaterial = new THREE.MeshLambertMaterial({ color: 0xeaeff2 }); const dodecahedron = new THREE.Mesh(dodecahedronGeometry, lambertMaterial); dodecahedron.position.x = 25; scene.add(dodecahedron); ``` This time, we are creating a dodecahedron, a shape containing twelve flat faces. The parameter, `DodecahedronGeometry(),` defines the size of the object. We're using a Lambert material, similar to Phong, but should be less glossy. Again it's black, for now. We're moving the object to the right, so it's not in the same position as the box, or torus. As mentioned above, the new objects currently just look black. To have both, the Phong and Lambert materials properly visible, we need to introduce a source of light. Lights ------ There are various types of light sources available in Three.js. The most basic is `PointLight`, which works like a flashlight, shining a spotlight in a defined direction. Add the following lines, below your shape definitions: ```js const light = new THREE.PointLight(0xffffff); light.position.set(-10, 15, 50); scene.add(light); ``` We define a white point of light, set its position a little away from the center of the scene, so it can light up some parts of the shapes, finally adding it to the scene. Now everything works as it should, all three shapes are visible. You should check the documentation for other types of lights, like Ambient, Directional, Hemisphere, or Spot. Experiment placing them on our scene, to see how they affect it. ![Shapes: blue cube, dark yellow torus and dark gray dodecahedron on a gray background rendered with Three.js.](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_Three.js/shapes.png) This looks a little boring though. In a game, something is usually happening. We might see animations and such. So let's try breathing a little life into these shapes, by animating them! Animation --------- We already used rotation, to adjust the position of the cube. We can also scale the shapes, or change their positions. To show animation, we need to make changes to these values inside the render loop, so they update on each frame. ### Rotation Rotating is straightforward. You add a value to a given direction of rotation on each frame. Add this line of code, right after the `requestAnimationFrame()` invocation inside the `render` function: ```js cube.rotation.y += 0.01; ``` This rotates the cube on every frame, by a tiny bit, so the animation looks smooth. ### Scaling We can also scale an object. Applying a constant value, we would make it grow, or shrink just once. Let's make things more interesting. First, we implement a helper variable, called `t,` for counting elapsed time. Add it right before the `render()` function: ```js let t = 0; ``` Now let's increase the value by a given constant value, on each frame of the animation. Add the following lines, just below the `requestAnimationFrame()` invocation: ```js t += 0.01; torus.scale.y = Math.abs(Math.sin(t)); ``` We use `Math.sin`, ending up with quite an interesting result. This scales the torus, repeating the process, as `sin` is a periodic function. We're wrapping the scale value in `Math.abs`, to pass the absolute values, greater or equal to 0. As sin is between -1 and 1, negative values might render out torus in unexpected way. In this case it looks black half the time. Now, onto movement. ### Moving Aside from rotation, and scaling, we can additionally move objects around the scene. Add the following, again just below our `requestAnimationFrame()` invocation: ```js dodecahedron.position.y = -7 \* Math.sin(t \* 2); ``` This will move the dodecahedron up and down, by applying the `sin()` value to the y-axis on each frame, and a little adjustment to make it look cooler. Try changing these values, to see how it affects the animations. Conclusion ---------- Here's the final code: You can also see it on GitHub and fork the repository, if you want to play with it locally. Now you understand the basics of Three.js, you can jump back to the parent page, 3D on the Web. You could also try learning raw WebGL, to gain a better understanding of what's going on underneath. See our WebGL documentation.
Building up a basic demo with the PlayCanvas engine - Game development
Building up a basic demo with the PlayCanvas engine =================================================== Built for modern browsers, **PlayCanvas** is a fully-featured 3D game engine with resource loading, an entity and component system, advanced graphics manipulation, collision and physics engine (built with ammo.js), audio, and facilities to handle control inputs from various devices (including gamepads). That's quite an impressive list of features — let's see some in action. ![PlayCanvas engine repository on GitHub.](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/engine/playcanvas-github.png) We will try putting together a simple demo first — a cube rendered on the screen. If you have already worked through our Building up a basic demo with Three.js article (or you are familiar with other 3D libraries) you'll notice that PlayCanvas works on similar concepts: camera, light and objects. Environment setup ----------------- To start developing with PlayCanvas, you don't need much. You should start off by: * Making sure you are using a modern browser with good WebGL support, such as the latest Firefox or Chrome. * Creating a directory to store your experiments in. * Saving a copy of the latest PlayCanvas engine inside your directory. * Opening the PlayCanvas documentation in a separate tab — it is useful to refer to. HTML structure -------------- Here's the HTML structure we will use. ```html <!doctype html> <html lang="en-GB"> <head> <meta charset="utf-8" /> <title>MDN Games: PlayCanvas demo</title> <style> body { margin: 0; padding: 0; } canvas { width: 100%; height: 100%; } </style> </head> <body> <script src="playcanvas-latest.js"></script> <canvas id="application-canvas"></canvas> <script> const canvas = document.getElementById("application-canvas"); /\* all our JavaScript code goes here \*/ </script> </body> </html> ``` It contains some basic information like the document `<title>`, and some CSS to set the width and height of the `<canvas>` element that PlayCanvas will use to 100% so that it will fill the entire available viewport space. The first `<script>` element includes the PlayCanvas library in the page; we will write our example code in the second one. There is one helper variable already included, which will store a reference to the `<canvas>` element. Before reading on, copy this code to a new text file and save it in your working directory as `index.html`. PlayCanvas application ---------------------- To begin developing our game we have to create the PlayCanvas application first (using the given `<canvas>` element), and then start the update loop. Add the following code to the bottom of your second `<script>` element: ```js const app = new pc.Application(canvas); app.start(); ``` The `pc` global object contains all the PlayCanvas functions available in the engine. Next, we'll set the Canvas to fill the window, and automatically change its resolution to be the same as the Canvas size. Again, add the following lines at the bottom of your script. ```js app.setCanvasFillMode(pc.FILLMODE\_FILL\_WINDOW); app.setCanvasResolution(pc.RESOLUTION\_AUTO); ``` Camera ------ Now when the setup code is in place we need to think about implementing the standard scene components: camera, lights and objects. Let's start with the camera — add these lines to your code, below the previous ones. ```js const camera = new pc.Entity(); camera.addComponent("camera", { clearColor: new pc.Color(0.8, 0.8, 0.8), }); app.root.addChild(camera); camera.setPosition(0, 0, 7); ``` The code above will create a new `Entity`. **Note:** An Entity is any object used in the scene — it can be an object like a box, cylinder or cone, but it can also be a camera, light or sound source. Then it adds a `camera` component to it with the light gray `clearColor` — the color will be visible as the background. Next, the `camera` object is added to the root of our application and positioned to be 7 units away from the center of the scene on the `z` axis. This allows us to make some space to visualize the objects that we will create later on. **Note:** The distance values (e.g. for the camera z position) are unitless, and can basically be anything you deem suitable for your scene — millimeters, meters, feet, or miles — it's up to you. Try saving the file and loading it in your browser. You should now see a gray window. Congratulations! Geometry -------- Now the scene is properly rendering we can start adding 3D shapes to it. To speed up development PlayCanvas provides a bunch of predefined primitives that you can use to create shapes instantly in a single line of code. There are cubes, spheres, cylinders and more complicated shapes available. Drawing everything for given shape is taken care of by the engine, so we can focus on the high level coding. Let's start by defining the geometry for a cube shape — add the following new code below your previous additions: ```js const box = new pc.Entity(); box.addComponent("model", { type: "box" }); app.root.addChild(box); box.rotate(10, 15, 0); ``` It will create an `Entity` with the `box` model component and add it to the root of the application, our scene. We also rotate the box a bit to show that it's actually a 3D cube and not a square. The cube is visible, but it is completely. To make it look better we need to shine some light onto it. Lights ------ The basic light types in PlayCanvas are directional and ambient. The first type is a directional light placed somewhere on the scene while the second one reflects the light from the first type, so it looks more natural; this can be set globally. Again, add the new code below your previous additions. ```js const light = new pc.Entity(); light.addComponent("light"); app.root.addChild(light); light.rotate(45, 0, 0); ``` It will create a light `Entity` component and add it to the scene. We can rotate the light on the `x` axis to make it shine on more than one side of the cube. It's time to add the ambient light: ```js app.scene.ambientLight = new pc.Color(0.2, 0.2, 0.2); ``` The code above assign a dark grey ambient light for the whole scene. The box look better now, but it could get some colors to look even better - for that we need to create material for it. Material -------- The basic PlayCanvas material is called PhongMaterial — add the following lines below the previous code. ```js const boxMaterial = new pc.PhongMaterial(); boxMaterial.diffuse.set(0, 0.58, 0.86); boxMaterial.update(); box.model.model.meshInstances[0].material = boxMaterial; ``` By diffusing the light on the object, we can give it its own color — we'll choose a nice familiar blue. **Note:** In PlayCanvas, the color channel values are provided as floats in the range `0-1`, instead of integers of `0-255` as you might be used to using on the Web. After the material is created and its color is set, it has to be updated so our changes are going to be applied. Then all we need to do is set the `box`'s material to the newly created `boxMaterial`. Congratulations, you've created your first object in a 3D environment using PlayCanvas! It was easier than you thought, right? Here's how it should look: ![Blue cube on a gray background rendered with PlayCanvas.](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/engine/cube-playcanvas.png) And here's the code we have created so far: You can also check it out on GitHub. More shapes ----------- Now we will add more shapes to the scene. Let's move the cube 2 units to the left to make space for some friends — add the following line just below the previous code: ```js box.translate(-2, 0, 0); ``` Now let's add a new shape — how about a cylinder? ### Cylinder Add the following lines at the bottom of your JavaScript code: ```js const cylinder = new pc.Entity(); cylinder.addComponent("model", { type: "cylinder" }); app.root.addChild(cylinder); cylinder.rotate(15, 0, 0); ``` This looks very similar to the code we used for creating a cube, but instead of the `box` component we are adding a `cylinder`. It is also rotated around the `x` axis to show it's actually a 3D shape. To make the cylinder have a color, let's say yellow, we need to create the material for it, as before. Add the following lines: ```js const cylinderMaterial = new pc.PhongMaterial(); cylinderMaterial.diffuse.set(1, 0.58, 0); cylinderMaterial.update(); cylinder.model.model.meshInstances[0].material = cylinderMaterial; ``` ### Cone Creating a cone and its material is done in almost exactly the same way as we did for the cylinder. Add the following code, again, at the bottom of your script: ```js const cone = new pc.Entity(); cone.addComponent("model", { type: "cone" }); app.root.addChild(cone); cone.translate(2, 0, 0); const coneMaterial = new pc.PhongMaterial(); coneMaterial.diffuse.set(0.9, 0.9, 0.9); coneMaterial.update(); cone.model.model.meshInstances[0].material = coneMaterial; ``` The code above will create a new `cone`, add it to the `app` and move it by 2 units to the right so it's not overlapping the cylinder. Then the material is created, given a gray color, and assigned to the cone `Entity`. Here's how it should look right now: ![Shapes: blue cube, yellow cylinder and gray cone on a light gray background rendered with PlayCanvas.](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/engine/shapes-playcanvas.png) This works, but it is a bit boring. In a game something is usually happening — we can see animations and such — so let's try to breathe a little life into those shapes by animating them. Animation --------- We already used `translate` or `rotate` to adjust the position of the shapes; we could also change their positions directly with `setPosition`, or scale them. To show actual animation, we need to make changes to these values inside the rendering loop, so they are updated on every frame. There's a special `update` event that we can use for that — add the following code just below the previous additions: ```js let timer = 0; app.on("update", (deltaTime) => { timer += deltaTime; // code executed on every frame }); ``` The callback takes the `deltaTime` as the parameter, so we have the relative time that has passed since the previous invocation of this update. For time based animations we'll use a `timer` variable that will store the time that has passed since the start of the app by adding the `deltaTime` to it on every update. ### Rotation Rotating is quite easy — all you need to do is to add a defined value to the given direction of rotation on each frame. Add this line of code inside the `app.on("update")` callback function, right after the addition of the `deltaTime` to the `timer` variable: ```js box.rotate(deltaTime \* 10, deltaTime \* 20, deltaTime \* 30); ``` It will rotate the `box` by `deltaTime*10` on the `x` axis, `deltaTime*20` on the `y` axis and `deltaTime*30` on the `z` axis, on very frame — giving us a smooth animation. ### Scaling We can also scale a given object — there's a function for that called `setLocalScale`. Add the following, again into the callback: ```js cylinder.setLocalScale(1, Math.abs(Math.sin(timer)), 1); ``` Here we are using `Math.sin` to scale the cylinder in a cycle, bigger and smaller again. We're wrapping the `y` scale value in `Math.abs` to pass the absolute values (greater or equal to 0); `sin` varies between -1 and 0, and for negative values the cylinder scaling can render unexpectedly (in this case it looks black half the time.) Now onto the movement part. ### Moving Beside rotation and scaling we can also move objects around the scene. Add the following code to achieve that. ```js cone.setPosition(2, Math.sin(timer \* 2), 0); ``` This will move the `cone` up and down by applying the `sin` value to the `y` axis on each frame, with a little bit of adjustment to make it look cooler. Try changing the value to see how it affects the animation. Conclusion ---------- Here's the final code listing, along with a viewable live example: You can also see it on GitHub and fork the repository if you want to play with it yourself locally. Now you know the basics of PlayCanvas engine; happy experimentation! Summary ------- Now you can continue reading the PlayCanvas editor article, go back to the Building up a basic demo with PlayCanvas page, or go back a level higher to the main 3D Games on the Web page.
Building up a basic demo with PlayCanvas editor - Game development
Building up a basic demo with PlayCanvas editor =============================================== Instead of coding everything from scratch you can also use the online **PlayCanvas editor**. This can be a more pleasant working environment if you are not someone who likes to code. Creating an account ------------------- The PlayCanvas Editor is free — all you have to do to begin with is register your account and login: ![PlayCanvas Editor - Login](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-login.png) When you first sign up, you are taken straight into the editor and given a simple starter tutorial involving editing a 3D rolling ball game. You can finish this before you continue our tutorial if you like. When you are ready to continue with our tutorial, go to your canvas homepage — for example mine is `https://playcanvas.com/end3r`. Here's what the page looks like — you can create projects and manage them, change their settings etc. Creating a new project ---------------------- Start a brand new project by clicking on the *New* button: ![PlayCanvas Editor - Panel](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-panel.png) The resulting dialog box will show a few different options. There are starter kits available, but we don't want to load models or start a platform game. 1. We want to start small, so we will use the empty project — click on the Blank Project option and enter a name for it (we are using "MDN Games demo".) 2. Enter a description if you want — it is optional. 3. Click *Create* to have it created. ![PlayCanvas Editor - New project](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-newproject.png) Next you'll see your project's page — there's not much yet. By clicking the *Editor* button we'll launch the online PlayCanvas editor where we'll create our scene with the shapes. Do this now. ![PlayCanvas Editor - Project](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-project.png) Creating the scene ------------------ Here's how the scene looks initially in the editor. Even though it's a blank new project we don't have to start entirely from scratch — the camera and directional light are prepared already, so you don't have to worry about them. ![PlayCanvas Editor - Scene](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-scene.png) Now onto the creative part. To add an entity to the scene you have to click on the big plus button located in the top left area of the editor, next to the Hierarchy text. When hovering over that button with your mouse the label will say 'Add Entity' — that's exactly what we want to do. An Entity is any object used in the scene — it can be an object like a box, cylinder or cone, but it can also be a camera, light or sound source. After clicking the button you'll see a dropdown list containing a lot of various entities to choose from. Go ahead and click *Box* — it will be added to the scene. ![PlayCanvas Editor - New box](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-newbox.png) The box is created with the default values — width, height and depth are set to 1, and it is placed in the middle of the scene. You can drag it around or apply new values in the right panel. ![PlayCanvas Editor - Box](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-box.png) To add some colors to the scene we need a new material that will be used on the newly created box. Click on the plus button in the *Assets* tab, and click on the *Material* option in the dropdown list that appears to create a new material. ![PlayCanvas Editor - New material](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-newmaterial.png) Click on your new material in the assets tab and its entity inspector will appear on the right-hand side of the display. Now edit the *Name* text field to give it a unique name (we've chosen *boxMaterial*). A unique name will help us remember what this material is for — we will add more later! ![PlayCanvas Editor - Box material](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-boxmaterial.png) To change its color we'll use the *Diffuse* option in the entity inspector. Click *Diffuse*, then select the colored box next to the Color label — it will open a color wheel. From here you can click your desired color or enter it in the bottom text field as a hex value. We've chosen a blue color with a hex value of `0095DD` — enter this code in the text field and press return for it to be accepted. **Note:** Yes, you read that right — you need to enter the hex value without the hash/pound symbol. ![PlayCanvas Editor - Diffuse color](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-diffusecolor.png) Now we can apply the colored material to the shape by clicking and dragging its icon from the bottom part of the screen (the little dot on the left-hand side of the material's name — it can be a bit fiddly to select; just persevere) onto the box on the scene. ![PlayCanvas Editor - Box drop](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-boxdrop.png) So, at this point we've created a blue box. Click on the box to bring up its entity sidebar — you'll see options for changing its position, rotation, and scale. Try applying the rotation values X: 10 and Y: 20. ![PlayCanvas Editor - Rotate](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-rotate.png) Now click on the play arrow in the top right corner of the scene to launch and render the scene — it will be opened in a separate browser tab. ![PlayCanvas Editor - Launch](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-launch.png) This looks great! Let's add more shapes to the scene to make it look more interesting. ![PlayCanvas Editor - Boxrender](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-boxrender.png) Adding more shapes ------------------ To make way for more shapes, move the box to the left to make some room for the next shape. You can do this by giving it an X position value of -2. Adding other shapes involves a very similar process to adding the box. Click on the Root folder in the hierarchy panel (to make sure that the new shape appears in the root, and not as a child of the Box) then Click on the big *Add Entity* (plus) button and select cylinder from the dropdown list — it will add a new cylinder shape to the scene. ![PlayCanvas Editor - Cylinder](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-cylinder.png)Now follow the same steps as we did before when coloring the cube: * Create a new material using the *Add Asset* (plus) button. * Make sure the New Material in the Assets panel is selected, to bring up the entity inspector. * Give the material a new name, along the lines of `cylinderMaterial`. * Click diffuse, then click the color picker — give it an orange color (we used FF9500.) * Drag and drop the `cylinderMaterial` icon onto the cylinder object on the screen to apply that color. ![PlayCanvas Editor - Cylinder material](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-cylindermaterial.png) Follow the same approach again to add a cone to the scene, giving it a grayish color (we used EAEFF2.) You should now have three shapes on your scene, something like the below screenshot. ![PlayCanvas Editor - Cone](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-cone.png) Animating our scene ------------------- Animating 3D models might be considered an advanced thing to do, but all we want to do is to control a few properties of a given object — we can use a script component to do that. Click on the plus button in the Assets panel, select the Script option, and name your new script file `boxAnimation.js`. ![PlayCanvas Editor - Box animation](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-boxanimation.png) If you double click on it, you'll be moved to a code editor. As you can see, the file contains some boilerplate code already: ```js pc.script.create("boxAnimation", function (app) { class BoxAnimation { constructor(entity) { this.entity = entity; } // Called once after all resources are loaded and before the first update initialize() {} // Called every frame, dt is time in seconds since last update update(dt) {} } return BoxAnimation; }); ``` The most interesting part is the `update()` function, which is where we can put any code that we want repeated on every frame. Add the following line inside this function, to rotate the cube on every frame: ```js this.entity.rotate(dt \* 10, dt \* 20, dt \* 30); ``` In the line above `this.entity` refers to the object to which the script will be attached (the box); using the `dt` variable, which contains the delta time passed since the previous frame, we can rotate the box by a different amount around all three axes. 1. Save the changes using the Save button in the top right of the code editor, then return to the main editor tab. Here, follow these steps: 2. Be sure you have the box selected on the scene. 3. Click on *Add component*, then *Script* in the entity inspector. 4. At the bottom of the screen you can see the list of scripts available — for now there's only `boxAnimation.js` — clicking it will add the animation script to the box object. ![PlayCanvas Editor - Box script](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-boxscript.png) ### The cylinder Now we'll do the same steps for cylinder. First: 1. Create a new Script asset. 2. Name it `cylinderAnimation.js`. 3. Double click the script icon to launch the code editor. This time instead of rotating the object we will try to scale it. For that we'll need a timer to store the total amount of time passed since the start of the animation. Add this code to the `initialize()` function: ```js this.timer = 0; ``` And those two lines to the `update()` function: ```js this.timer += dt; this.entity.setLocalScale(1, Math.abs(Math.sin(this.timer)), 1); ``` The `setLocalScale()` method applies the given values to the X, Y and Z axes of the object. In our case we're modifying the scale of the cylinder on the Y axis, giving it as a value the `Math.sin()` of the timer, with `Math.abs()` applied to the result of that to have the values always above zero (0-1; sin values are normally between -1 and 1.) This gives us a nice scaling effect as a result. Remember to add the `cylinderAnimation.js` file to the Cylinder object to apply the given animations. ### The cone Time to play with the last object — the cone. Create a `coneAnimation.js` file and double click it to open it in the editor. Next, add the following line to the `initialize()` function: ```js this.timer = 0; ``` To move the cone up and down we will use the `setPosition()` method — add the code below to the `update()` function: ```js this.timer += dt; this.entity.setPosition(2, Math.sin(this.timer \* 2), 0); ``` The position of the cone will be animated on each frame by being passed the `Math.sin()` value of the `timer` at each point in time — we have doubled the `this.timer` value to make it move higher. Add the `coneAnimation.js` script to the cone object, as before. Test the demo out ----------------- Launch the demo to see the effects — all the shapes should animate. Congratulations, you've completed the tutorial! ![PlayCanvas Editor - Shapes](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/editor/playcanvas-editor-shapes.png) Summary ------- Now you can check the PlayCanvas engine article if you haven't seen it yet, go back to the Building up a basic demo with PlayCanvas page, or go back a level higher to the main 3D Games on the Web page.
Bounding volume collision detection with THREE.js - Game development
Bounding volume collision detection with THREE.js ================================================= This article shows how to implement **collision detection between bounding boxes and spheres using the Three.js** library. It is assumed that before reading this you have read our 3D collision detection introductory article first, and have basic knowledge about Three.js. Using `Box3` and `Sphere` ------------------------- Three.js has objects that represent **mathematical volumes** and shapes — for 3D AABB and bounding spheres we can use the **`Box3`** and **`Sphere`** objects. Once instantiated, they have methods available to do intersection tests against other volumes. ### Instantiating boxes To create a **`Box3` instance**, we need to provide the **lower and upper boundaries** of the box. Usually we will want this AABB to be "linked" to an object in our 3D world (like a character.) In Three.js, `Geometry` instances have a `boundingBox` property with `min` and `max` boundaries for the object. Keep in mind that in order for this property to be defined, you need to manually call `Geometry.computeBoundingBox` beforehand. ```js const knot = new THREE.Mesh( new THREE.TorusKnotGeometry(0.5, 0.1), new MeshNormalMaterial({}), ); knot.geometry.computeBoundingBox(); const knotBBox = new Box3( knot.geometry.boundingBox.min, knot.geometry.boundingBox.max, ); ``` **Note:** The `boundingBox` property takes the `Geometry` itself as reference, and not the `Mesh`. So any transformations such as scale, position, etc. applied to the `Mesh` will be ignored while computing the calculating box. A more simple alternative that fixes the previous issue is to set those boundaries later on with `Box3.setFromObject`, which will compute the dimensions taking into account a 3D entity's **transformations *and* any child meshes** as well. ```js const knot = new THREE.Mesh( new THREE.TorusKnotGeometry(0.5, 0.1), new MeshNormalMaterial({}), ); const knotBBox = new Box3(new THREE.Vector3(), new THREE.Vector3()); knotBBox.setFromObject(knot); ``` ### Instantiating spheres Instantiating **`Sphere` objects** is similar. We need to provide the sphere's center and radius, which can be added to the `boundingSphere` property available in `Geometry`. ```js const knot = new THREE.Mesh( new THREE.TorusKnotGeometry(0.5, 0.1), new MeshNormalMaterial({}), ); const knotBSphere = new Sphere( knot.position, knot.geometry.boundingSphere.radius, ); ``` Unfortunately, there is no equivalent of `Box3.setFromObject` for Sphere instances. So if we apply transformations or change the position of the `Mesh`, we need to manually update the bounding sphere. For instance: ```js knot.scale.set(2, 2, 2); knotBSphere.radius = knot.geometry.radius \* 2; ``` ### Intersection tests #### Point vs. `Box3` / `Sphere` Both `Box3` and `Sphere` have a **`containsPoint`** method to do this test. ```js const point = new THREE.Vector3(2, 4, 7); knotBBox.containsPoint(point); ``` #### `Box3` vs. `Box3` The **`Box3.intersectsBox`** method is available for performing this test. ```js knotBbox.intersectsBox(otherBox); ``` **Note:** This is different from the `Box3.containsBox` method, which checks whether the Box3 *fully* wraps another one. #### `Sphere` vs. `Sphere` In a similar fashion as before, there is a **`Sphere.intersectsSphere`** method to perform this test. ```js knotBSphere.intersectsSphere(otherSphere); ``` #### `Sphere` vs. `Box3` Unfortunately this test is not implemented in Three.js, but we can patch Sphere to implement a Sphere vs. AABB intersection algorithm. ```js // expand THREE.js Sphere to support collision tests vs. Box3 // we are creating a vector outside the method scope to // avoid spawning a new instance of Vector3 on every check THREE.Sphere.__closest = new THREE.Vector3(); THREE.Sphere.prototype.intersectsBox = function (box) { // get box closest point to sphere center by clamping THREE.Sphere.__closest.set(this.center.x, this.center.y, this.center.z); THREE.Sphere.__closest.clamp(box.min, box.max); const distance = this.center.distanceToSquared(THREE.Sphere.__closest); return distance < this.radius \* this.radius; }; ``` ### Demos We have prepared some live demos to demonstrate these techniques, with source code to examine. * Point vs. Box and Sphere * Box vs. Box and Sphere * Sphere vs. Box and Sphere ![A knot object, a large sphere object and a small sphere object in 3-D space. Three vectors are drawn on the small sphere. The vectors point in the directions of the three axes that define the space. Text at the bottom reads: Drag the ball around.](/en-US/docs/Games/Techniques/3D_collision_detection/Bounding_volume_collision_detection_with_THREE.js/screen_shot_2015-10-20_at_15.19.16.png) Using `BoxHelper` ----------------- As an alternative to using raw `Box3` and `Sphere` objects, Three.js has a useful object to make handling **bounding boxes easier: `BoxHelper`** (previously `BoundingBoxHelper`, which has been deprecated). This helper takes a `Mesh` and calculates a bounding box volume for it (including its child meshes). This results in a new box `Mesh` representing the bounding box, which shows the bounding box's shape, and can be passed to the previously seen `setFromObject` method in order to have a bounding box matching the `Mesh`. `BoxHelper` is the **recommended** way to handle 3D collisions with bounding volumes in Three.js. You will miss sphere tests, but the tradeoffs are well worth it. The advantages of using this helper are: * It has an `update()` method that will **resize** its bounding box Mesh if the linked Mesh rotates or changes its dimensions, and update its **position**. * It **takes into account the child meshes** when computing the size of the bounding box, so the original mesh and all its children are wrapped. * We can easily debug collisions by **rendering** the `Mesh`es that `BoxHelper` creates. By default they are created with a `LineBasicMaterial` material (a three.js material for drawing wireframe-style geometries). The main disadvantage is that it **only creates box bounding volumes**, so if you need spheres vs. AABB tests you need to create your own `Sphere` objects. To use it, we need to create a new `BoxHelper` instance and supply the geometry and — optionally — a color that will be used for the wireframe material. We also need to add the newly created object to the `three.js` scene in order to render it. We assume our scene variable to be called `scene`. ```js const knot = new THREE.Mesh( new THREE.TorusKnotGeometry(0.5, 0.1), new THREE.MeshNormalMaterial({}), ); const knotBoxHelper = new THREE.BoxHelper(knot, 0x00ff00); scene.add(knotBoxHelper); ``` In order to also have our actual `Box3` bounding box, we create a new `Box3` object and make it assume the `BoxHelper`'s shape and position. ```js const box3 = new THREE.Box3(); box3.setFromObject(knotBoxHelper); ``` If we change the `Mesh` position, rotation, scale, etc. we need to call the `update()` method so the `BoxHelper` instance matches its linked `Mesh`. We also need to call `setFromObject` again in order to make the `Box3` follow the `Mesh`. ```js knot.position.set(-3, 2, 1); knot.rotation.x = -Math.PI / 4; // update the bounding box so it stills wraps the knot knotBoxHelper.update(); box3.setFromObject(knotBoxHelper); ``` Performing **collision tests** is done in the same way as explained in the above section — we use our Box3 object in the same way as described above. ```js // box vs. box box3.intersectsBox(otherBox3); // box vs. point box3.containsPoint(point.position); ``` ### Demos There are **two demos** you can take a look at on our live demos page. The first one showcases point vs. box collisions using `BoxHelper`. The second one performs box vs. box tests. ![A knot object, a sphere object and a cube object in 3-D space. The knot and the sphere are encompassed by a virtual bounding box. The cube is intersecting the bounding box of the sphere. Text at the bottom reads: Drag the cube around. Press Esc to toggle B-Boxes.](/en-US/docs/Games/Techniques/3D_collision_detection/Bounding_volume_collision_detection_with_THREE.js/screen_shot_2015-10-19_at_12.10.06.png)
Desktop mouse and keyboard controls - Game development
Desktop mouse and keyboard controls =================================== * Previous * Overview: Control mechanisms * Next Now, when we have our mobile controls in place and the game is playable on touch-enabled devices, it would be good to add mouse and keyboard support so the game can be playable on desktop also. That way we can broaden the list of supported platforms. We'll look at this below. It's also easier to test control-independent features like gameplay on desktop if you develop it there, so you don't have to push the files to a mobile device every time you make a change in the source code. **Note:** the Captain Rogers: Battle at Andromeda is built with Phaser and managing the controls is Phaser-based, but it could also be done in pure JavaScript. The good thing about using Phaser is that it offers helper variables and functions for easier and faster development, but it's totally up to you which approach you chose. Pure JavaScript approach ------------------------ Let's think about implementing pure JavaScript keyboard/mouse controls in the game first, to see how it would work. First, we'd need an event listener to listen for the pressed keys: ```js document.addEventListener("keydown", keyDownHandler, false); document.addEventListener("keyup", keyUpHandler, false); ``` Whenever any key is pressed down, we're executing the `keyDownHandler` function, and when press finishes we're executing the `keyUpHandler` function, so we know when it's no longer pressed. To do that, we'll hold the information on whether the keys we are interested in are pressed or not: ```js let rightPressed = false; let leftPressed = false; let upPressed = false; let downPressed = false; ``` Then we will listen for the `keydown` and `keyup` events and act accordingly in both handler functions. Inside them we can get the code of the key that was pressed from the keyCode property of the event object, see which key it is, and then set the proper variable. There are no helpers so you have to remember what the given codes are (or look them up); `37` is the left arrow: ```js function keyDownHandler(event) { if (event.keyCode === 39) { rightPressed = true; } else if (event.keyCode === 37) { leftPressed = true; } if (event.keyCode === 40) { downPressed = true; } else if (event.keyCode === 38) { upPressed = true; } } ``` The `keyUpHandler` looks almost exactly the same as the `keyDownHandler` above, but instead of setting the pressed variables to `true`, we would set them to `false`. If the left arrow is pressed (`⬅︎`; key code 37), we can set the `leftPressed` variable to `true` and in the `draw` function perform the action assigned to it — move the ship left: ```js function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); if (rightPressed) { playerX += 5; } else if (leftPressed) { playerX -= 5; } if (downPressed) { playerY += 5; } else if (upPressed) { playerY -= 5; } ctx.drawImage(img, playerX, playerY); requestAnimationFrame(draw); } ``` The `draw` function first clears the whole Canvas — we draw everything from scratch on every single frame. Then the pressed key variables are checked and the `playerX` and `playerY` variables (that we define earlier just after `leftPressed` and the others) holding the position of the ship are adjusted by a given amount, let's say 5 pixels. Then the player's ship is drawn on the screen and the next draw is called from within the requestAnimationFrame. We could write our own `KeyCode` object containing the key codes. For example: ```js const KeyboardHelper = { left: 37, up: 38, right: 39, down: 40 }; ``` That way instead of using the codes to compare the input in the handler functions, we could do something like this, which is arguably easier to remember: ```js leftPressed = event.keyCode === KeyboardHelper.left; ``` **Note:** You can also find a list of the different keycodes and what keys they relate to in the keyCode reference page. ![Pure JavaScript demo containing player's ship (with stars in the background) that can be controlled with keyboard and mouse.](/en-US/docs/Games/Techniques/Control_mechanisms/Desktop_with_mouse_and_keyboard/controls-purejsgame.png) You can see this example in action online at end3r.github.io/JavaScript-Game-Controls and the full source code can be found at github.com/end3r/JavaScript-Game-Controls. Phaser approach --------------- As I mentioned before, you can write everything on your own, but you can also take advantage of built-in functions in frameworks like Phaser. These will make your life easier and development a lot faster. All the edge cases--differences between browser implementations, etc.--are handled by the framework, so you can focus on the actual task you want to do. ### Mouse The mouse interactions in the game are focused on clicking the buttons. In Phaser, the buttons you create will take any type of input, whether it's a touch on mobile or a click on desktop. That way, if you already implemented the buttons as shown in the Mobile touch controls article, it will work out of the box on the desktop too: ```js const buttonEnclave = this.add.button( 10, 10, "logo-enclave", this.clickEnclave, this, ); ``` The button will be placed ten pixels from the top left corner of the screen, use the `logo-enclave` image, and will execute the `clickEnclave()` function when clicked. We can assign actions directly to the buttons: ```js this.buttonShoot = this.add.button( this.world.width \* 0.5, 0, "button-alpha", null, this, ); this.buttonShoot.onInputDown.add(this.shootingPressed, this); this.buttonShoot.onInputUp.add(this.shootingReleased, this); ``` The button used for shooting works perfectly fine on both the mobile and desktop approach. If you want to use the mouse's cursor position on the screen, you can do so with `this.game.input.mousePointer`. Let's assume you'd like to shoot a bullet when the right half of the screen is clicked with a mouse, it would be done something like this: ```js if (this.game.input.mousePointer.isDown) { if (this.game.input.mousePointer.x > this.world.width \* 0.5) { // shoot } } ``` If you'd like to differentiate the mouse buttons being pressed, there are three defaults you can pick from: ```js this.game.input.mousePointer.leftButton.isDown; this.game.input.mousePointer.middleButton.isDown; this.game.input.mousePointer.rightButton.isDown; ``` Keep in mind that instead of `mousePointer`, it's better to use `activePointer` for platform-independent input, if you want to keep the support for mobile touch interactions. ### Keyboard The whole game can be controlled with just the keyboard and nothing else. The built-in `this.game.input.keyboard` object manages the input from the keyboard, and has a few helpful methods like `addKey()` and `isDown()`. There's also the Phaser.KeyCode object, which contains all the available keyboard keys: ![A full list of Phaser Key codes available inside the game.](/en-US/docs/Games/Techniques/Control_mechanisms/Desktop_with_mouse_and_keyboard/controls-keycodes.png) In the main menu of the game, we can add an extra way to begin playing. The Start button can be clicked to do so, but we can use the `Enter` key to do the same: ```js const keyEnter = this.game.input.keyboard.addKey(Phaser.KeyCode.ENTER); keyEnter.onDown.add(this.clickStart, this); ``` You can use `addKey()` to add any key the `Phaser.KeyCode` object has to offer. The `onDown()` function is executed whenever the `Enter` key is pressed. It will launch the `clickStart()` method, which starts a new game. It's useful to provide an option to play the game on desktop without using a mouse, so you don't have to take your hands off the keyboard. ### Controlling the game We can support keyboard input in games built with Phaser by enabling the basic cursor keys in the `create()` function using the `createCursorKeys()` function: ```js this.cursors = this.input.keyboard.createCursorKeys(); ``` This creates four directional arrow keys for us: ```js this.cursors.left; this.cursors.right; this.cursors.up; this.cursors.down; ``` You can also define the keys on your own and offer an alternative, `W` `A` `S` `D` control mechanism. For example: ```js this.keyLeft = this.input.keyboard.addKey(Phaser.KeyCode.A); this.keyRight = this.input.keyboard.addKey(Phaser.KeyCode.D); this.keyUp = this.input.keyboard.addKey(Phaser.KeyCode.W); this.keyDown = this.input.keyboard.addKey(Phaser.KeyCode.S); ``` To support both the cursor and `W` `A` `S` `D` keys, we need to do this: ```js if (this.cursors.left.isDown || this.keyLeft.isDown) { // move left } else if (this.cursors.right.isDown || this.keyRight.isDown) { // move right } if (this.cursors.up.isDown || this.keyUp.isDown) { // move up } else if (this.cursors.down.isDown || this.keyDown.isDown) { // move down } ``` In the `update()` function we can now move the player's ship in any direction using one of the two sets of movement key options. We can also offer firing control alternatives. For cursor keys the natural shooting button would be on the other side of the keyboard, so the player can use the other hand — for example the `X` key. For `W` `A` `S` `D` keys it can be the Space bar: ```js this.keyFire1 = this.input.keyboard.addKey(Phaser.KeyCode.X); this.keyFire2 = this.input.keyboard.addKey(Phaser.KeyCode.SPACEBAR); ``` In the `update()` function we can easily check if any of those two were pressed on each frame: ```js if (this.keyFire1.isDown || this.keyFire2.isDown) { // fire the weapon } ``` If yes, then it's time to shoot some bullets! We can even define a secret cheat button: ```js this.keyCheat = this.input.keyboard.addKey(Phaser.KeyCode.C); ``` And then in the `update()` function, whenever `C` is pressed we'll do this: ```js if (this.keyCheat.isDown) { this.player.health = this.player.maxHealth; } ``` We can set the health of the player to maximum. Remember: it's a secret, so *don't tell anyone*! ### How to play We've implemented the controls, and now we should inform the player about their options to control the game. They wouldn't know about them otherwise! When showing the how to play screen where the various ways to control the ship in the game are shown, instead of showing them all to everyone, we can detect whether the game is launched on desktop or mobile and just show the appropriate controls for the device: ```js if (this.game.device.desktop) { moveText = "Arrow keys or WASD to move"; shootText = "X or Space to shoot"; } else { moveText = "Tap and hold to move"; shootText = "Tap to shoot"; } ``` If the game is running on desktop, the cursor and `W` `A` `S` `D` keys message will be shown. If not, then the mobile touch controls message will be. ![How to play screen of a player's ship (with stars in the background) which can be controlled by keyboard and mouse, and the visible message: "arrow keys or WASD to move" and "X or Space to shoot".](/en-US/docs/Games/Techniques/Control_mechanisms/Desktop_with_mouse_and_keyboard/controls-howtoplay.png) To skip the how to play screen, we can listen for any key being pressed and move on: ```js this.input.keyboard.onDownCallback = function () { if (this.stateStatus === "intro") { this.hideIntro(); } }; ``` This hides the intro and starts the actual game without us having to set up another new key control just for this. ### Pause and game over screens To make the game fully playable with the keyboard, it should be possible to go back to the main menu, continue playing, or restart the game from the pause and game over screens. It can be done exactly the same as before, by capturing key codes and performing actions. For example, by specifying `Phaser.KeyCode.Backspace` or `Phaser.KeyCode.Delete` you can hook up an action to fire when the `Delete/Backspace` button is pressed. Summary ------- Ok, we've dealt with touch, keyboard, and mouse controls. Now let's move on to look at how to set up the game to be controlled using a console gamepad, using the Gamepad API. * Previous * Overview: Control mechanisms * Next
Unconventional controls - Game development
Unconventional controls ======================= * Previous * Overview: Control mechanisms Having different control mechanisms in your game helps reach broader audiences. Implementing mobile and desktop controls is recommended is a must, and gamepad controls add that extra experience. But imagine going even further — in this article we will explore various unconventional ways to control your web game, some more unconventional than others. TV remote --------- Playing games on a TV screen doesn't always have to be done through consoles. There's already a Gamepad API working on the desktop computers, so we can imitate the experience, but we can go even further. Modern smart TVs can handle HTML games, because they have a built-in browser that can be used as a gaming platform. Smart TVs are shipped with remote controls, which can be used to control your games if you know how. The earliest demo of Captain Rogers: Battle at Andromeda was adjusted to work on a huge TV. Interestingly enough, the first Captain Rogers game (Asteroid Belt of Sirius) was optimized for low-end, small-screen, cheap smartphones running Firefox OS, so you can see the difference three years can make — you can read the whole story in our Building games for Firefox OS TV Hacks post. ![Panasonic TV remote controls for the game Captain Rogers: Battle at Andromeda.](/en-US/docs/Games/Techniques/Control_mechanisms/Other/controls-tvremote.png) Using a TV remote to control the game ended up being surprisingly easy, because the events fired by the controller are emulating conventional keyboard keys. Captain Rogers had the keyboard controls implemented already: ```js this.cursors = this.input.keyboard.createCursorKeys(); // … if (this.cursors.right.isDown) { // move player right } ``` It works out of the box. The cursors are the four directional arrow keys on the keyboard, and these have exactly the same key codes as the arrow keys on the remote. How do you know the codes for the other remote keys? You can check them by printing the responses out in the console: ```js window.addEventListener( "keydown", (event) => { console.log(event.keyCode); }, true, ); ``` Every key pressed on the remote will show its key code in the console. You can also check this handy cheat sheet seen below if you're working with Panasonic TVs running Firefox OS: ![Remote control key codes for Panasonic TV.](/en-US/docs/Games/Techniques/Control_mechanisms/Other/controls-tvkeys.png) You can add moving between states, starting a new game, controlling the ship and blowing stuff up, pausing and restarting the game. All that is needed is checking for key presses: ```js window.addEventListener( "keydown", (event) => { switch (event.keyCode) { case 8: { // Pause the game break; } case 588: { // Detonate bomb break; } // … } }, true, ); ``` You can see it in action by watching this video. Leap Motion ----------- Have you ever thought about controlling a game only with your hands? It's possible with Leap Motion, an immersive controller for games and apps. Leapmotion is becoming more and more popular due to very good integration with VR headsets — demoing Rainbow Membrane on an Oculus Rift with Leap Motion attached to it was voted one of the best WebVR experiences by JavaScript developers visiting demo booths at conferences around the world. As well as being great for virtual interfaces, it can also be used for a casual 2D gaming experiences. It would be very difficult to do everything with only your hands, but it's totally doable for the simple Captain Roger's gameplay — steering the ship and shooting the bullets. There's a good Hello World tutorial available on the Leap Motion documentation pages, which will get you through the basics. You can also check out the tutorial about using the Leap Motion plugin for Kiwi.js, or the case study of building a web game with Leap Motion and Pixi.js. Be sure to visit the LeapJS repository on GitHub to learn about the JavaScript client for the Leap Motion controller and read the documentation there. If all else fails, there's also a gallery of working examples you can look at. To get the Leap Motion working on your computer you have to first install it by following the steps at docs.ultraleap.com. When everything is installed and the controller is connected to your computer we can proceed with implementing support in our little demo. First, we add a `<script>` tag with the `url` pointing at this file, and add `<div id="output"></div>` just before the closing `</body>` tag for outputting diagnostic information. We will need a few helper variables for our code to work — one for the purpose of calculating the degrees from radians, two for holding the horizontal and vertical amount of degrees our hand is leaning above the controller, one for the threshold of that lean, and one for the state of our hand's grab status. We next add these lines after all the event listeners for keyboard and mouse, but before the `draw` method: ```js const toDegrees = 1 / (Math.PI / 180); let horizontalDegree = 0; let verticalDegree = 0; const degreeThreshold = 30; let grabStrength = 0; ``` Right after that we use the Leap's `loop` method to get the information held in the `hand` variable on every frame: ```js Leap.loop({ hand(hand) { horizontalDegree = Math.round(hand.roll() \* toDegrees); verticalDegree = Math.round(hand.pitch() \* toDegrees); grabStrength = hand.grabStrength; output.innerHTML = `Leap Motion: <br />` + ` roll: ${horizontalDegree}° <br />` + ` pitch: ${verticalDegree}° <br />` + ` strength: ${grabStrength}`; }, }); ``` The code above is calculating and assigning the `horizontalDegree`, `verticalDegree` and `grabStrength` values that we will use later on, and outputting it in HTML so we can see the actual values. When those variables are up-to-date, we can use them in the `draw()` function to move the ship: ```js function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // … if (horizontalDegree > degreeThreshold) { playerX -= 5; } else if (horizontalDegree < -degreeThreshold) { playerX += 5; } if (verticalDegree > degreeThreshold) { playerY += 5; } else if (verticalDegree < -degreeThreshold) { playerY -= 5; } if (grabStrength === 1) { alert("BOOM!"); } ctx.drawImage(img, playerX, playerY); requestAnimationFrame(draw); } ``` If the `horizontalDegree` value is greater than our `degreeThreshold`, which is 30 in this case, then the ship will be moved left 5 pixels on every frame. If its value is lower than the threshold's negative value, then the ship is moved right. Up/down movement works in the same sort of way. The last value is `grabStrength`, which is a float between 0 and 1 — when reaching 1 (fist fully clenched), we show an alert for now (in a full game this could be replaced with the shooting logic). ![Leap Motion controller support in the game, with visible output for roll, pitch and strength.](/en-US/docs/Games/Techniques/Control_mechanisms/Other/controls-leapmotion.png) That's it — everything you needed for a working Leap Motion example in JavaScript is here already. You can explore the `hand`'s properties and implement any behavior you like right inside your game. Doppler effect -------------- There's a very interesting article available on Motion sensing using the doppler effect, which mixes together waving your hand and using the microphone. This time it's about detecting sound waves bouncing off objects and returning to the microphone. ![Doppler effect as a way to control the scroll of an article on a laptop using hand gesture.](/en-US/docs/Games/Techniques/Control_mechanisms/Other/controls-doppler.png) If the frequency of the bounced sound is shifted from the original one, then we can detect that the movement of that object occurred. That way we can detect a hand movement by using only a built-in microphone! This can be accomplished using a small library created by Daniel Rapp — it can be as simple as calculating the difference between two frequencies: ```js doppler.init((bandwidth) => { const diff = bandwidth.left - bandwidth.right; }); ``` The `diff` would be the difference between the initial position of the hand and the final one. This approach won't give us the full flexibility of using a Gamepad, or even Leap Motion, but it's definitely an interesting, unconventional alternative. You can use it to scroll a page hands-free, or play theremin, but it should also be enough to move the ship up and down the screen if implemented correctly. MaKey MaKey ----------- If you want to go completely bananas you can use MaKey MaKey, a board that can turn anything into a controller — it's all about connecting real-world, conductive objects to a computer and using them as touch interfaces. ![Controlling a banana piano using Makey Makey.](/en-US/docs/Games/Techniques/Control_mechanisms/Other/controls-banana.png) Check out the banana piano video, and be sure to visit the quick start guide for all the needed info. There's even a Cylon.js-supported Makey Button functionality inspired by the MaKey MaKey board, so you can use the popular Cylon robotics framework for your experiments with Arduino or Raspberry Pi. Connecting the boards and using them may look like this: ```js const Cylon = require("cylon"); Cylon.robot({ connections: { arduino: { adaptor: "firmata", port: "/dev/ttyACM0" }, }, devices: { makey: { driver: "makey-button", pin: 2 }, }, work(my) { my.makey.on("push", () => { console.log("Button pushed!"); }); }, }).start(); ``` As the description says: this GPIO driver allows you to connect a 10 MOhm resistor to a digital pin on your Arduino or Raspberry Pi to control your robots with bananas, clay, or drawable circuitry. Summary ------- I hope you liked the experiments — if you have any others that you think might interest other people, feel free to add details of them here. And remember: have fun making games! * Previous * Overview: Control mechanisms
Mobile touch controls - Game development
Mobile touch controls ===================== * Overview: Control mechanisms * Next The future of mobile gaming is definitely web, and many developers choose the mobile first approach in their game development process — in the modern world, this generally also involves implementing touch controls. In this tutorial, we will see how easy it is to implement mobile controls in an HTML game, and enjoy playing on a mobile touch-enabled device. **Note:** The game Captain Rogers: Battle at Andromeda is built with Phaser and managing the controls is Phaser-based, but it could also be done in pure JavaScript. The good thing about using Phaser is that it offers helper variables and functions for easier and faster development, but it's entirely up to you which approach you to choose. Pure JavaScript approach ------------------------ We could implement touch events on our own — setting up event listeners and assigning relevant functions to them would be quite straightforward: ```js const el = document.querySelector("canvas"); el.addEventListener("touchstart", handleStart); el.addEventListener("touchmove", handleMove); el.addEventListener("touchend", handleEnd); el.addEventListener("touchcancel", handleCancel); ``` This way, touching the game's `<canvas>` on the mobile screen would emit events, and thus we could manipulate the game in any way we want (for example, moving the spaceship around). The events are as follows: * touchstart is fired when the user puts a finger on the screen. * touchmove is fired when they move the finger on the screen while touching it * touchend is fired when the user stops touching the screen * touchcancel is fired when a touch is cancelled, for example when the user moves their finger out of the screen. **Note:** The touch events reference article provides more examples and information. ### Pure JavaScript demo Let's implement the mobile support in a little demo available on GitHub, so we can move the player's ship by touching the screen on a mobile device. We will use two events: `touchstart` and `touchmove`, both handled by one function. Why? The function `touchHandler` will assign proper variables to the ship's position so that we can use it for both cases: when the player touches the screen but doesn't move it (`touchstart`), and when the finger is moved on the screen (`touchmove`): ```js document.addEventListener("touchstart", touchHandler); document.addEventListener("touchmove", touchHandler); ``` The `touchHandler` function looks like this: ```js function touchHandler(e) { if (e.touches) { playerX = e.touches[0].pageX - canvas.offsetLeft - playerWidth / 2; playerY = e.touches[0].pageY - canvas.offsetTop - playerHeight / 2; output.textContent = `Touch: x: ${playerX}, y: ${playerY}`; e.preventDefault(); } } ``` If the touch occurs (`touches` object is not empty), then we will have all the info we need in that object. We can get the first touch (`e.touches[0]`, our example is not multitouch-enabled), extract the `pageX` and `pageY` variables and set the player's ship position on the screen by subtracting the Canvas offset (distance from the Canvas and the edge of the screen) and half the player's width and height. ![Touch controls for the player's ship, with visible output of the x and y position.](/en-US/docs/Games/Techniques/Control_mechanisms/Mobile_touch/controls-touch.png) To see if it's working correctly we can output the `x` and `y` positions using the `output` element. The `preventDefault()` function is needed to prevent the browser from moving — without it, you'd have the default behavior, and the Canvas would be dragged around the page, which would show the browser scroll bars and look messy. Touch events in Phaser ---------------------- We don't have to do this on our own; frameworks like Phaser offer systems for managing touch events for us — see managing the touch events. ### Pointer theory A pointer represents a single finger on the touch screen. Phaser starts two pointers by default, so two fingers can perform an action at once. Captain Rogers is a simple game — it can be controlled by two fingers, the left one moving the ship and the right one controlling the ship's gun. There's no multitouch or gestures — everything is handled by single pointer inputs. You can add more pointers to the game by using; `this.game.input.addPointer` up to ten pointers can be managed simultaneously. The most recently used pointer is available in the `this.game.input.activePointer` object — the most recent finger active on the screen. If you need to access a specific pointer, they are all available at, `this.game.input.pointer1`, `this.game.input.pointer2`, etc. They are assigned dynamically, so if you put three fingers on the screen, then, `pointer1`, `pointer2`, and `pointer3` will be active. Removing the second finger, for example, won't affect the other two, and setting it back again will use the first available property, so `pointer2` will be used again. You can quickly get the coordinates of the most recently active pointer via the `this.game.input.x` and `this.game.input.y` variables. ### Input events Instead of using the pointers directly it is also possible to listen for `this.game.input` events, like `onDown`, `onUp`, `onTap` and `onHold`: ```js this.game.input.onDown.add(itemTouched, this); function itemTouched(pointer) { // Do something } ``` The `itemTouched()` function will be executed when the `onDown` event is dispatched by touching the screen. The `pointer` variable will contain the information about the pointer that activated the event. This approach uses the generally available `this.game.input` object, but you can also detect the actions on any game objects like sprites or buttons by using `onInputOver`, `onInputOut`, `onInputDown`, `onInputUp`, `onDragStart`, or `onDragStop`: ```js this.button.events.onInputOver.add(itemTouched, this); function itemTouched(button, pointer) { // Do something } ``` That way you'll be able to attach an event to any object in the game, like the player's ship, and react to the actions performed by the user. An additional advantage of using Phaser is that the buttons you create will take any type of input, whether it's a touch on mobile or a click on desktop — the framework sorts this out in the background for you. ### Implementation The easiest way to add an interactive object that will listen for user input is to create a button: ```js const buttonEnclave = this.add.button( 10, 10, "logo-enclave", this.clickEnclave, this, ); ``` This one is formed in the `MainMenu` state — it will be placed ten pixels from the top left corner of the screen, use the `logo-enclave` image, and execute the `clickEnclave()` function when it is touched. This will work on mobile and desktop out of the box. There are a few buttons in the main menu, including the one that will start the game. For the actual gameplay, instead of creating more buttons and covering the small mobile screen with them, we can use something a little different: we'll create invisible areas which respond to the given action. From a design point of view, it is better to make the field of activity bigger without covering half of the screen with button images. For example, tapping on the right side of the screen will fire the weapon: ```js this.buttonShoot = this.add.button( this.world.width \* 0.5, 0, "button-alpha", null, this, ); this.buttonShoot.onInputDown.add(this.goShootPressed, this); this.buttonShoot.onInputUp.add(this.goShootReleased, this); ``` The code above will create a new button using a transparent image that covers the right half of the screen. You can assign functions on input down and input up separately if you'd like to perform more complicated actions, but in this game touching the right side of the screen will fire the bullets to the right — this is all we need in this case. Moving the player could be managed by creating the four directional buttons, but we can take the advantage of touch screens and drag the player's ship around: ```js const player = this.game.add.sprite(30, 30, "ship"); player.inputEnabled = true; player.input.enableDrag(); player.events.onDragStart.add(onDragStart, this); player.events.onDragStop.add(onDragStop, this); function onDragStart(sprite, pointer) { // Do something when dragging } ``` We can pull the ship around and do something in the meantime, and react when the drag is stopped. Hauling in Phaser, if enabled, will work out of the box — you don't have to set the position of the sprite yourself manually, so you could leave the `onDragStart()` function empty, or place some debug output to see if it's working correctly. The `pointer` element contains the `x` and `y` variables storing the current position of the dragged element. ### Dedicated plugins You could go even further and use dedicated plugins like Virtual Joystick — this is a paid, official Phaser plugin, but you can find free and open source alternatives. The initialization of Virtual Joystick looks like this: ```js this.pad = this.game.plugins.add(Phaser.VirtualJoystick); this.stick = this.pad.addStick(30, 30, 80, "generic"); ``` In the `create()` function of the `Game` state we're creating a virtual pad and a generic stick that has four directional virtual buttons by default. This is placed 30 pixels from the top and left edges of the screen and is 80 pixels wide. The stick being pressed can be handled during the gameplay in the `update` function like so: ```js if (this.stick.isDown) { // Move the player } ``` We can adjust the player's velocity based on the current angle of the stick and move him appropriately. Summary ------- That covers adding touch controls for mobile; in the next article we'll see how to add keyboard and mouse support. * Overview: Control mechanisms * Next
Desktop gamepad controls - Game development
Desktop gamepad controls ======================== * Previous * Overview: Control mechanisms * Next Now we'll look at adding something extra — support for gamepad controls, via the Gamepad API. It brings a console-like experience to your web games. The Gamepad API gives you the ability to connect a gamepad to your computer and detect pressed buttons directly from the JavaScript code thanks to the browsers implementing such feature. An API exposes all the information you need to hook up your game's logic and successfully control the user interface and gameplay. API status, browser and hardware support ---------------------------------------- The Gamepad API is still in Working Draft status, although browser support is already quite good — around 63% global coverage, according to caniuse.com. The list of supported devices is also quite extensive — most popular gamepads (e.g. XBox 360 or PS3) should be suitable for web implementations. Pure JavaScript approach ------------------------ Let's think about implementing pure JavaScript gamepad controls in our little controls demo first to see how it would work. First, we need an event listener to listen for the connection of the new device: ```js window.addEventListener("gamepadconnected", gamepadHandler); ``` It's executed once, so we can create some variables we will need later on for storing the controller info and the pressed buttons: ```js let controller = {}; let buttonsPressed = []; function gamepadHandler(e) { controller = e.gamepad; output.textContent = `Gamepad: ${controller.id}`; } ``` The second line in the `gamepadHandler` function shows up on the screen when the device is connected: ![Gamepad connected message under the Captain Rogers game - wireless XBox 360 controller.](/en-US/docs/Games/Techniques/Control_mechanisms/Desktop_with_gamepad/controls-gamepadtext.png) We can also show the `id` of the device — in the case above we're using the XBox 360 wireless controller. To update the state of the gamepad's currently pressed buttons we will need a function that will do exactly that on every frame: ```js function gamepadUpdateHandler() { buttonsPressed = []; if (controller.buttons) { for (let b = 0; b < controller.buttons.length; b++) { if (controller.buttons[b].pressed) { buttonsPressed.push(b); } } } } ``` We first reset the `buttonsPressed` array to get it ready to store the latest info we'll write to it from the current frame. Then, if the buttons are available we loop through them; if the `pressed` property is set to `true`, then we add them to the `buttonsPressed` array for later processing. Next, we'll consider the `gamepadButtonPressedHandler()` function: ```js function gamepadButtonPressedHandler(button) { let press = false; for (let i = 0; i < buttonsPressed.length; i++) { if (buttonsPressed[i] === button) { press = true; } } return press; } ``` The function takes a button as a parameter; in the loop it checks if the given button's number is among the currently pressed buttons available in the `buttonsPressed` array. If it is, then the function returns `true`; `false` otherwise. Next, in the `draw()` function we do two things — execute the `gamepadUpdateHandler()` function to get the current state of pressed buttons on every frame, and use the `gamepadButtonPressedHandler()` function to check the buttons we are interested to see whether they are pressed, and do something if they are: ```js function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // … gamepadUpdateHandler(); if (gamepadButtonPressedHandler(0)) { playerY -= 5; } else if (gamepadButtonPressedHandler(1)) { playerY += 5; } if (gamepadButtonPressedHandler(2)) { playerX -= 5; } else if (gamepadButtonPressedHandler(3)) { playerX += 5; } if (gamepadButtonPressedHandler(11)) { alert("BOOM!"); } // … ctx.drawImage(img, playerX, playerY); requestAnimationFrame(draw); } ``` In this case, we are checking the four D-Pad buttons (0-3) and the A button (11). **Note:** Please remember that different devices may have different key mappings, i.e. the D-Pad Right button have an index of 3 on the wireless XBox 360, but may have a different one on another device. You could also create a helper function that would assign proper names to the listed buttons, so for example instead of checking out if `gamepadButtonPressedHandler(3)` is pressed, you could do a more descriptive check: `gamepadButtonPressedHandler('DPad-Right')`. You can see a live demo in action — try connecting your gamepad and pressing the buttons. Phaser approach --------------- Let's move on to the final Gamepad API implementation in the Captain Rogers: Battle at Andromeda game we created with Phaser. This is pure JavaScript code however too, so can be used in any other project no matter what framework was used. First off, we'll create a small library that will take care of handling the input for us. Here's the `GamepadAPI` object, which contains useful variables and functions: ```js const GamepadAPI = { active: false, controller: {}, connect(event) {}, disconnect(event) {}, update() {}, buttons: { layout: [], cache: [], status: [], pressed(button, state) {}, }, axes: { status: [], }, }; ``` The `controller` variable stores the information about the connected gamepad, and there's an `active` boolean variable we can use to know if the controller is connected or not. The `connect()` and `disconnect()` functions are bound to the following events: ```js window.addEventListener("gamepadconnected", GamepadAPI.connect); window.addEventListener("gamepaddisconnected", GamepadAPI.disconnect); ``` They are fired when the gamepad is connected and disconnected respectively. The next function is `update()`, which updates the information about the pressed buttons and axes. The `buttons` variable contains the `layout` of a given controller (for example which buttons are where, because an XBox 360 layout may be different to a generic one), the `cache` containing the information about the buttons from the previous frame and the `status` containing the information from the current frame. The `pressed()` function gets the input data and sets the information about it in our object, and the `axes` property stores the array containing the values signifying the amount an axis is pressed in the `x` and `y` directions, represented by a float in the `(-1, 1)` range. After the gamepad is connected, the information about the controller is stored in the object: ```js connect(event) { GamepadAPI.controller = event.gamepad; GamepadAPI.active = true; }, ``` The `disconnect` function removes the information from the object: ```js disconnect(event) { delete GamepadAPI.controller; GamepadAPI.active = false; }, ``` The `update()` function is executed in the update loop of the game on every frame, so it contains the latest information on the pressed buttons: ```js update() { GamepadAPI.buttons.cache = []; for (let k = 0; k < GamepadAPI.buttons.status.length; k++) { GamepadAPI.buttons.cache[k] = GamepadAPI.buttons.status[k]; } GamepadAPI.buttons.status = []; const c = GamepadAPI.controller || {}; const pressed = []; if (c.buttons) { for (let b = 0; b < c.buttons.length; b++) { if (c.buttons[b].pressed) { pressed.push(GamepadAPI.buttons.layout[b]); } } } const axes = []; if (c.axes) { for (let a = 0; a < c.axes.length; a++) { axes.push(c.axes[a].toFixed(2)); } } GamepadAPI.axes.status = axes; GamepadAPI.buttons.status = pressed; return pressed; }, ``` The function above clears the buttons cache, and copies their status from the previous frame to the cache. Next, the button status is cleared and the new information is added. The same goes for the axes' information — looping through axes adds the values to the array. Received values are assigned to the proper objects and returns the pressed info for debugging purposes. The `button.pressed()` function detects the actual button presses: ```js pressed(button, hold) { let newPress = false; for (let i = 0; i < GamepadAPI.buttons.status.length; i++) { if (GamepadAPI.buttons.status[i] === button) { newPress = true; if (!hold) { for (let j = 0; j < GamepadAPI.buttons.cache.length; j++) { if (GamepadAPI.buttons.cache[j] === button) { newPress = false; } } } } } return newPress; }, ``` It loops through pressed buttons and if the button we're looking for is pressed, then the corresponding boolean variable is set to `true`. If we want to check the button is not held already (so it's a new press), then looping through the cached states from the previous frame does the job — if the button was already pressed, then we ignore the new press and set it to `false`. Implementation -------------- We now know what the `GamepadAPI` object looks like and what variables and functions it contains, so let's learn how all this is actually used in the game. To indicate that the gamepad controller is active we can show the user some custom text on the game's main menu screen. The `textGamepad` object holds the text saying a gamepad has been connected, and is hidden by default. Here's the code we've prepared in the `create()` function that is executed once when the new state is created: ```js create() { // … const message = 'Gamepad connected! Press Y for controls'; const textGamepad = this.add.text(0, 0, message); textGamepad.visible = false; } ``` In the `update()` function, which is executed every frame, we can wait until the controller is actually connected, so the proper text can be shown. Then we can keep the track of the information about pressed buttons by using the `Gamepad.update()` method, and react to the given information: ```js update() { // … if (GamepadAPI.active) { this.textGamepad.visible = true; GamepadAPI.update(); if (GamepadAPI.buttons.pressed('Start')) { // start the game } if (GamepadAPI.buttons.pressed('X')) { // turn on/off the sounds } this.screenGamepadHelp.visible = GamepadAPI.buttons.pressed('Y', 'hold'); } } ``` When pressing the `Start` button the relevant function will be called to begin the game, and the same approach is used for turning the audio on and off. There's an option wired up to show `screenGamepadHelp`, which holds an image with all the button controls explained — if the `Y` button is pressed and held, the help becomes visible; when it is released the help disappears. ![Gamepad info with all the available keys described and explained.](/en-US/docs/Games/Techniques/Control_mechanisms/Desktop_with_gamepad/controls-gamepadinfo.png) On-screen instructions ---------------------- When the game is started, some introductory text is shown that shows you available controls — we are already detecting if the game is launched on desktop or mobile then showing a relevant message for the device, but we can go even further, to allow for the presence of a gamepad: ```js create() { // … if (this.game.device.desktop) { if (GamepadAPI.active) { moveText = 'DPad or left Stick\nto move'; shootText = 'A to shoot,\nY for controls'; } else { moveText = 'Arrow keys\nor WASD to move'; shootText = 'X or Space\nto shoot'; } } else { moveText = 'Tap and hold to move'; shootText = 'Tap to shoot'; } } ``` When on desktop, we can check if the controller is active and show the gamepad controls — if not, then the keyboard controls will be shown. Gameplay controls ----------------- We can offer even more flexibility to the player by giving him main and alternative gamepad movement controls: ```js if (GamepadAPI.buttons.pressed("DPad-Up", "hold")) { // move player up } else if (GamepadAPI.buttons.pressed("DPad-Down", "hold")) { // move player down } if (GamepadAPI.buttons.pressed("DPad-Left", "hold")) { // move player left } if (GamepadAPI.buttons.pressed("DPad-Right", "hold")) { // move player right } if (GamepadAPI.axes.status) { if (GamepadAPI.axes.status[0] > 0.5) { // move player up } else if (GamepadAPI.axes.status[0] < -0.5) { // move player down } if (GamepadAPI.axes.status[1] > 0.5) { // move player left } else if (GamepadAPI.axes.status[1] < -0.5) { // move player right } } ``` They can now move the ship on the screen by using the `DPad` buttons, or the left stick axes. Have you noticed that the current value of the axes is evaluated against `0.5`? It's because axes are having floating point values while buttons are booleans. After a certain threshold is reached we can assume the input is done deliberately by the user and can act accordingly. For the shooting controls, we used the `A` button — when it is held down, a new bullet is spawned, and everything else is handled by the game: ```js if (GamepadAPI.buttons.pressed("A", "hold")) { this.spawnBullet(); } ``` Showing the screen with all the controls looks exactly the same as in the main menu: ```js this.screenGamepadHelp.visible = GamepadAPI.buttons.pressed("Y", "hold"); ``` If the `B` button is pressed, the game is paused: ```js if (gamepadAPI.buttonPressed("B")) { this.managePause(); } ``` The paused and gameover states ------------------------------ We already learned how to control the whole lifecycle of the game: pausing the gameplay, restarting it, or getting back to the main menu. It works smooth on mobile and desktop, and adding gamepad controls is just as straightforward — in the `update()` function, we check to see if the current state status is `paused` — if so, the relevant actions are enabled: ```js if (GamepadAPI.buttons.pressed("Start")) { this.managePause(); } if (GamepadAPI.buttons.pressed("Back")) { this.stateBack(); } ``` Similarly, when the `gameover` state status is active, then we can allow the user to restart the game instead of continuing it: ```js if (GamepadAPI.buttons.pressed("Start")) { this.stateRestart(); } if (GamepadAPI.buttons.pressed("Back")) { this.stateBack(); } ``` When the game over screen is visible, the `Start` button restarts the game while the `Back` button helps us get back to the main menu. The same goes for when the game is paused: the `Start` button unpauses the game and the `Back` button goes back, just like before. Summary ------- That's it! We have successfully implemented gamepad controls in our game — try connecting any popular controller like the XBox 360 one and see for yourself how fun it is to avoid the asteroids and shoot the aliens with a gamepad. Now we can move on and explore new, even more unconventional ways to control the HTML game like waving your hand in front of the laptop or screaming into your microphone. * Previous * Overview: Control mechanisms * Next
asm.js - Game development
asm.js ====== **Warning:** The asm.js specification is considered **deprecated**. Developers may look to WebAssembly as an alternative to asm.js for running high-performance code in the browser. Asm.js is a specification defining a subset of JavaScript that is highly optimizable. This article looks at exactly what is permitted in the asm.js subset, what improvements it confers, where and how you can make use of it, and further resources and examples. What is asm.js, exactly? ------------------------ It is a very small, strict subset of JavaScript that only allows things like `while`, `if`, numbers, top-level named functions, and other simple constructs. It does not allow objects, strings, closures, and basically anything that requires heap allocation. Asm.js code resembles C in many ways, but it's still completely valid JavaScript that will run in all current engines. It pushes JS engines to optimize this kind of code, and gives compilers like Emscripten a clear definition of what kind of code to generate. We will show what asm.js code looks like and explain how it helps and how you can use it. This subset of JavaScript is already highly optimized in many JavaScript engines using fancy Just-In-Time (JIT) compiling techniques. However, by defining an explicit standard we can work on optimizing this kind of code even more and getting as much performance as we can out of it. It makes it easier to collaborate across multiple JS engines because it's easy to talk about and benchmark. The idea is that this kind of code **should** run very fast in each engine, and if it doesn't, it's a bug and there's a clear spec that engines should optimize for. It also makes it easy for people writing compilers that want to generate high-performant code on the web. They can consult the asm.js spec and know that it will run fast if they adhere to asm.js patterns. Emscripten, a C/C++ to JavaScript compiler, emits asm.js code to make it run with near native performance on several browsers. Additionally, if an engine chooses to specially recognize asm.js code, there even more optimizations that can be made. Firefox is the only browser to do this right now. asm.js language summary ----------------------- asm.js is an intermediate programming language. asm.js has a very predictable performance rate because it is limited to an extremely restricted subset of JavaScript that provides only strictly-typed integers, floats, arithmetic, function calls, and heap accesses. The performance characteristics are closer to native code than that of standard JavaScript. Using a subset of JavaScript asm.js is already supported by major web browsers. Since asm.js runs in a browser it depends heavily on the browser and the hardware.
Touch Event Horizon - Game development
Touch Event Horizon =================== This article is for Touch Event Horizon and A Game Related To It Touch Gestures and Events ------------------------- Link The example game ---------------- ![Box with the text touch to start](/en-US/docs/Games/Tutorials/Touch_Event_Horizon/touch-to-start.png) ![Two circles placed side-by-side, one bigger than the other. The size of the circle represents a player's score. The scores are written above each circle.](/en-US/docs/Games/Tutorials/Touch_Event_Horizon/tapping.png) GitHub repository Live demo ### Setting up the canvas ### Counting the taps touchstart, touchend ### Collecting the bonus touchmove Future developments ------------------- Summary ------- This tutorial shows how to use Touch Events to create a game on a <canvas>. This is a multiplayer game relying on the Tap and Drag gestures.
2D breakout game using pure JavaScript - Game development
2D breakout game using pure JavaScript ====================================== * Next » In this step-by-step tutorial we create a simple **MDN Breakout** game written entirely in pure JavaScript and rendered on HTML `<canvas>`. Every step has editable, live samples available to play with so you can see what the intermediate stages should look like. You will learn the basics of using the `<canvas>` element to implement fundamental game mechanics like rendering and moving images, collision detection, control mechanisms, and winning and losing states. To get the most out of this series of articles you should already have basic to intermediate JavaScript knowledge. After working through this tutorial you should be able to build your own simple Web games. ![Gameplay screen from the game MDN Breakout where you can use your paddle to bounce the ball and destroy the brick field, with keeping the score and lives.](/en-US/docs/Games/Tutorials/2D_Breakout_game_pure_JavaScript/mdn-breakout-gameplay.png) Lesson details -------------- All the lessons — and the different versions of the MDN Breakout game we are building together — are available on GitHub: 1. Create the Canvas and draw on it 2. Move the ball 3. Bounce off the walls 4. Paddle and keyboard controls 5. Game over 6. Build the brick field 7. Collision detection 8. Track the score and win 9. Mouse controls 10. Finishing up Starting with pure JavaScript is the best way to get a solid knowledge of web game development. After that, you can pick any framework you like and use it for your projects. Frameworks are just tools built with the JavaScript language; so even if you plan on working with them, it's good to learn about the language itself first to know what exactly is going on under the hood. Frameworks speed up development time and help take care of boring parts of the game, but if something is not working as expected, you can always try to debug that or just write your own solutions in pure JavaScript. **Note:** If you are interested in learning about 2D web game development using a game library, consult this series' counterpart, 2D breakout game using Phaser. **Note:** This series of articles can be used as material for hands-on game development workshops. You can also make use of the Gamedev Canvas Content Kit based on this tutorial if you want to give a talk about game development in general. Next steps ---------- Ok, let's get started! Head to the first chapter— Create the Canvas and draw on it. * Next »
2D maze game with device orientation - Game development
2D maze game with device orientation ==================================== In this tutorial we'll go through the process of building an HTML mobile game that uses the Device Orientation and Vibration **APIs** to enhance the gameplay and is built using the Phaser framework. Basic JavaScript knowledge is recommended to get the most from this tutorial. Example game ------------ By the end of the tutorial you will have a fully functional demo game: Cyber Orb. It will look something like this: ![A 2D game board featuring a small yellow ball. There is a large black hole for the ball to escape down, and a number of barriers blocking the ball from escaping.](/en-US/docs/Games/Tutorials/HTML5_Gamedev_Phaser_Device_Orientation/cyber-orb.png) Phaser framework ---------------- Phaser is a framework for building desktop and mobile HTML games. It's quite new, but growing rapidly thanks to the passionate community involved in the development process. You can check it out on GitHub where it's open sourced, read the online documentation and go through the big collection of examples. The Phaser framework provides you with a set of tools that will speed up development and help handle generic tasks needed to complete the game, so you can focus on the game idea itself. Starting with the project ------------------------- You can see Cyber Orb source code on GitHub. The folder structure is quite straightforward: the starting point is the `index.html` file where we initialize the framework and set up an `<canvas>` to render the game on. ![Screenshot of the GitHub repository with the Cyber Orb game code, listing the folders and the files in the main structure.](/en-US/docs/Games/Tutorials/HTML5_Gamedev_Phaser_Device_Orientation/cyber-orb-github.png) You can open the index file in your favorite browser to launch the game and try it. There are also three folders in the directory: * `img`: All the images that we will use in the game. * `src`: The JavaScript files with all the source code of the game defined inside. * `audio:` The sound files used in the game. Setting up the Canvas --------------------- We will be rendering our game on Canvas, but we won't do it manually — this will be taken care of by the framework. Let's set it up: our starting point is the `index.html` file with the following content. You can create this yourself if you want to follow along: ```html <!doctype html> <html lang="en-GB"> <head> <meta charset="utf-8" /> <title>Cyber Orb demo</title> <style> body { margin: 0; background: #333; } </style> <script src="src/phaser-arcade-physics.2.2.2.min.js"></script> <script src="src/Boot.js"></script> <script src="src/Preloader.js"></script> <script src="src/MainMenu.js"></script> <script src="src/Howto.js"></script> <script src="src/Game.js"></script> </head> <body> <script> (() => { const game = new Phaser.Game(320, 480, Phaser.CANVAS, "game"); game.state.add("Boot", Ball.Boot); game.state.add("Preloader", Ball.Preloader); game.state.add("MainMenu", Ball.MainMenu); game.state.add("Howto", Ball.Howto); game.state.add("Game", Ball.Game); game.state.start("Boot"); })(); </script> </body> </html> ``` So far we have a simple HTML website with some basic content in the `<head>` section: charset, title, CSS styling and the inclusion of the JavaScript files. The `<body>` contains initialization of the Phaser framework and the definitions of the game states. ```js const game = new Phaser.Game(320, 480, Phaser.CANVAS, "game"); ``` The line above will initialize the Phaser instance — the arguments are the width of the Canvas, height of the Canvas, rendering method (we're using `CANVAS`, but there are also `WEBGL` and `AUTO` options available) and the optional ID of the DOM container we want to put the Canvas in. If there's nothing specified in that last argument or the element is not found, the Canvas will be added to the <body> tag. Without the framework, to add the Canvas element to the page, you would have to write something like this inside the <body> tag: ```html <canvas id="game" width="320" height="480"></canvas> ``` The important thing to remember is that the framework is setting up helpful methods to speed up a lot of things like image manipulation or assets management, which would be a lot harder to do manually. **Note:** You can read the Building Monster Wants Candy article for the in-depth introduction to the basic Phaser-specific functions and methods. Back to game states: the line below is adding a new state called `Boot` to the game: ```js game.state.add("Boot", Ball.Boot); ``` The first value is the name of the state and the second one is the object we want to assign to it. The `start` method is starting the given state and making it active. Let's see what the states are actually. Managing game states -------------------- The states in Phaser are separate parts of the game logic; in our case we're loading them from independent JavaScript files for better maintainability. The basic states used in this game are: `Boot`, `Preloader`, `MainMenu`, `Howto` and `Game`. `Boot` will take care of initializing a few settings, `Preloader` will load all the assets like graphics and audio, `MainMenu` is the menu with the start button, `Howto` shows the "how to play" instructions and the `Game` state lets you actually play the game. Let's quickly go through the content of those states. ### Boot.js The `Boot` state is the first one in the game. ```js const Ball = { \_WIDTH: 320, \_HEIGHT: 480, }; Ball.Boot = function (game) {}; Ball.Boot.prototype = { preload() { this.load.image("preloaderBg", "img/loading-bg.png"); this.load.image("preloaderBar", "img/loading-bar.png"); }, create() { this.game.scale.scaleMode = Phaser.ScaleManager.SHOW\_ALL; this.game.scale.pageAlignHorizontally = true; this.game.scale.pageAlignVertically = true; this.game.state.start("Preloader"); }, }; ``` The main `Ball` object is defined and we're adding two variables called `_WIDTH` and `_HEIGHT` that are the width and the height of the game Canvas — they will help us position the elements on the screen. We're loading two images first that will be used later in the `Preload` state to show the progress of loading all the other assets. The `create` function holds some basic configuration: we're setting up the scaling and alignment of the Canvas, and moving on to the `Preload` state when everything's ready. ### Preloader.js The `Preloader` state takes care of loading all the assets: ```js Ball.Preloader = function (game) {}; Ball.Preloader.prototype = { preload() { this.preloadBg = this.add.sprite( (Ball._WIDTH - 297) \* 0.5, (Ball._HEIGHT - 145) \* 0.5, "preloaderBg", ); this.preloadBar = this.add.sprite( (Ball._WIDTH - 158) \* 0.5, (Ball._HEIGHT - 50) \* 0.5, "preloaderBar", ); this.load.setPreloadSprite(this.preloadBar); this.load.image("ball", "img/ball.png"); // … this.load.spritesheet("button-start", "img/button-start.png", 146, 51); // … this.load.audio("audio-bounce", [ "audio/bounce.ogg", "audio/bounce.mp3", "audio/bounce.m4a", ]); }, create() { this.game.state.start("MainMenu"); }, }; ``` There are single images, spritesheets and audio files loaded by the framework. In this state the `preloadBar` is showing the progress on the screen. That progress of the loaded assets is visualized by the framework with the use of one image. With every asset loaded you can see more of the `preloadBar` image: from 0% to 100%, updated on every frame. After all the assets are loaded, the `MainMenu` state is launched. ### MainMenu.js The `MainMenu` state shows the main menu of the game, where you can start playing by clicking the button. ```js Ball.MainMenu = function (game) {}; Ball.MainMenu.prototype = { create() { this.add.sprite(0, 0, "screen-mainmenu"); this.gameTitle = this.add.sprite(Ball._WIDTH \* 0.5, 40, "title"); this.gameTitle.anchor.set(0.5, 0); this.startButton = this.add.button( Ball._WIDTH \* 0.5, 200, "button-start", this.startGame, this, 2, 0, 1, ); this.startButton.anchor.set(0.5, 0); this.startButton.input.useHandCursor = true; }, startGame() { this.game.state.start("Howto"); }, }; ``` To create a new button there's `add.button` method with the following list of optional arguments: * Top absolute position on Canvas in pixels. * Left absolute position on Canvas in pixels. * Name of the image asset the button is using. * Function that will be executed when someone clicks the button. * The execution context. * Frame from the image asset used as the button's "hover" state. * Frame from the image asset used as the button's "normal" or "out" state. * Frame from the image asset used as the button's "click" or "down" state. The `anchor.set` is setting up the anchor point on the button for which all the calculations of the position are applied. In our case it's anchored half the way from the left edge and at the start of the top edge, so it can be easily horizontally centered on the screen without the need to know its width. When the start button is pressed, instead of jumping directly into the action the game will show the screen with the information on how to play the game. ### Howto.js ```js Ball.Howto = function (game) {}; Ball.Howto.prototype = { create() { this.buttonContinue = this.add.button( 0, 0, "screen-howtoplay", this.startGame, this, ); }, startGame() { this.game.state.start("Game"); }, }; ``` The `Howto` state shows the gameplay instructions on the screen before starting the game. After clicking the screen the actual game is launched. ### Game.js The `Game` state from the `Game.js` file is where all the magic happens. All the initialization is in the `create()` function (launched once at the beginning of the game). After that some functionality will require further code to control — we will write our own functions to handle more complicated tasks. In particular, take note of the `update()` function (executed at every frame), which updates things such as the ball position. ```js Ball.Game = function (game) {}; Ball.Game.prototype = { create() {}, initLevels() {}, showLevel(level) {}, updateCounter() {}, managePause() {}, manageAudio() {}, update() {}, wallCollision() {}, handleOrientation(e) {}, finishLevel() {}, }; ``` The `create` and `update` functions are framework-specific, while others will be our own creations: * `initLevels` initializes the level data. * `showLevel` prints the level data on the screen. * `updateCounter` updates the time spent playing each level and records the total time spent playing the game. * `managePause` pauses and resumes the game. * `manageAudio` turns the audio on and off. * `wallCollision` is executed when the ball hits the walls or other objects. * `handleOrientation` is the function bound to the event responsible for the Device Orientation API, providing the motion controls when the game is running on a mobile device with appropriate hardware. * `finishLevel` loads a new level when the current level is completed, or finished the game if the final level is completed. #### Adding the ball and its motion mechanics First, let's go to the `create()` function, initialize the ball object itself and assign a few properties to it: ```js this.ball = this.add.sprite(this.ballStartPos.x, this.ballStartPos.y, "ball"); this.ball.anchor.set(0.5); this.physics.enable(this.ball, Phaser.Physics.ARCADE); this.ball.body.setSize(18, 18); this.ball.body.bounce.set(0.3, 0.3); ``` Here we're adding a sprite at the given place on the screen and using the `'ball'` image from the loaded graphic assets. We're also setting the anchor for any physics calculations to the middle of the ball, enabling the Arcade physics engine (which handles all the physics for the ball movement), and setting the size of the body for the collision detection. The `bounce` property is used to set the bounciness of the ball when it hits the obstacles. #### Controlling the ball It's cool to have the ball ready to be thrown around in the play area, but it's also important to be able to actually move it! Now we will add the ability to control the ball with the keyboard on the desktop devices, and then we will move to the implementation of the Device Orientation API. Let's focus on the keyboard first by adding the following to the `create()` function: ```js this.keys = this.game.input.keyboard.createCursorKeys(); ``` As you can see there's a special Phaser function called `createCursorKeys()`, which will give us an object with event handlers for the four arrow keys to play with: up, down, left and right. Next we will add the following code to the `update()` function, so it will be fired on every frame. The `this.keys` object will be checked against player input, so the ball can react accordingly with the predefined force: ```js if (this.keys.left.isDown) { this.ball.body.velocity.x -= this.movementForce; } else if (this.keys.right.isDown) { this.ball.body.velocity.x += this.movementForce; } if (this.keys.up.isDown) { this.ball.body.velocity.y -= this.movementForce; } else if (this.keys.down.isDown) { this.ball.body.velocity.y += this.movementForce; } ``` That way we can check which key is pressed at the given frame and apply the defined force to the ball, thus increase the velocity in the proper direction. #### Implementing the Device Orientation API Probably the most interesting part of the game is its usage of the **Device Orientation API** for control on mobile devices. Thanks to this you can play the game by tilting the device in the direction you want the ball to roll. Here's the code from the `create()` function responsible for this: ```js window.addEventListener("deviceorientation", this.handleOrientation, true); ``` We're adding an event listener to the `"deviceorientation"` event and binding the `handleOrientation` function which looks like this: ```js handleOrientation(e) { const x = e.gamma; const y = e.beta; Ball._player.body.velocity.x += x; Ball._player.body.velocity.y += y; }, ``` The more you tilt the device, the more force is applied to the ball, therefore the faster it moves (the velocity is higher). ![An explanation of the X, Y and Z axes of a Flame mobile device with the Cyber Orb game demo on the screen.](/en-US/docs/Games/Tutorials/HTML5_Gamedev_Phaser_Device_Orientation/cyber-orb-flame-orientation.png) **Note:** To find out more about implementing device orientation and what raw code would look like, read Keep it level: responding to device orientation changes. #### Adding the hole The main objective in the game is to move the ball from the starting position to the ending position: a hole in the ground. Implementation looks very similar to the part where we created the ball, and it's also added in the `create()` function of our `Game` state: ```js this.hole = this.add.sprite(Ball._WIDTH \* 0.5, 90, "hole"); this.physics.enable(this.hole, Phaser.Physics.ARCADE); this.hole.anchor.set(0.5); this.hole.body.setSize(2, 2); ``` The difference is that our hole's body will not move when we hit it with the ball and will have the collision detection calculated (which will be discussed later on in this article). #### Building the block labyrinth To make the game harder and more interesting we will add some obstacles between the ball and the exit. We could use a level editor, but for the sake of this tutorial let's create something on our own. To hold the block information we'll use a level data array: for each block we'll store the top and left absolute positions in pixels (`x` and `y`) and the type of the block — horizontal or vertical (`t` with the `'w'` value meaning width and `'h'` meaning height). Then, to load the level we'll parse the data and show the blocks specific for that level. In the `initLevels` function we have: ```js this.levelData = [ [{ x: 96, y: 224, t: "w" }], [ { x: 72, y: 320, t: "w" }, { x: 200, y: 320, t: "h" }, { x: 72, y: 150, t: "w" }, ], // … ]; ``` Every array element holds a collection of blocks with an `x` and `y` position and `t` value for each. After `levelData`, but still in the `initLevels` function, we're adding the blocks into an array in the `for` loop using some framework-specific methods: ```js for (let i = 0; i < this.maxLevels; i++) { const newLevel = this.add.group(); newLevel.enableBody = true; newLevel.physicsBodyType = Phaser.Physics.ARCADE; for (let e = 0; e < this.levelData[i].length; e++) { const item = this.levelData[i][e]; newLevel.create(item.x, item.y, `element-${item.t}`); } newLevel.setAll("body.immovable", true); newLevel.visible = false; this.levels.push(newLevel); } ``` First, `add.group()` is used to create a new group of items. Then the `ARCADE` body type is set for that group to enable physics calculations. The `newLevel.create` method creates new items in the group with starting left and top positions, and its own image. If you don't want to loop through the list of items again to add a property to every single one explicitly, you can use `setAll` on a group to apply it to all the items in that group. The objects are stored in the `this.levels` array, which is by default invisible. To load specific levels, we make sure the previous levels are hidden, and show the current one: ```js showLevel(level) { const lvl = level | this.level; if (this.levels[lvl - 2]) { this.levels[lvl - 2].visible = false; } this.levels[lvl - 1].visible = true; } ``` Thanks to that the game gives the player a challenge - now they have to roll the ball across the play area and guide it through the labyrinth built from the blocks. It's just an example of loading the levels, and there are only 5 of them just to showcase the idea, but you can work on expanding that on your own. #### Collision detection At this point we've got the ball that is controlled by the player, the hole to reach and the obstacles blocking the way. There's a problem though — our game doesn't have any collision detection yet, so nothing happens when the ball hits the blocks — it just goes through. Let's fix it! The good news is that the framework will take care of calculating the collision detection, we only have to specify the colliding objects in the `update()` function: ```js this.physics.arcade.collide( this.ball, this.borderGroup, this.wallCollision, null, this, ); this.physics.arcade.collide( this.ball, this.levels[this.level - 1], this.wallCollision, null, this, ); ``` This will tell the framework to execute the `wallCollision` function when the ball hits any of the walls. We can use the `wallCollision` function to add any functionality we want like playing the bounce sound and implementing the **Vibration API**. #### Adding the sound Among the preloaded assets there was an audio track (in various formats for browser compatibility), which we can use now. It has to be defined in the `create()` function first: ```js this.bounceSound = this.game.add.audio("audio-bounce"); ``` If the status of the audio is `true` (so the sounds in the game are enabled), we can play it in the `wallCollision` function: ```js if (this.audioStatus) { this.bounceSound.play(); } ``` That's all — loading and playing the sounds is easy with Phaser. #### Implementing the Vibration API When collision detection works as expected let's add some special effects with the help from the Vibration API. ![A visualization of the vibrations of a Flame mobile device with the Cyber Orb game demo on the screen.](/en-US/docs/Games/Tutorials/HTML5_Gamedev_Phaser_Device_Orientation/cyber-orb-flame-vibration.png) The best way to use it in our case is to vibrate the phone every time the ball hits the walls — inside the `wallCollision` function: ```js if ("vibrate" in window.navigator) { window.navigator.vibrate(100); } ``` If the `vibrate` method is supported by the browser and available in the `window.navigator` object, vibrate the phone for 100 milliseconds. That's it! #### Adding the elapsed time To improve replayability and give players the option to compete with each other we will store the elapsed time — players can then try to improve on their best game completion time. To implement this we have to create a variable for storing the actual number of seconds elapsed from the start of the game, and to show it for the player in the game. Let's define the variables in the `create` function first: ```js this.timer = 0; // time elapsed in the current level this.totalTimer = 0; // time elapsed in the whole game ``` Then, right after that, we can initialize the necessary text objects to display this information to the user: ```js this.timerText = this.game.add.text( 15, 15, `Time: ${this.timer}`, this.fontBig, ); this.totalTimeText = this.game.add.text( 120, 30, `Total time: ${this.totalTimer}`, this.fontSmall, ); ``` We're defining the top and left positions of the text, the content that will be shown and the styling applied to the text. We have this printed out on the screen, but it would be good to update the values every second: ```js this.time.events.loop(Phaser.Timer.SECOND, this.updateCounter, this); ``` This loop, also in the `create` function, will execute the `updateCounter` function every single second from the beginning of the game, so we can apply the changes accordingly. This is how the complete `updateCounter` function looks: ```js updateCounter() { this.timer++; this.timerText.setText(`Time: ${this.timer}`); this.totalTimeText.setText(`Total time: ${this.totalTimer+this.timer}`); }, ``` As you can see we're incrementing the `this.timer` variable and updating the content of the text objects with the current values on each iteration, so the player sees the elapsed time. #### Finishing the level and the game The ball is rolling on the screen, the timer is working and we have the hole created that we have to reach. Now let's set up the possibility to actually finish the level! The following line in the `update()` function adds a listener that fires when the ball gets to the hole. ```js this.physics.arcade.overlap(this.ball, this.hole, this.finishLevel, null, this); ``` This works similarly to the `collide` method explained earlier. When the ball overlaps with the hole (instead of colliding), the `finishLevel` function is executed: ```js finishLevel() { if (this.level >= this.maxLevels) { this.totalTimer += this.timer; alert(`Congratulations, game completed!\nTotal time of play: ${this.totalTimer} seconds!`); this.game.state.start('MainMenu'); } else { alert(`Congratulations, level ${this.level} completed!`); this.totalTimer += this.timer; this.timer = 0; this.level++; this.timerText.setText(`Time: ${this.timer}`); this.totalTimeText.setText(`Total time: ${this.totalTimer}`); this.levelText.setText(`Level: ${this.level} / ${this.maxLevels}`); this.ball.body.x = this.ballStartPos.x; this.ball.body.y = this.ballStartPos.y; this.ball.body.velocity.x = 0; this.ball.body.velocity.y = 0; this.showLevel(); } }, ``` If the current level is equal to the maximum number of levels (in this case 5), then the game is finished — you'll get a congratulations message along with the number of seconds elapsed through the whole game, and a button to press that takes you to the main menu. If the current level is lower than 5, all the necessary variables are reset and the next level is loaded. Ideas for new features ---------------------- This is merely a working demo of a game that could have lots of additional features. We can for example add power-ups to collect along the way that will make our ball roll faster, stop the timer for a few seconds or give the ball special powers to go through obstacles. There's also room for the traps which will slow the ball down or make it more difficult to reach the hole. You can create more levels of increasing difficulty. You can even implement achievements, leaderboards and medals for different actions in the game. There are endless possibilities — they only depend on your imagination. Summary ------- I hope this tutorial will help you dive into 2D game development and inspire you to create awesome games on your own. You can play the demo game Cyber Orb and check out its source code on GitHub. HTML gives us raw tools, the frameworks built on top of it are getting faster and better, so now is a great time get into web game development. In this tutorial we used Phaser, but there are a number of other frameworks worth considering too like ImpactJS, Construct 3 or PlayCanvas — it depends on your preferences, coding skills (or lack thereof), project scale, requirements and other aspects. You should check them all out and decide which one suits your needs best.
2D breakout game using Phaser - Game development
2D breakout game using Phaser ============================= * Next » In this step-by-step tutorial, we create a simple mobile **MDN Breakout** game written in JavaScript, using the Phaser framework. Every step has editable, live samples available to play with, so you can see what the intermediate stages should look like. You will learn the basics of using the Phaser framework to implement fundamental game mechanics like rendering and moving images, collision detection, control mechanisms, framework-specific helper functions, animations and tweens, and winning and losing states. To get the most out of this series of articles you should already have basic to intermediate JavaScript knowledge. After working through this tutorial, you should be able to build your own simple Web games with Phaser. ![Gameplay screen from the game MDN Breakout created with Phaser where you can use your paddle to bounce the ball and destroy the brick field, with keeping the points and lives.](/en-US/docs/Games/Tutorials/2D_breakout_game_Phaser/mdn-breakout-phaser.png) Lesson details -------------- All the lessons — and the different versions of the MDN Breakout game we are building together — are available on GitHub: 1. Initialize the framework 2. Scaling 3. Load the assets and print them on screen 4. Move the ball 5. Physics 6. Bounce off the walls 7. Player paddle and controls 8. Game over 9. Build the brickfield 10. Collision detection 11. The score 12. Win the game 13. Extra lives 14. Animations and tweens 15. Buttons 16. Randomizing gameplay As a note on learning paths — starting with pure JavaScript is the best way to get a solid knowledge of web game development. If you are not already familiar with pure JavaScript game development, we would suggest that you first work through this series' counterpart, 2D breakout game using pure JavaScript. After that, you can pick any framework you like and use it for your projects; we have chosen Phaser as it is a good solid framework, with a good support and community available, and a good set of plugins. Frameworks speed up development time and help take care of the boring parts, allowing you to concentrate on the fun stuff. However, frameworks are not always perfect, so if something unexpected happens or you want to write some functionality that the framework does not provide, you will need some pure JavaScript knowledge. **Note:** This series of articles can be used as material for hands-on game development workshops. You can also make use of the Gamedev Phaser Content Kit based on this tutorial if you want to give a talk about game development with Phaser. Next steps ---------- Ok, let us get started! Head to the first part of the series — Initialize the framework. * Next »
Move the ball - Game development
Move the ball ============= * « Previous * Next » This is the **2nd step** out of 10 of the Gamedev Canvas tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Canvas-workshop/lesson2.html. You already know how to draw a ball from working through the previous article, so now let's make it move. Technically, we will be painting the ball on the screen, clearing it and then painting it again in a slightly different position every frame to make the impression of movement — just like how movement works with the movies. Defining a drawing loop ----------------------- To keep constantly updating the canvas drawing on each frame, we need to define a drawing function that will run over and over again, with a different set of variable values each time to change sprite positions, etc. You can run a function over and over again using a JavaScript timing function such as `setInterval()` or `requestAnimationFrame()`. Delete all the JavaScript you currently have inside your HTML file except for the first two lines, and add the following below them. The `draw()` function will be executed within `setInterval` every 10 milliseconds: ```js function draw() { // drawing code } setInterval(draw, 10); ``` Thanks to the infinite nature of `setInterval` the `draw()` function will be called every 10 milliseconds forever, or until we stop it. Now, let's draw the ball — add the following inside your `draw()` function: ```js ctx.beginPath(); ctx.arc(50, 50, 10, 0, Math.PI \* 2); ctx.fillStyle = "#0095DD"; ctx.fill(); ctx.closePath(); ``` Try your updated code now — the ball should be repainted on every frame. Making it move -------------- You won't notice the ball being repainted constantly at the moment, as it's not moving. Let's change that. First, instead of a hardcoded position at (50,50) we will define a starting point at the bottom center part of the Canvas in variables called `x` and `y`, then use those to define the position the circle is drawn at. First, add the following two lines above your `draw()` function, to define `x` and `y`: ```js let x = canvas.width / 2; let y = canvas.height - 30; ``` Next update the `draw()` function to use the x and y variables in the `arc()` method, as shown in the following highlighted line: ```js function draw() { ctx.beginPath(); ctx.arc(x, y, 10, 0, Math.PI \* 2); ctx.fillStyle = "#0095DD"; ctx.fill(); ctx.closePath(); } ``` Now comes the important part: we want to add a small value to `x` and `y` after every frame has been drawn to make it appear that the ball is moving. Let's define these small values as `dx` and `dy` and set their values to 2 and -2 respectively. Add the following below your x and y variable definitions: ```js let dx = 2; let dy = -2; ``` The last thing to do is to update `x` and `y` with our `dx` and `dy` variable on every frame, so the ball will be painted in the new position on every update. Add the following two new lines indicated below to your `draw()` function: ```js function draw() { ctx.beginPath(); ctx.arc(x, y, 10, 0, Math.PI \* 2); ctx.fillStyle = "#0095DD"; ctx.fill(); ctx.closePath(); x += dx; y += dy; } ``` Save your code again and try it in your browser. This works OK, although it appears that the ball is leaving a trail behind it: ![A blue line that indicates where the ball has been](/en-US/docs/Games/Tutorials/2D_Breakout_game_pure_JavaScript/Move_the_ball/ball-trail.png) Clearing the canvas before each frame ------------------------------------- The ball is leaving a trail because we're painting a new circle on every frame without removing the previous one. Don't worry, because there's a method to clear canvas content: `clearRect()`. This method takes four parameters: the x and y coordinates of the top left corner of a rectangle, and the x and y coordinates of the bottom right corner of a rectangle. The whole area covered by this rectangle will be cleared of any content previously painted there. Add the following highlighted new line to the `draw()` function: ```js function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.arc(x, y, 10, 0, Math.PI \* 2); ctx.fillStyle = "#0095DD"; ctx.fill(); ctx.closePath(); x += dx; y += dy; } ``` Save your code and try again, and this time you'll see the ball move without a trail. Every 10 milliseconds the canvas is cleared, the blue circle (our ball) will be drawn on a given position and the `x` and `y` values will be updated for the next frame. Cleaning up our code -------------------- We will be adding more and more commands to the `draw()` function in the next few articles, so it's good to keep it as simple and clean as possible. Let's start by moving the ball drawing code to a separate function. Replace the existing draw() function with the following two functions: ```js function drawBall() { ctx.beginPath(); ctx.arc(x, y, 10, 0, Math.PI \* 2); ctx.fillStyle = "#0095DD"; ctx.fill(); ctx.closePath(); } function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); drawBall(); x += dx; y += dy; } ``` Compare your code ----------------- You can check the finished code for this article for yourself in the live demo below, and play with it to understand better how it works: **Note:** Try changing the speed of the moving ball, or the direction it moves in. Next steps ---------- We've drawn our ball and gotten it moving, but it keeps disappearing off the edge of the canvas. In the third chapter we'll explore how to make it bounce off the walls. * « Previous * Next »
Track the score and win - Game development
Track the score and win ======================= * « Previous * Next » This is the **8th step** out of 10 of the Gamedev Canvas tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Canvas-workshop/lesson8.html. Destroying the bricks is really cool, but to be even more awesome the game could award points for every brick a user hits, and keep count of the total score. Counting the score ------------------ If you can see your score throughout the game, eventually you can impress your friends. You need a variable to record the score. Add the following into your JavaScript, after the rest of your variables: ```js let score = 0; ``` You also need a `drawScore()` function, to create and update the score display. Add the following after the `collisionDetection()` function: ```js function drawScore() { ctx.font = "16px Arial"; ctx.fillStyle = "#0095DD"; ctx.fillText(`Score: ${score}`, 8, 20); } ``` Drawing text on a canvas is similar to drawing a shape. The font definition looks exactly like the one in CSS — you can set the size and font type in the `font()` method. Then use `fillStyle()` to set the color of the font and `fillText()` to set the actual text that will be placed on the canvas, and where it will be placed. The first parameter is the text itself — the code above shows the current number of points — and the last two parameters are the coordinates where the text will be placed on the canvas. To award a score each time a brick is hit, add a line to the `collisionDetection()` function to increment the value of the score variable each time a collision is detected. Add the following highlighted line to your code: ```js function collisionDetection() { for (let c = 0; c < brickColumnCount; c++) { for (let r = 0; r < brickRowCount; r++) { const b = bricks[c][r]; if (b.status === 1) { if ( x > b.x && x < b.x + brickWidth && y > b.y && y < b.y + brickHeight ) { dy = -dy; b.status = 0; score++; } } } } } ``` Calling `drawScore()` from the `draw()` function keeps the score up to date with every new frame — add the following line inside `draw()`, just below the `drawPaddle()` call: ```js drawScore(); ``` Displaying a winning message when all bricks have been destroyed ---------------------------------------------------------------- Collecting the points works well, but you won't be adding them forever — what about when all the bricks have been destroyed? It's the main purpose of the game after all, so you should display a winning message if all available points have been collected. Add the following highlighted section into your `collisionDetection()` function: ```js function collisionDetection() { for (let c = 0; c < brickColumnCount; c++) { for (let r = 0; r < brickRowCount; r++) { const b = bricks[c][r]; if (b.status === 1) { if ( x > b.x && x < b.x + brickWidth && y > b.y && y < b.y + brickHeight ) { dy = -dy; b.status = 0; score++; if (score === brickRowCount \* brickColumnCount) { alert("YOU WIN, CONGRATULATIONS!"); document.location.reload(); clearInterval(interval); // Needed for Chrome to end game } } } } } } ``` Thanks to this, your users can actually win the game when they destroy all the bricks, which is quite important when it comes to games. The `document.location.reload()` function reloads the page and starts the game again once the alert button is clicked. Compare your code ----------------- The latest code looks (and works) like this, in case you want to compare and contrast it with yours: **Note:** Try adding more points per brick hit, print out the number of collected points in the end game alert box. Next steps ---------- The game looks pretty good at this point. In the next lesson you will broaden the game's appeal by adding Mouse controls. * « Previous * Next »
Bounce off the walls - Game development
Bounce off the walls ==================== * « Previous * Next » This is the **3rd step** out of 10 of the Gamedev Canvas tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Canvas-workshop/lesson3.html. It is nice to see our ball moving, but it quickly disappears from the screen, limiting the fun we can have with it! To overcome that we will implement some very simple collision detection (which will be explained later in more detail) to make the ball bounce off the four edges of the Canvas. Simple collision detection -------------------------- To detect the collision we will check whether the ball is touching (colliding with) the wall, and if so, we will change the direction of its movement accordingly. To make the calculations easier let's define a variable called `ballRadius` that will hold the radius of the drawn circle and be used for calculations. Add this to your code, somewhere below the existing variable declarations: ```js const ballRadius = 10; ``` Now update the line that draws the ball inside the `drawBall()` function to this: ```js ctx.arc(x, y, ballRadius, 0, Math.PI \* 2); ``` ### Bouncing off the top and bottom There are four walls to bounce the ball off — let's focus on the top one first. We need to check, on every frame, whether the ball is touching the top edge of the Canvas — if yes, we'll reverse the ball movement so it will start to move in the opposite direction and stay within the visible boundaries. Remembering that the coordinate system starts from the top left, we can come up with something like this: ```js if (y + dy < 0) { dy = -dy; } ``` If the `y` value of the ball position is lower than zero, change the direction of the movement on the `y` axis by setting it equal to itself, reversed. If the ball was moving upwards with a speed of 2 pixels per frame, now it will be moving "up" with a speed of -2 pixels, which actually equals to moving down at a speed of 2 pixels per frame. The code above would deal with the ball bouncing off the top edge, so now let's think about the bottom edge: ```js if (y + dy > canvas.height) { dy = -dy; } ``` If the ball's `y` position is greater than the height of the Canvas (remember that we count the `y` values from the top left, so the top edge starts at 0 and the bottom edge is at 320 pixels, the Canvas' height), then bounce it off the bottom edge by reversing the `y` axis movement as before. We could merge those two statements into one to save on code verbosity: ```js if (y + dy > canvas.height || y + dy < 0) { dy = -dy; } ``` If either of the two statements is `true`, reverse the movement of the ball. ### Bouncing off the left and right We have the top and bottom edge covered, so let's think about the left and right ones. It is very similar actually, all you have to do is to repeat the statements for `x` instead of `y`: ```js if (x + dx > canvas.width || x + dx < 0) { dx = -dx; } if (y + dy > canvas.height || y + dy < 0) { dy = -dy; } ``` At this point you should insert the above code block into the draw() function, just before the closing curly brace. ### The ball keeps disappearing into the wall! Test your code at this point, and you will be impressed — now we have a ball that bounced off all four edges of the canvas! We have another problem however — when the ball hits each wall it sinks into it slightly before changing direction: ![skyblue ball disappearing into the top of the white wall.](/en-US/docs/Games/Tutorials/2D_Breakout_game_pure_JavaScript/Bounce_off_the_walls/ball-in-wall.png) This is because we're calculating the collision point of the wall and the center of the ball, while we should be doing it for its circumference. The ball should bounce right after if touches the wall, not when it's already halfway in the wall, so let's adjust our statements a bit to include that. Update the last code you added to this: ```js if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) { dx = -dx; } if (y + dy > canvas.height - ballRadius || y + dy < ballRadius) { dy = -dy; } ``` When the distance between the center of the ball and the edge of the wall is exactly the same as the radius of the ball, it will change the movement direction. Subtracting the radius from one edge's width and adding it onto the other gives us the impression of the proper collision detection — the ball bounces off the walls as it should do. Compare your code ----------------- Let's again check the finished code for this part against what you've got, and have a play: **Note:** Try changing the color of the ball to a random color every time it hits the wall. Next steps ---------- We've now got to the stage where our ball is both moving and staying on the game board. In the fourth chapter we'll look at implementing a controllable paddle — see Paddle and keyboard controls. * « Previous * Next »
Mouse controls - Game development
Mouse controls ============== * « Previous * Next » This is the **9th step** out of 10 of the Gamedev Canvas tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Canvas-workshop/lesson9.html. The game itself is actually finished, so let's work on polishing it up. We have already added keyboard controls, but we could easily add mouse controls too. Listening for mouse movement ---------------------------- Listening for mouse movement is even easier than listening for key presses: all we need is the listener for the `mousemove` event. Add the following line in the same place as the other event listeners, just below the `keyup event`: ```js document.addEventListener("mousemove", mouseMoveHandler, false); ``` Anchoring the paddle movement to the mouse movement --------------------------------------------------- We can update the paddle position based on the pointer coordinates — the following handler function will do exactly that. Add the following function to your code, below the previous line you added: ```js function mouseMoveHandler(e) { const relativeX = e.clientX - canvas.offsetLeft; if (relativeX > 0 && relativeX < canvas.width) { paddleX = relativeX - paddleWidth / 2; } } ``` In this function we first work out a `relativeX` value, which is equal to the horizontal mouse position in the viewport (`e.clientX`) minus the distance between the left edge of the canvas and left edge of the viewport (`canvas.offsetLeft`) — effectively this is equal to the distance between the canvas left edge and the mouse pointer. If the relative X pointer position is greater than zero and lower than the Canvas width, the pointer is within the Canvas boundaries, and the `paddleX` position (anchored on the left edge of the paddle) is set to the `relativeX` value minus half the width of the paddle, so that the movement will actually be relative to the middle of the paddle. The paddle will now follow the position of the mouse cursor, but since we're restricting the movement to the size of the Canvas, it won't disappear completely off either side. Compare your code ----------------- This is the latest state of the code to compare against: **Note:** Try adjusting the boundaries of the paddle movement, so the whole paddle will be visible on both edges of the Canvas instead of only half of it. Next steps ---------- Now we've got a complete game we'll finish our series of lessons with some more small tweaks — Finishing up. * « Previous * Next »
Collision detection - Game development
Collision detection =================== * « Previous * Next » This is the **7th step** out of 10 of the Gamedev Canvas tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Canvas-workshop/lesson7.html. We have the bricks appearing on the screen already, but the game still isn't *that* interesting as the ball goes through them. We need to think about adding collision detection so it can bounce off the bricks and break them. It's our decision how to implement this, of course, but it can be tough to calculate whether the ball is touching the rectangle or not because there are no helper functions in Canvas for this. For the sake of this tutorial we will do it the easiest way possible. We will check if the center of the ball is colliding with any of the given bricks. This won't give a perfect result every time, and there are much more sophisticated ways to do collision detection, but this will work fine for teaching you the basic concepts. A collision detection function ------------------------------ To kick this all off we want to create a collision detection function that will loop through all the bricks and compare every single brick's position with the ball's coordinates as each frame is drawn. For better readability of the code we will define the `b` variable for storing the brick object in every loop of the collision detection: ```js function collisionDetection() { for (let c = 0; c < brickColumnCount; c++) { for (let r = 0; r < brickRowCount; r++) { const b = bricks[c][r]; // calculations } } } ``` If the center of the ball is inside the coordinates of one of our bricks, we'll change the direction of the ball. For the center of the ball to be inside the brick, all four of the following statements need to be true: * The x position of the ball is greater than the x position of the brick. * The x position of the ball is less than the x position of the brick plus its width. * The y position of the ball is greater than the y position of the brick. * The y position of the ball is less than the y position of the brick plus its height. Let's write that down in code: ```js function collisionDetection() { for (let c = 0; c < brickColumnCount; c++) { for (let r = 0; r < brickRowCount; r++) { const b = bricks[c][r]; if (x > b.x && x < b.x + brickWidth && y > b.y && y < b.y + brickHeight) { dy = -dy; } } } } ``` Add the above block to your code, below the `keyUpHandler()` function. Making the bricks disappear after they are hit ---------------------------------------------- The above code will work as desired and the ball changes its direction. The problem is that the bricks are staying where they are. We have to figure out a way to get rid of the ones we've already hit with the ball. We can do that by adding an extra parameter to indicate whether we want to paint each brick on the screen or not. In the part of the code where we initialize the bricks, let's add a `status` property to each brick object. Update the following part of the code as indicated by the highlighted line: ```js const bricks = []; for (let c = 0; c < brickColumnCount; c++) { bricks[c] = []; for (let r = 0; r < brickRowCount; r++) { bricks[c][r] = { x: 0, y: 0, status: 1 }; } } ``` Next we'll check the value of each brick's `status` property in the `drawBricks()` function before drawing it — if `status` is `1`, then draw it, but if it's `0`, then it was hit by the ball and we don't want it on the screen anymore. Update your `drawBricks()` function as follows: ```js function drawBricks() { for (let c = 0; c < brickColumnCount; c++) { for (let r = 0; r < brickRowCount; r++) { if (bricks[c][r].status === 1) { const brickX = c \* (brickWidth + brickPadding) + brickOffsetLeft; const brickY = r \* (brickHeight + brickPadding) + brickOffsetTop; bricks[c][r].x = brickX; bricks[c][r].y = brickY; ctx.beginPath(); ctx.rect(brickX, brickY, brickWidth, brickHeight); ctx.fillStyle = "#0095DD"; ctx.fill(); ctx.closePath(); } } } } ``` Tracking and updating the status in the collision detection function -------------------------------------------------------------------- Now we need to involve the brick `status` property in the `collisionDetection()` function: if the brick is active (its status is `1`) we will check whether the collision happens; if a collision does occur we'll set the status of the given brick to `0` so it won't be painted on the screen. Update your `collisionDetection()` function as indicated below: ```js function collisionDetection() { for (let c = 0; c < brickColumnCount; c++) { for (let r = 0; r < brickRowCount; r++) { const b = bricks[c][r]; if (b.status === 1) { if ( x > b.x && x < b.x + brickWidth && y > b.y && y < b.y + brickHeight ) { dy = -dy; b.status = 0; } } } } } ``` Activating our collision detection ---------------------------------- The last thing to do is to add a call to the `collisionDetection()` function to our main `draw()` function. Add the following line to the `draw()` function, just below the `drawPaddle()` call: ```js collisionDetection(); ``` Compare your code ----------------- The collision detection of the ball is now checked on every frame, with every brick. Now we can destroy bricks! :- **Note:** Try changing the color of the ball when it hits the brick. Next steps ---------- We are definitely getting there now; let's move on! In the eighth chapter we will be looking at how to Track the score and win. * « Previous * Next »
Build the brick field - Game development
Build the brick field ===================== * « Previous * Next » This is the **6th step** out of 10 of the Gamedev Canvas tutorial. You can find the source code as it would look after completing this lesson at Gamedev-Canvas-workshop/lesson6.html. After modifying the gameplay mechanics, we are now able to lose — this is great as it means the game is finally feeling more like a game. However, it will quickly get boring if all you do is bounce the ball off the walls and the paddle. What a breakout game really needs is some bricks to destroy with the ball, and this is what we'll create now! Setting up the brick variables ------------------------------ The overall aim of this lesson is to render a few lines of code for the bricks, using a nested loop that works through a two-dimensional array. First however we need to set up some variables to define information about the bricks such as their width and height, rows and columns, etc. Add the following lines to your code below the variables which you have previously declared in your program. ```js const brickRowCount = 3; const brickColumnCount = 5; const brickWidth = 75; const brickHeight = 20; const brickPadding = 10; const brickOffsetTop = 30; const brickOffsetLeft = 30; ``` Here we've defined the number of rows and columns of bricks, their width and height, the padding between the bricks so they won't touch each other and a top and left offset so they won't start being drawn right from the edge of the Canvas. We will hold all our bricks in a two-dimensional array. It will contain the brick columns (c), which in turn will contain the brick rows (r), which in turn will each contain an object containing the `x` and `y` position to paint each brick on the screen. Add the following just below your variables: ```js const bricks = []; for (let c = 0; c < brickColumnCount; c++) { bricks[c] = []; for (let r = 0; r < brickRowCount; r++) { bricks[c][r] = { x: 0, y: 0 }; } } ``` The code above will loop through the rows and columns and create the new bricks. NOTE that the brick objects will also be used for collision detection purposes later. Brick drawing logic ------------------- Now let's create a function to loop through all the bricks in the array and draw them on the screen. Our code might look like this: ```js function drawBricks() { for (let c = 0; c < brickColumnCount; c++) { for (let r = 0; r < brickRowCount; r++) { bricks[c][r].x = 0; bricks[c][r].y = 0; ctx.beginPath(); ctx.rect(0, 0, brickWidth, brickHeight); ctx.fillStyle = "#0095DD"; ctx.fill(); ctx.closePath(); } } } ``` Again, we're looping through the rows and columns to set the `x` and `y` position of each brick, and we're also painting a brick on the Canvas — size `brickWidth` x `brickHeight` — with each loop iteration. The problem is that we're painting them all in one place, at coordinates `(0,0)`. What we need to do is include some calculations that will work out the `x` and `y` position of each brick for each loop iteration: ```js const brickX = c \* (brickWidth + brickPadding) + brickOffsetLeft; const brickY = r \* (brickHeight + brickPadding) + brickOffsetTop; ``` Each `brickX` position is worked out as `brickWidth` + `brickPadding`, multiplied by the column number, `c`, plus the `brickOffsetLeft`; the logic for the brickY is identical except that it uses the values for row number, `r`, `brickHeight`, and `brickOffsetTop`. Now every single brick can be placed in its correct place row and column, with padding between each brick, drawn at an offset from the left and top canvas edges. The final version of the `drawBricks()` function, after assigning the `brickX` and `brickY` values as the coordinates instead of `(0,0)` each time, will look like this — add this into your code below the `drawPaddle()` function: ```js function drawBricks() { for (let c = 0; c < brickColumnCount; c++) { for (let r = 0; r < brickRowCount; r++) { const brickX = c \* (brickWidth + brickPadding) + brickOffsetLeft; const brickY = r \* (brickHeight + brickPadding) + brickOffsetTop; bricks[c][r].x = brickX; bricks[c][r].y = brickY; ctx.beginPath(); ctx.rect(brickX, brickY, brickWidth, brickHeight); ctx.fillStyle = "#0095DD"; ctx.fill(); ctx.closePath(); } } } ``` Actually drawing the bricks --------------------------- The last thing to do in this lesson is to add a call to `drawBricks()` somewhere in the `draw()` function, preferably at the beginning, between the clearing of the Canvas and drawing the ball. Add the following just above the `drawBall()` call: ```js drawBricks(); ``` Compare your code ----------------- At this point, the game has got a little more interesting again: **Note:** Try changing the number of bricks in a row or a column, or their positions. Next steps ---------- So now we have bricks! But the ball isn't interacting with them at all — we'll change that as we continue to the seventh chapter: Collision detection. * « Previous * Next »
Create the Canvas and draw on it - Game development
Create the Canvas and draw on it ================================ * « Previous * Next » This is the **1st step** out of 10 of the Gamedev Canvas tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Canvas-workshop/lesson1.html. Before we can start writing the game's functionality, we need to create a basic structure to render the game inside. This can be done using HTML and the `<canvas>` element. The game's HTML --------------- The HTML document structure is quite simple, as the game will be rendered entirely on the `<canvas>` element. Using your favorite text editor, create a new HTML document, save it as `index.html`, in a sensible location, and add the following code to it: ```html <!doctype html> <html lang="en-US"> <head> <meta charset="utf-8" /> <title>Gamedev Canvas Workshop</title> <style> \* { padding: 0; margin: 0; } canvas { background: #eee; display: block; margin: 0 auto; } </style> </head> <body> <canvas id="myCanvas" width="480" height="320"></canvas> <script> // JavaScript code goes here </script> </body> </html> ``` We have a `charset` defined, `<title>` and some basic CSS in the header. The body contains `<canvas>` and `<script>` elements — we will render the game inside the first one and write the JavaScript code that controls it in the second one. The `<canvas>` element has an `id` of `myCanvas` to allow us to easily grab a reference to it, and it is 480 pixels wide and 320 pixels high. All the JavaScript code we will write in this tutorial will go between the opening `<script>` and closing `</script>` tags. Canvas basics ------------- To actually be able to render graphics on the `<canvas>` element, first we have to grab a reference to it in JavaScript. Add the following below your opening `<script>` tag. ```js const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); ``` Here we're storing a reference to the `<canvas>` element to the `canvas` variable. Then we're creating the `ctx` variable to store the 2D rendering context — the actual tool we can use to paint on the Canvas. Let's see an example piece of code that prints a red square on the canvas. Add this below your previous lines of JavaScript, then load your `index.html` in a browser to try it out. ```js ctx.beginPath(); ctx.rect(20, 40, 50, 50); ctx.fillStyle = "#FF0000"; ctx.fill(); ctx.closePath(); ``` All the instructions are between the `beginPath()` and `closePath()` methods. We are defining a rectangle using `rect()`: the first two values specify the coordinates of the top left corner of the rectangle on the canvas, while the second two specify the width and height of the rectangle. In our case the rectangle is painted 20 pixels from the left side of the screen and 40 pixels from the top side, and is 50 pixels wide and 50 pixels high, which makes it a perfect square. The `fillStyle` property stores a color that will be used by the `fill()` method to paint the square, in our case, red. We're not limited to rectangles — here's a piece of code for printing out a green circle. Try adding this to the bottom of your JavaScript, saving and refreshing: ```js ctx.beginPath(); ctx.arc(240, 160, 20, 0, Math.PI \* 2, false); ctx.fillStyle = "green"; ctx.fill(); ctx.closePath(); ``` As you can see we're using the `beginPath()` and `closePath()` methods again. Between them, the most important part of the code above is the `arc()` method. It takes six parameters: * `x` and `y` coordinates of the arc's center * arc radius * start angle and end angle (what angle to start and finish drawing the circle, in radians) * direction of drawing (`false` for clockwise, the default, or `true` for anti-clockwise.) This last parameter is optional. The `fillStyle` property looks different than before. This is because, just as with CSS, color can be specified as a hexadecimal value, a color keyword, the `rgb()` function, or any of the other available color methods. Instead of using `fill()` and filling the shapes with colors, we can use `stroke()` to only color the outer stroke. Try adding this code to your JavaScript too: ```js ctx.beginPath(); ctx.rect(160, 10, 100, 40); ctx.strokeStyle = "rgb(0 0 255 / 50%)"; ctx.stroke(); ctx.closePath(); ``` The code above prints a blue-stroked empty rectangle. Thanks to the alpha channel in the `rgb()` function, the blue color is semi transparent. Compare your code ----------------- Here's the full source code of the first lesson, running live in a JSFiddle: **Note:** Try changing the size and color of the given shapes. Next steps ---------- Now we've set up the basic HTML and learned a bit about canvas, lets continue to the second chapter and work out how to Move the ball in our game. * « Previous * Next »
Finishing up - Game development
Finishing up ============ * « Previous This is the **10th and final step** of the Gamedev Canvas tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Canvas-workshop/lesson10.html. There's always room for improvements in any game we write. For example, we can offer more than one life to the player. They could make a mistake or two and still be able to finish the game. We could also improve our code rendering. Giving the player some lives ---------------------------- Implementing lives is quite straightforward. Let's first add a variable to store the number of lives in the same place where we declared our other variables: ```js let lives = 3; ``` Drawing the life counter looks almost the same as drawing the score counter — add the following function to your code, below the `drawScore()` function: ```js function drawLives() { ctx.font = "16px Arial"; ctx.fillStyle = "#0095DD"; ctx.fillText(`Lives: ${lives}`, canvas.width - 65, 20); } ``` Instead of ending the game immediately, we will decrease the number of lives until they are no longer available. We can also reset the ball and the paddle positions when the player begins with their next life. So, in the `draw()` function replace the following three lines: ```js alert("GAME OVER"); document.location.reload(); clearInterval(interval); // Needed for Chrome to end game ``` With this, we can add slightly more complex logic to it as given below: ```js lives--; if (!lives) { alert("GAME OVER"); document.location.reload(); clearInterval(interval); // Needed for Chrome to end game } else { x = canvas.width / 2; y = canvas.height - 30; dx = 2; dy = -2; paddleX = (canvas.width - paddleWidth) / 2; } ``` Now, when the ball hits the bottom edge of the screen, we're subtracting one life from the `lives` variable. If there are no lives left, the game is lost; if there are still some lives left, then the position of the ball and the paddle are reset, along with the movement of the ball. ### Rendering the lives display Now you need to add a call to `drawLives()` inside the `draw()` function and add it below the `drawScore()` call. ```js drawLives(); ``` Improving rendering with requestAnimationFrame() ------------------------------------------------ Now let's work on something that is not connected to the game mechanics, but to the way it is being rendered. `requestAnimationFrame` helps the browser render the game better than the fixed frame rate we currently have implemented using `setInterval()`. Replace the following line: ```js const interval = setInterval(draw, 10); ``` with: ```js draw(); ``` and remove each instance of: ```js clearInterval(interval); // Needed for Chrome to end game ``` Then, at the very bottom of the `draw()` function (just before the closing curly brace), add in the following line, which causes the `draw()` function to call itself over and over again: ```js requestAnimationFrame(draw); ``` The `draw()` function is now getting executed again and again within a `requestAnimationFrame()` loop, but instead of the fixed 10 milliseconds frame rate, we are giving control of the frame rate back to the browser. It will sync the frame rate accordingly and render the shapes only when needed. This produces a more efficient, smoother animation loop than the older `setInterval()` method. Compare your code ----------------- That's all — the final version of the game is ready and set to go ! **Note:**: Try changing the number of lives and the angle the ball bounces off the paddle. Game over - for now! -------------------- You've finished all the lessons - congratulations! By this point, you should now know the basics of canvas manipulation and the logic behind simple 2D games. Now it's a good time to learn some frameworks and continue game development. You can check out this series' counterpart, 2D breakout game using Phaser or the Cyber Orb built in Phaser tutorial. You can also look through the Games section on MDN for inspiration and more knowledge. You could also go back to this tutorial series' index page. Have fun coding! * « Previous
Game over - Game development
Game over ========= * « Previous * Next » This is the **5th step** out of 10 of the Gamedev Canvas tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Canvas-workshop/lesson5.html. It's fun to watch the ball bouncing off the walls and be able to move the paddle around, but other than that the game does nothing and doesn't have any progression or end goal. It would be good from the gameplay point of view to be able to lose. The logic behind losing in breakout is simple. If you miss the ball with the paddle and let it reach the bottom edge of the screen, then it's game over. Implementing game over ---------------------- Let's try to implement game over in our game. Here's the piece of code from the third lesson where we made the ball bounce off the walls: ```js if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) { dx = -dx; } if (y + dy > canvas.height - ballRadius || y + dy < ballRadius) { dy = -dy; } ``` Instead of allowing the ball to bounce off all four walls, let's only allow three now — left, top and right. Hitting the bottom wall will end the game. We'll edit the second if block so it's an if else block that will trigger our "game over" state upon the ball colliding with the bottom edge of the canvas. For now we'll keep it simple, showing an alert message and restarting the game by reloading the page. First, replace where you initially called `setInterval()` ```js setInterval(draw, 10); ``` with: ```js const interval = setInterval(draw, 10); ``` Then replace the second if statement with the following: ```js if (y + dy < ballRadius) { dy = -dy; } else if (y + dy > canvas.height - ballRadius) { alert("GAME OVER"); document.location.reload(); clearInterval(interval); // Needed for Chrome to end game } ``` Letting the paddle hit the ball ------------------------------- The last thing to do in this lesson is to create some kind of collision detection between the ball and the paddle, so it can bounce off it and get back into the play area. The easiest thing to do is to check whether the center of the ball is between the left and right edges of the paddle. Update the last bit of code you modified again, to the following: ```js if (y + dy < ballRadius) { dy = -dy; } else if (y + dy > canvas.height - ballRadius) { if (x > paddleX && x < paddleX + paddleWidth) { dy = -dy; } else { alert("GAME OVER"); document.location.reload(); clearInterval(interval); } } ``` If the ball hits the bottom edge of the Canvas we need to check whether it hits the paddle. If so, then it bounces off just like you'd expect; if not, then the game is over as before. Compare your code ----------------- Here's the working code for you to compare yours against: **Note:** Try making the ball move faster when it hits the paddle. Next steps ---------- We're doing quite well so far and our game is starting to feel a lot more worth playing now that you can lose! But it is still missing something. Let's move on to the sixth chapter — Build the brick field — and create some bricks for the ball to destroy. * « Previous * Next »
Paddle and keyboard controls - Game development
Paddle and keyboard controls ============================ * « Previous * Next » This is the **4th step** out of 10 of the Gamedev Canvas tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Canvas-workshop/lesson4.html. The ball is bouncing off the walls freely and you can watch it indefinitely, but currently there's no interactivity. It's not a game if you cannot control it! So let's add some user interaction: a controllable paddle. Defining a paddle to hit the ball --------------------------------- So, we need a paddle to hit the ball. Let's define a few variables for that. Add the following variables near the top of your code, beside your other variables: ```js const paddleHeight = 10; const paddleWidth = 75; let paddleX = (canvas.width - paddleWidth) / 2; ``` Here we're defining the height and width of the paddle and its starting point on the `x` axis for use in calculations further on down the code. Let's create a function that will draw the paddle on the screen. Add the following just below your `drawBall()` function: ```js function drawPaddle() { ctx.beginPath(); ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight); ctx.fillStyle = "#0095DD"; ctx.fill(); ctx.closePath(); } ``` Allowing the user to control the paddle --------------------------------------- We can draw the paddle wherever we want, but it should respond to the user's actions. It's time to implement some keyboard controls. We will need the following: * Two variables for storing information on whether the left or right control button is pressed. * Two event listeners for `keydown` and `keyup` events. We want to run some code to handle the paddle movement when the buttons are pressed. * Two functions handling the `keydown` and `keyup` events the code that will be run when the buttons are pressed. * The ability to move the paddle left and right Pressed buttons can be defined and initialized with boolean variables like in the example. Add these lines somewhere near the rest of your variables: ```js let rightPressed = false; let leftPressed = false; ``` The default value for both is `false` because at the beginning the control buttons are not pressed. To listen for key presses, we will set up two event listeners. Add the following lines just above the `setInterval()` line at the bottom of your JavaScript: ```js document.addEventListener("keydown", keyDownHandler, false); document.addEventListener("keyup", keyUpHandler, false); ``` When the `keydown` event is fired on any of the keys on your keyboard (when they are pressed), the `keyDownHandler()` function will be executed. The same pattern is true for the second listener: `keyup` events will fire the `keyUpHandler()` function (when the keys stop being pressed). Add these to your code now, below the `addEventListener()` lines: ```js function keyDownHandler(e) { if (e.key === "Right" || e.key === "ArrowRight") { rightPressed = true; } else if (e.key === "Left" || e.key === "ArrowLeft") { leftPressed = true; } } function keyUpHandler(e) { if (e.key === "Right" || e.key === "ArrowRight") { rightPressed = false; } else if (e.key === "Left" || e.key === "ArrowLeft") { leftPressed = false; } } ``` When we press a key down, this information is stored in a variable. The relevant variable in each case is set to `true`. When the key is released, the variable is set back to `false`. Both functions take an event as a parameter, represented by the `e` variable. From that you can get useful information: the `key` holds the information about the key that was pressed. Most browsers use `ArrowRight` and `ArrowLeft` for the left/right cursor keys, but we need to also include `Right` and `Left` checks to support IE/Edge browsers. If the left cursor is pressed, then the `leftPressed` variable is set to `true`, and when it is released, the `leftPressed` variable is set to `false`. The same pattern follows with the right cursor and the `rightPressed` variable. ### The paddle moving logic We've now set up the variables for storing the info about the pressed keys, event listeners, and relevant functions. Next we'll get into the code to use all the things we just set up and to move the paddle on the screen. Inside the `draw()` function, we will check if the left or right cursor keys are pressed when each frame is rendered. Our code might look like this: ```js if (rightPressed) { paddleX += 7; } else if (leftPressed) { paddleX -= 7; } ``` If the left cursor is pressed, the paddle will move seven pixels to the left, and if the right cursor is pressed, the paddle will move seven pixels to the right. This currently works, but the paddle disappears off the edge of the canvas if we hold either key for too long. We could improve that and move the paddle only within the boundaries of the canvas by changing the code like this: ```js if (rightPressed) { paddleX = Math.min(paddleX + 7, canvas.width - paddleWidth); } else if (leftPressed) { paddleX = Math.max(paddleX - 7, 0); } ``` The `paddleX` position we're using will move between `0` on the left side of the canvas and `canvas.width-paddleWidth` on the right-hand side, which will work exactly as we want it to. Add the above code block into the `draw()` function at the bottom, just above the closing curly brace. The only thing left to do now is call the `drawPaddle()` function from within the `draw()` function, to actually print it on the screen. Add the following line inside your `draw()` function, just below the line that calls `drawBall()`: ```js drawPaddle(); ``` Compare your code ----------------- Here's the working code for you to compare yours against: **Note:** Try making the paddle move faster or slower, or change its size. Next steps ---------- Now we have something resembling a game. The only trouble now is that you can just continue hitting the ball with the paddle forever. This will all change in the fifth chapter, Game over, when we start to add in an endgame state for our game. * « Previous * Next »