Programming/JavaScript

[EloquentJS] Ch18. HTTP and Forms

dododoo 2020. 5. 21. 15:04

HTTP and Forms

The protocol

  • the browser might send something like this:

  • GET /18_http.html HTTP/1.1
    Host: eloquentjavascript.net
    User-Agent: Your browser's name
  • Then the server responds, through that same connection.

  • HTTP/1.1 200 OK
    Content-Length: 65585
    Content-Type: text/html
    Last-Modified: Mon, 08 Jan 2018 10:29:45 GMT
    
    <!doctype html>
    ... the rest of the document
  • The browser takes the part of the response after the blank line, its body (not to be confused with the HTML <body> tag), and displays it as an HTML document.

  • The information sent by the client is called the request. It starts with this line:

  • GET /18_http.html HTTP/1.1
  • The first word is the method of the request. GET means that we want to get the specified resource. Other common methods are DELETE to delete a resource, PUT to create or replace it, and POST to send information to it.

    • GET: 리소스를 얻기 위한 리퀘스트
    • DELETE: 리소스를 삭제하기 위한 리퀘스트
    • PUT: 리소스를 생성하거나 대체하기 위한 리퀘스트
    • POST: 리소스로 정보를 보내기 위한 리퀘스트
  • Note that the server is not obliged to carry out every request it gets. If you walk up to a random website and tell it to DELETE its main page, it’ll probably refuse.

    서버는 리퀘스트들을 모두 실행할 의무는 없다.

  • The part after the method name is the path of the resource the request applies to. In the simplest case, a resource is simply a file on the server, but the protocol doesn’t require it to be. A resource may be anything that can be transferred as if it is a file.

    메소드 이름 다음 부분은 그 메소드가 적용될 리소스의 경로를 말한다. 파일인 것처럼 전송될 수 있는 모든 것들은 리소스가 될 수 있다.

  • Many servers generate the responses they produce on the fly. For example, if you open https://github.com/marijnh, the server looks in its database for a user named “marijnh”, and if it finds one, it will generate a profile page for that user.

    많은 서버들이 리스폰스를 즉석으로(on the fly) 생성한다.

  • Browsers will automatically switch to the appropriate protocol version when talking to a given server, and the outcome of a request is the same regardless of which version is used.

    브라우저는 서버와 대화하며 자동적으로 적절한 프로토콜 버전으로 전환한다. 또한, 리퀘스트의 결과는 어떤 버전을 사용하느냐와 관계없이 동일하다.

  • The server’s response will start with a version as well, followed by the status of the response, first as a three-digit status code and then as a human-readable string.

  • HTTP/1.1 200 OK
  • Status codes starting with a 2 indicate that the request succeeded. Codes starting with 4 mean there was something wrong with the request. 404 is probably the most famous HTTP status code—it means that the resource could not be found. Codes that start with 5 mean an error happened on the server and the request is not to blame.

    2로 시작하는 상태 코드는 해당 리퀘스트가 성공적이라는 것을 말한다. 4는 리퀘스트에 무언가 잘못된 것이 있음을 말한다. 5는 서버에서 오류가 발생했고 리퀘스트는 문제가 없음을 말한다.

  • The first line of a request or response may be followed by any number of headers. These are lines in the form name: value that specify extra information about the request or response.

    리퀘스트나 리스폰스의 첫 줄 다음에는 임의의 개수만큼의 헤더가 따라올 수 있다. 헤더는 해당 리퀘스트나 리스폰스에 대해 추가적인 정보를 명시한다.

  • These headers were part of the example response:

  • Content-Length: 65585
    Content-Type: text/html
    Last-Modified: Thu, 04 Jan 2018 14:05:30 GMT    
  • For most headers, the client and server are free to decide whether to include them in a request or response. But a few are required. For example, the Host header, which specifies the hostname, should be included in a request because a server might be serving multiple hostnames on a single IP address, and without that header, the server won’t know which hostname the client is trying to talk to.

    대부분의 헤더들은 클라이언트나 서버가 그것들을 리퀘스트나 리스폰스에 포함할지 말지를 자유롭게 결정할 수 있다. 그러나 몇몇의 헤더들은 필수적이다. Host 헤더가 그러한데, 왜냐하면 한 서버가 한 IP 주소로 여러 호스트명을 제공할 수도 있기 때문이다. Host 헤더 없이는 어느 호스트명인지 특정할 수 없다.

  • After the headers, both requests and responses may include a blank line followed by a body, which contains the data being sent. GET and DELETE requests don’t send along any data, but PUT and POST requests do. Similarly, some response types, such as error responses, do not require a body.

    리스폰스와 리퀘스트는 헤더 뒤에 한 줄을 비운 뒤 전달하려는 데이터를 포함하는 body를 붙일 수 있다. GET, DELETE 리퀘스트는 어떤 데이터도 보내지 않지만 PUT, POST 리퀘스트는 데이터를 보낸다. 이와 비슷하게, 에러 리스폰스같은 몇몇 리스폰스들은 body를 필요로 하지 않는다.

Browsers and HTTP

  • A browser will make a request when we enter a URL in its address bar. When the resulting HTML page references other files, such as images and JavaScript files, those are also retrieved.

  • A moderately complicated website can easily include anywhere from 10 to 200 resources. To be able to fetch those quickly, browsers will make several GET requests simultaneously, rather than waiting for the responses one at a time.

    브라우저는 여러개의 GET 리퀘스트를 동시에 보낼 것이다.

  • HTML pages may include forms, which allow the user to fill out information and send it to the server.

    HTML 페이지는 사용자가 정보를 채워서 서버로 전달할 수 있는 폼들을 포함할 수 있다.

  • <form method="GET" action="example/message.html">
        <p>Name: <input type="text" name="name"></p>
        <p>Message:<br><textarea name="message"></textarea></p>
        <p><button type="submit">Send</p>
    </form>    
  • This code describes a form with two fields: a small one asking for a name and a larger one to write a message in. When you click the Send button, the form is submitted, meaning that the content of its field is packed into an HTTP request and the browser navigates to the result of that request.

    Send 버튼을 누르면 해당 폼이 제출된다-필드의 내용이 HTTP 리퀘스트 속에 넣어지고, 브라우저는 해당 리퀘스트의 결과로 이동한다.

  • When the <form> element’s method attribute is GET (or is omitted), the information in the form is added to the end of the action URL as a query string.

    <form> 엘리먼트의 메소드 어트리뷰트가 GET이거나 생략되었다면 폼 안의 정보는 action 어트리뷰트에 명시된 URL 끝에 쿼리 문자열로써 붙는다.

  • The browser might make a request to this URL:

  • GET /example/message.html?name=Jean&message=Yes%3F HTTP/1.1
  • The question mark indicates the end of the path part of the URL and the start of the query. It is followed by pairs of names and values, corresponding to the name attribute on the form field elements and the content of those elements, respectively. An ampersand character (&) is used to separate the pairs.

    ?는 URL의 끝 그리고 쿼리의 시작을 나타낸다. 이 뒤에는 이름과 값의 쌍들이 따라오는데, 이들은 각각 폼 필드 엘리먼트의 name 어트리뷰트와 그 엘리먼트의 값에 대응된다. &는 이 쌍들을 구분한다.

  • The actual message encoded in the URL is “Yes?”, but the question mark is replaced by a strange code. Some characters in query strings must be escaped. The question mark, represented as %3F, is one of those. ... This one, called URL encoding, uses a percent sign followed by two hexadecimal (base 16) digits that encode the character code. ... JavaScript provides the encodeURIComponent and decodeURIComponent functions to encode and decode this format.

    이스케이핑, encodeURIComponent, decodeURIComponent

  • console.log(encodeURIComponent("YES?"));    // YES%3F
    console.log(decodeURICompenent("YES%3F"));  // YES?
  • If we change the method attribute of the HTML form in the example we saw earlier to POST, the HTTP request made to submit the form will use the POST method and put the query string in the body of the request, rather than adding it to the URL.

  • POST /example/message.html HTTP/1.1
    Content-length: 24
    Content-type: application/x-www-form-urlencoded
    
    name=Jean&message=Yes%3F

    form 태그의 method 어트리뷰트를 POST로 바꾼다면 이 폼을 전송하기 위한 HTTP 리퀘스트이 POST 메소드를 사용하고, 쿼리 문자열을 URL이 아닌 리퀘스트의 바디에 놓는다.

  • GET requests should be used for requests that do not have side effects but simply ask for information. Requests that change something on the server, for example creating a new account or posting a message, should be expressed with other methods, such as POST.

    GET 리퀘스트는 side effect를 가지지 않고 단순히 정보를 요구하는 리퀘스트를 위해 사용되어야 한다. 서버에서 무언가를 바꾸는 리퀘스트는 POST와 같이 다른 메소드들로 표현되어야 한다.

Fetch

  • The interface through which browser JavaScript can make HTTP requests is called fetch. Since it is relatively new, it conveniently uses promises (which is rare for browser interfaces).

    브라우저 자바스크립트가 HTTP 리퀘스트를 만들 수 있는 인터페이스를 fetch라 부른다.

  • fetch("exmaple/data.txt").then(response => {
        console.log(response.status);
        // 200
        console.log(response.headers.get("Content-Type"));
        // text/plain
    });
  • Calling fetch returns a promise that resolves to a Response object holding information about the server’s response. The headers are wrapped in a Map-like object that treats its keys (the header names) as case insensitive because header names are not supposed to be case sensitive.

    fetch는 서버의 리스폰스에 대한 정보를 갖는 Response 객체를 resolve하는 프로미스를 반환한다. header들은 Map과 비슷한 객체에 쌓여지는데, 이때 key(헤더 이름)는 대소문자를 구별하지 않는다.

  • Note that the promise returned by fetch resolves successfully even if the server responded with an error code. It might also be rejected if there is a network error or if the server that the request is addressed to can’t be found.

    fetch의 결과는 에러 코드를 포함한 리스폰스를 받더라도 성공적으로 resolve된다. 네트워크 에러나 서버를 찾을 수 없는 경우 등에서 reject된다.

  • The first argument to fetch is the URL that should be requested. When that URL doesn’t start with a protocol name (such as http:), it is treated as relative, which means it is interpreted relative to the current document. When it starts with a slash (/), it replaces the current path, which is the part after the server name. When it does not, the part of the current path up to and including its last slash character is put in front of the relative URL.

    fetch의 첫 번째 인자는 URL인데, 이 URL이 http:와 같은 프로토콜 이름으로 시작하지 않는다면 상대적인 경로로 취급된다. 즉, 현재 문서와 상대적으로 해석된다. 슬래시(/)로 시작하면 현재 경로(서버 이름 뒤의 부분)를 대체한다. 그렇지 않을 경우 마지막 슬래시 문자를 포함한 현재 경로 부분이 상대 URL 앞에 배치된다.

  • To get at the actual content of a response, you can use its text method. Because the initial promise is resolved as soon as the response’s headers have been received and because reading the response body might take a while longer, this again returns a promise.

    리스폰스의 실제 내용물을 얻기 위해서 text 메소드를 사용할 수 있다. 처음 프로미스는 리스폰스의 헤더들을 받자마자 resolve되고 body를 읽는 것은 좀 더 걸릴 수 있기 때문에 text는 프로미스를 반환하게 되어있다.

  • fetch("example/data.txt")
        .then(resp => resp.text())
        .then(text => console.log(text));
    // → This is the content of data.txt
  • A similar method, called json, returns a promise that resolves to the value you get when parsing the body as JSON or rejects if it’s not valid JSON.

    비슷한 메소드로 json이 있다. 이는 바디를 JSON으로 파싱할 때 얻는 값으로 resolve되는 프로미스를 반환한다. 바디가 유효한 JSON이 아니라면 reject한다.

  • By default, fetch uses the GET method to make its request and does not include a request body. You can configure it differently by passing an object with extra options as a second argument. For example, this request tries to delete example/data.txt:

    기본적으로 fetchGET 메소드를 사용하여 리퀘스트를 만들고 바디를 포함하지 않는다. 그러나 두 번째 인자로 추가 옵션들을 담은 객체를 전달하여 다르게 사용할 수 있다.

  • fetch("example/data.txt", {method: "DELETE"}).then(resp => {
        console.log(resp.status);
        // 405; method not allowed
    });
  • To add a request body, you can include a body option. To set headers, there’s the headers option. For example, this request includes a Range header, which instructs the server to return only part of a response.

    body 옵션과 headers 옵션을 사용하여 각각을 포함할 수 있다. + Range 헤더

  • fetch("example/data.txt", {headers: {Range: "bytes=8-19"}})
        .then(resp => resp.text())
        .then(console.log);
        // the content
  • The browser will automatically add some request headers, such as “Host” and those needed for the server to figure out the size of the body. But adding your own headers is often useful to include things such as authentication information or to tell the server which file format you’d like to receive.

    브라우저는 자동으로 몇몇 필수적인 리퀘스트 헤더를 추가한다. 그러나 때때로 직접 헤더를 추가하는 것을 유용하게 활용할 수 있다.(인증, 파일 형식 지정 등)

HTTP sandboxing

  • Making HTTP requests in web page scripts once again raises concerns about security. The person who controls the script might not have the same interests as the person on whose computer it is running. More specifically, if I visit themafia.org, I do not want its scripts to be able to make a request to mybank.com, using identifying information from my browser, with instructions to transfer all my money to some random account.

    웹 페이지 스크립트에서 HTTP 리퀘스트를 만드는 건 보안 문제를 고민하게 한다.

  • For this reason, browsers protect us by disallowing scripts to make HTTP requests to other domains (names such as themafia.org and mybank.com).

    따라서, 브라우저는 다른 도메인으로 HTTP 리퀘스트를 만드는 것을 허용하지 않는다.

  • This can be an annoying problem when building systems that want to access several domains for legitimate reasons. Fortunately, servers can include a header like this in their response to explicitly indicate to the browser that it is okay for the request to come from another domain:

    이는 합법적인 이유로 여러 도메인에 접근해야 하는 시스템을 만들 때 성가시다. 다행히 서버는 다음과 같은 헤더를 리스폰스에 포함하여 브라우저에게 명시적으로 다른 도메인에서 오는 리퀘스트를 허가한다고 지시할 수 있다.

  • Access-Control-Allow-Origin: *

Appreciating HTTP

  • When building a system that requires communication between a JavaScript program running in the browser (client-side) and a program on a server (server-side), there are several different ways to model this communication.

    브라우저에서 작동하는 자바스크립트 프로그램과 서버에서 작동하는 프로그램 사이에서 의사소통이 필요한 시스템을 만들 때, 이 커뮤니케이션을 모델링하는 여러가지 방법들이 있다.

  • A commonly used model is that of remote procedure calls. In this model, communication follows the patterns of normal function calls, except that the function is actually running on another machine. Calling it involves making a request to the server that includes the function’s name and arguments. The response to that request contains the returned value.

    remote procedure call 모델은 일반적으로 사용되는 모델이다. 이 모델에서 커뮤니케이션은 함수가 실제로는 다른 머신에서 실행된다는 점을 제외하곤 일반적인 함수 호출 패턴을 따른다. 이러한 함수를 호출하는 것은 서버로의 리퀘스트에 함수의 이름과 인자들을 담고, 리스폰스가 반환 값을 담는 것이다.

  • When thinking in terms of remote procedure calls, HTTP is just a vehicle for communication, and you will most likely write an abstraction layer that hides it entirely.

    이런 관점에서 HTTP는 단지 커뮤니케이션의 운송 수단이고, 이를 완전히 숨기는 추상화 계층을 작성할 가능성이 클 것이다.

  • Another approach is to build your communication around the concept of resources and HTTP methods. Instead of a remote procedure called addUser, you use a PUT request to /users/larry. Instead of encoding that user’s properties in function arguments, you define a JSON document format (or use an existing format) that represents a user. The body of the PUT request to create a new resource is then such a document. A resource is fetched by making a GET request to the resource’s URL (for example, /user/larry), which again returns the document representing the resource.

    다른 방법으로는 리소스와 HTTP 메소드를 바탕으로 커뮤니케이션을 만드는 것이다.

  • This second approach makes it easier to use some of the features that HTTP provides, such as support for caching resources. The concepts used in HTTP, which are well designed, can provide a helpful set of principles to design your server interface around.

    두 번째 방식은 HTTP가 제공하는 몇 가지 특성을 더 쉽게 사용할 수 있게 만든다(예-캐싱). 잘 설계 된, HTTP에서 사용되는 개념은 서버 인터페이스를 제공하는데 도움이 되는 일련의 원칙들을 제공할 수 있다.

Security and HTTPS

  • The secure HTTP protocol, used for URLs starting with https://, wraps HTTP traffic in a way that makes it harder to read and tamper with. Before exchanging data, the client verifies that the server is who it claims to be by asking it to prove that it has a cryptographic certificate issued by a certificate authority that the browser recognizes. Next, all data going over the connection is encrypted in a way that should prevent eavesdropping and tampering.
  • Thus, when it works right, HTTPS prevents other people from impersonating the website you are trying to talk to and from snooping on your communication. It is not perfect, and there have been various incidents where HTTPS failed because of forged or stolen certificates and broken software, but it is a lot safer than plain HTTP.

Form fields

  • Forms were originally designed for the pre-JavaScript Web to allow web sites to send user-submitted information in an HTTP request. This design assumes that interaction with the server always happens by navigating to a new page.

    폼은 자바스크립트 이전의 웹에서 사용자가 제출한 정보를 HTTP 리퀘스트로 전송하기 위해 고안되었다. 이러한 디자인은 서버와의 상호작용이 언제나 새로운 페이지로 향하면서 일어난다고 가정한다.

  • But their elements are part of the DOM like the rest of the page, and the DOM elements that represent form fields support a number of properties and events that are not present on other elements. These make it possible to inspect and control such input fields with JavaScript programs and do things such as adding new functionality to a form or using forms and fields as building blocks in a JavaScript application.
  • A web form consists of any number of input fields grouped in a <form> tag. HTML allows several different styles of fields, ranging from simple on/off checkboxes to drop-down menus and fields for text input.

    웹 폼은 <form> 태그 안에 임의의 개수의 입력 필드들로 구성된다. HTML은 여러 스타일의 필드들을 사용할 수 있다.

  • A lot of field types use the <input> tag. This tag’s type attribute is used to select the field’s style. These are some commonly used <input> types:

    많은 필드 타입들은 <input> 태그를 사용하며 이 태그의 type 어트리뷰트로 필드의 스타일을 선택할 수 있다.

  • text        A single-line text field
    password    Same as text but hides the text that is typed
    checkbox    An on/off switch
    radio        (Part of) a multiple-choice field
    file        Allows the user to choose a file from their computer
  • Form fields do not necessarily have to appear in a <form> tag. You can put them anywhere in a page. Such form-less fields cannot be submitted (only a form as a whole can), but when responding to input with JavaScript, we often don’t want to submit our fields normally anyway.

    폼 필드들을 반드시 <form> 태그 안에 넣어야 하는 것은 아니다. 이러한 필드는 제출될 수 없다. 그러나 자바스크립트를 사용하여 입력에 반응할 때는 필드를 제출하는 것을 원하지 않기도 한다.

  • <p><input type="text" value="abc"> (text)</p>
    <p><input type="password" value="abc"> (password)</p>
    <p><input type="checkbox" checked> (checkbox)</p>
    <p><input type="radio" value="A" name="choice">
       <input type="radio" value="B" name="choice" checked>
       <input type="radio" value="C" name="choice"> (radio)</p>
    <p><input type="file"> (file)</p>
  • The JavaScript interface for such elements differs with the type of the element.
  • Multiline text fields have their own tag, <textarea>, mostly because using an attribute to specify a multiline starting value would be awkward. The <textarea> tag requires a matching </textarea> closing tag and uses the text between those two, instead of the value attribute, as starting text.

    여러 줄의 텍스트 필드는 <textarea> 태그를 사용한다. 이 태그는 쌍을 갖춰 써야하고, value 어트리뷰터가 아니라 태그 사이의 텍스트가 시작 텍스트가 된다.

  • <textarea>
    one
    two
    three
    </textarea>
  • The <select> tag is used to create a field that allows the user to select from a number of predefined options.

    <select> 태그는 사전에 정의한 옵션들 중 하나를 선택할 수 있는 필드를 만든다.

  • <select>
        <option>Pancakes</option>
        <option>Pudding</option>
        <option>Ice cream</option>
    </select>
  • Whenever the value of a form field changes, it will fire a "change" event.

    폼 필드의 값이 변할 때마다 "change" 이벤트가 발생한다.

Focus

  • Unlike most elements in HTML documents, form fields can get keyboard focus. When clicked or activated in some other way, they become the currently active element and the recipient of keyboard input.

    대부분의 엘리먼트와 다르게 폼 필드는 키보드 포커스를 가질 수 있다.

  • Thus, you can type into a text field only when it is focused. Other fields respond differently to keyboard events. For example, a <select> menu tries to move to the option that contains the text the user typed and responds to the arrow keys by moving its selection up and down.

    따라서 한 텍스트 필드가 있다면 이 필드가 지금 포커스를 갖고 있어야 텍스트를 써 넣을 수 있다. 또한, 다른 필드들은 키보드 이벤트에 다르게 반응한다.

  • We can control focus from JavaScript with the focus and blur methods. The first moves focus to the DOM element it is called on, and the second removes focus. The value in document.activeElement corresponds to the currently focused element.

    자바스크립트와 focus, blur 메소드를 사용하여 포커스를 제어할 수 있다. focus 메소드는 메소드가 호출된 DOM 엘리먼트로 포커스를 옮기고, blur 메소드는 포커스를 제거한다. document.activeElement는 현재 포커싱된 엘리먼트를 말한다.

  • <input type="text">
    <script>
        document.querySelector("input").focus();
        console.log(document.activeElement.tagName);
        // INPUT
        document.querySelector("input").blur();
        console.log(document.activeElement.tagName);
        // BODY
    </script>
  • For some pages, the user is expected to want to interact with a form field immediately. JavaScript can be used to focus this field when the document is loaded, but HTML also provides the autofocus attribute, which produces the same effect while letting the browser know what we are trying to achieve. This gives the browser the option to disable the behavior when it is not appropriate, such as when the user has put the focus on something else.

    사용자가 어떤 폼 필드와 즉시 상호작용하고 싶을거라 기대되는 페이지에서는, 페이지가 로드될 때 이 필드에 자바스크립트로 포커스를 줄 수 있다. HTML 역시 autofocus 어트리뷰트로 같은 기능을 달성할 수 있게 해준다.

  • Browsers traditionally also allow the user to move the focus through the document by pressing the tab key. We can influence the order in which elements receive focus with the tabindex attribute. The following example document will let the focus jump from the text input to the OK button, rather than going through the help link first:

    브라우저는 탭 키를 이용하여 사용자가 포커스를 이동할 수 있도록 해 왔다. tabindex 어트리뷰트를 사용하여 엘리먼트들이 포커스를 받는 순서를 바꿀 수 있다.

  • <input type="text" tabindex=1> <a href=".">(help)</a>
    <button onclick="console.log('ok')" tabindex=2>OK</button>
  • By default, most types of HTML elements cannot be focused. But you can add a tabindex attribute to any element that will make it focusable. A tabindex of -1 makes tabbing skip over an element, even if it is normally focusable.

    기본적으로 대부분의 HTML 엘리먼트트는 포커스를 가질 수 없으나 tabindex 어트리뷰트를 추가하여 포커스를 가질 수 있도록 만들 수도 있다. tabindex를 -1로 하면 포커스를 가질 수 있는 엘리먼트라도 무시하게 만들 수 있다.

Disabled fields

  • All form fields can be disabled through their disabled attribute. It is an attribute that can be specified without value.
  • <button>I'm all right.</button>
    <button disabled>I'm out</button>
  • Disabled fields cannot be focused or changed, and browsers make them look gray and faded.
  • When a program is in the process of handling an action caused by some button or other control that might require communication with the server and thus take a while, it can be a good idea to disable the control until the action finishes. That way, when the user gets impatient and clicks it again, they don’t accidentally repeat their action.

The form as a whole

  • When a field is contained in a <form> element, its DOM element will have a form property linking back to the form’s DOM element. The <form> element, in turn, has a property called elements that contains an array-like collection of the fields inside it.

    한 필드가 <form> 엘리먼트에 포함되어 있으면 그 필드의 DOM 엘리먼트는 form 프로터피로 폼의 DOM 엘리먼트에 접근할 수 있다. 폼 엘리먼트는 배열과 비슷한 필드들의 컬렉션을 elements 속성으로 갖는다.

  • The name attribute of a form field determines the way its value will be identified when the form is submitted. It can also be used as a property name when accessing the form’s elements property, which acts both as an array-like object (accessible by number) and a map (accessible by name).

    폼 필드의 name 어트리뷰트는 해당 폼이 제출되었을 때 폼 필드의 값을 확인하는 방법을 결정한다. 폼의 elements 프로퍼티는 배열처럼 숫자로도 접근 가능하고, 맵처럼 이름으로도 접근 가능한데, 이때 name 어트리뷰트를 사용한다.

  • <form action="example/submit.html">
        Name: <input type="text" name="name"><br>
        Password: <input type="password" name="password"><br>
        <button type="submit">Log in</button>
    </form>
    <script>
        let form = document.querySelector("form");
        console.log(form.elements[1].type);
        // password
        console.log(form.elements.password.type);
        // password
        console.log(form.elements.name.form == form);
        // true
    </script>
  • A button with a type attribute of submit will, when pressed, cause the form to be submitted. Pressing enter when a form field is focused has the same effect.

    type 어트리뷰트를 submit으로 정의한 버튼이 클릭되면 폼이 제출된다. 폼 필드가 포커스된 채로 ENTER키를 누르는 것도 같은 효과를 가진다.

  • Submitting a form normally means that the browser navigates to the page indicated by the form’s action attribute, using either a GET or a POST request. But before that happens, a "submit" event is fired. You can handle this event with JavaScript and prevent this default behavior by calling preventDefault on the event object.

    폼을 제출한다는 것은 일반적으로 폼의 action 어트리뷰트에 지정된 페이지로 GET 또는 POST 메소드를 사용하여 브라우저가 이동하는 것을 말한다. 그러나 그 전에, "submit" 이벤트가 발생한다. 따라서, 이러한 기본 작동 방식을 preventDefault 메소드를 사용하여 막을 수도 있다.

  • <form action="example/submit.html">
        Value: <input type="text" name="value">
        <button type="submit">Save</button>
    </form>
    <script>
        let form = document.querySelector("form");
        form.addEventListener("submit", event => {
            console.log("Saved value", form.elements.value.value);
            event.preventDefault();
        });
    </script>
  • Intercepting "submit" events in JavaScript has various uses. We can write code to verify that the values the user entered make sense and immediately show an error message instead of submitting the form. Or we can disable the regular way of submitting the form entirely, as in the example, and have our program handle the input, possibly using fetch to send it to a server without reloading the page.

    이는 입력의 유효성을 검사하거나, 페이지 전환 없이 fetch를 사용하여 서버에게 입력을 보내는 등으로 활용할 수 있디.

Text fields

  • Fields created by <textarea> tags, or <input> tags with a type of text or password, share a common interface. Their DOM elements have a value property that holds their current content as a string value. Setting this property to another string changes the field’s content.

    <textarea>, text, password 타입의 <input>은 공통된 인터페이스를 갖는다. 그들의 DOM 엘리먼트는 value 프로퍼티로 현재 가진 값을 문자열로 갖는다. 이 속성을 바꾸면 해당 필드의 내용이 바뀐다.

  • The selectionStart and selectionEnd properties of text fields give us information about the cursor and selection in the text. When nothing is selected, these two properties hold the same number, indicating the position of the cursor. For example, 0 indicates the start of the text, and 10 indicates the cursor is after the 10th character. When part of the field is selected, the two properties will differ, giving us the start and end of the selected text. Like value, these properties may also be written to.

    selectionStart, selectionEnd

  • <textarea></textarea>
    <script>
        let textarea = document.querySelector("textarea");
        textarea.addEventListener("keydown", event => {
            // The key code for F2 happens to be 113
            if (event.keyCode == 113) {
                replaceSelection(textarea, "Khasekhemwy");
                event.prevendDefault();
            }
        });
    
        function replaceSelection(field, word) {
            let from = field.selectionStart, to = field.selectionEnd;
            field.value = field.value.slice(0, from) + word +
                          field.value.slice(to);
            field.selectionStart = from + word.length;
            field.selectionEnd = from + word.length;
        }
    </script>

    "keydown" 이벤트

  • The "change" event for a text field does not fire every time something is typed. Rather, it fires when the field loses focus after its content was changed. To respond immediately to changes in a text field, you should register a handler for the "input" event instead, which fires for every time the user types a character, deletes text, or otherwise manipulates the field’s content.

    텍스트 필드의 "change" 이벤트는 뭔가가 타이핑될 때마다 발생하지는 않는다. 필드의 내용이 바뀐 뒤 그 필드가 포커스를 잃을 때만 발생한다. 텍스트 필드의 변화에 즉시 반응하기 위해서는 "input" 이벤트의 핸들러를 등록해야 한다.

  • <input type="text"> length: <span id="length">0</span>
    <script>
        let text = document.querySelector("input");
        let output = documenet.querySelector("#length");
        text.addEventListener("input", () => {
            output.textContent = text.value.length;
        });
    </script>

Checkboxes and radio buttons

  • A checkbox field is a binary toggle. Its value can be extracted or changed through its checked property, which holds a Boolean value.

    체크박스 필드의 값은 checked 프로퍼티를 통해 가져오거나 바꿀 수 있다. 이 값은 불리안이다.

  • <label>
        <input type="checkbox" id="purple"> Make this page purple
    </label>
    <script>
        let checkbox = document.querySelector("#purple");
        checkbox.addEventListener("change", () => {
            document.body.style.background = 
                checkbox.checked ? "mediumpurple" : "";
        });
    </script>
  • The <label> tag associates a piece of document with an input field. Clicking anywhere on the label will activate the field, which focuses it and toggles its value when it is a checkbox or radio button.

    <label> 태그는 입력 필드와 문서를 결합시킨다. 레이블의 어떤 곳이든 클릭하면 해당 필드가 활성화된다. 즉, 필드에 포커스를 주고 그 필드가 체크박스나 라디오버튼일 경우 토글한다.

  • A radio button is similar to a checkbox, but it’s implicitly linked to other radio buttons with the same name attribute so that only one of them can be active at any time.

    라디오버튼은 체크박스와 비슷하지만, 같은 name 어트리뷰트를 갖는 버튼들 끼리 암묵적으로 묶여 한 번에 하나만 활성화될 수 있다.

  • Color:
    <label>
        <input type="radio" name="color" value="orange"> Orange
    </label>
    <label>
        <input type="radio" name="color" value="lightgreen"> Green
    </label>
    <label>
        <input type="radio" name="color" value="lightblue"> Blue
    </label>
    <script>
        let buttons = document.querySelectorAll("[name=color]");
        for (let button of Array.from(buttons)) {
            // 선택될 때만 이벤트가 발생하는 듯
            // 잃을 때는 발생하지 않음
            botton.addEventListener("change", () => {
                document.body.style.background = button.value;
            });
        }
    </script>
  • The square brackets in the CSS query given to querySelectorAll are used to match attributes. It selects elements whose name attribute is "color".

    [...]를 사용한 CSS 쿼리는 어트리뷰트를 매치하기 위해 사용된다. 예시에서는 name 어트리뷰트의 값이 "color"인 엘리먼트들을 선택한다.

Select fields

  • Select fields are conceptually similar to radio buttons—they also allow the user to choose from a set of options. But where a radio button puts the layout of the options under our control, the appearance of a <select> tag is determined by the browser.

    선택 필드는 라디오버튼과 비슷하다. 그러나, 라디오버튼은 옵션들의 레이아웃을 우리가 제어할 수 있는 반면, <select>의 모양은 브라우저에 의해 결정된다.

  • Select fields also have a variant that is more akin to a list of checkboxes, rather than radio boxes. When given the multiple attribute, a <select> tag will allow the user to select any number of options, rather than just a single option. This will, in most browsers, show up differently than a normal select field, which is typically drawn as a drop-down control that shows the options only when you open it.

    <select> 태그에 multiple 어트리뷰트를 주면 선택 필드를 체크박스와 비슷한 형태로 사용할 수 있다. (여러 개를 고를 수 있다.) 이렇게 하면 드롭다운 방식의 일반적인 선택 필드 모양과 달라질 수 있다.

  • Each <option> tag has a value. This value can be defined with a value attribute. When that is not given, the text inside the option will count as its value. The value property of a <select> element reflects the currently selected option. For a multiple field, though, this property doesn’t mean much since it will give the value of only one of the currently selected options.

    <option> 태그는 각각의 값을 갖는다. 이 값은 value 어트리뷰트에 의해 정의될 수 있다. 만약 정의되지 않는다면, <option> 태그 내의 텍스트가 값으로 사용될 것이다. <select> 엘리먼트의 value 프로퍼티는 현재 선택된 옵션을 나타내지만, 만약 multiple 필드인 경우 선택된 옵션들 중 하나만 나타내는 이 프로퍼티는 큰 의미를 갖지 못한다.

  • The <option> tags for a <select> field can be accessed as an array-like object through the field’s options property. Each option has a property called selected, which indicates whether that option is currently selected. The property can also be written to select or deselect an option.

    <option> 태그들은 배열과 비슷한 객체인 <select>options 프로퍼티를 통해 접근할 수 있다. 각 옵션은 현재 옵션이 선택되었는 지를 나타내는 selected 프로퍼티를 갖는다. 이 프로퍼티는 선택과 선택 해제를 위해 값을 바꿀 수 있다.

  • <!-- CONTROL이나 COMMAND 키 사용 -->
    <select multiple>
        <option value="1">0001</option>
        <option value="2">0010</option>
        <option value="4">0100</option>
        <option value="8">1000</option>
    </select> = <span id="output">0</span>
    <script>
        let select = document.querySelector("select");
        let output = document.querySelector("#output");
        select.addEventListener("change", () => {
            let number = 0;
            for (let option of Array.from(select.options)) {
                if (option.selected) {
                    number += Number(option.value);
                }
            }
            output.textContent = number;
        });
    </script>

File fields

  • File fields were originally designed as a way to upload files from the user’s machine through a form. In modern browsers, they also provide a way to read such files from JavaScript programs. The field acts as a kind of gatekeeper. The script cannot simply start reading private files from the user’s computer, but if the user selects a file in such a field, the browser interprets that action to mean that the script may read the file.

    원래, 파일 필드는 사용자의 머신의 파일들을 폼을 통해 업로드할 수 있도록 고안되었다. 모던 브라우저에서 사용자의 파일을 자바스크립트 프로그램이 읽을 수 있는 방법이기도 하다. 일반적으로 스크립트는 사용자의 컴퓨터에 있는 파일을 읽을 수 없지만, 만약 사용자가 이러한 필드에서 한 파일을 선택한다면 브라우저는 이를 해당 스크립트가 그 파일을 읽을 수 있는 것이라고 이해한다.

  • A file field usually looks like a button labeled with something like “choose file” or “browse”, with information about the chosen file next to it.
  • <input type="file">
    <script>
        let input = document.querySelector("input");
        input.addEventListener("change", () => {
            if (input.files.length > 0) {
                let file = input.files[0];
                console.log("You chose", file.name);
                if (file.type) console.log("It has type", file.type);
            }
        });
    </script>
  • The files property of a file field element is an array-like object (again, not a real array) containing the files chosen in the field. It is initially empty. The reason there isn’t simply a file property is that file fields also support a multiple attribute, which makes it possible to select multiple files at the same time.

    파일 필드 엘리먼트의 files 프로퍼티는 배열과 비슷한 객체로 해당 필드에 선택된 파일들을 가지고 있다. 파일 필드 역시 multiple 어트리뷰트를 주어 한 번에 여러 파일을 선택할 수 있게 할 수 있다.

  • Objects in the files object have properties such as name (the filename), size (the file’s size in bytes, which are chunks of 8 bits), and type (the media type of the file, such as text/plain or image/jpeg).

    files 객체 속의 객체들은 size, name, type 등의 프로퍼티를 갖는다.

  • What it does not have is a property that contains the content of the file. Getting at that is a little more involved. Since reading a file from disk can take time, the interface must be asynchronous to avoid freezing the document.

    파일의 내용을 읽는 프로퍼티는 없다. 내용을 읽는 것은 조금 복잡한데, 그 인터페이스는 반드시 비동기적이어야 한다.

  • <input type="file" multiple>
    <script>
        let input = document.querySelector("input");
        input.addEventListener("change", () => {
            for (let file of Array.from(input.files)) {
                let reader = new FileReader();
                reader.addEventListener("load", () => {
                    console.log("File", file.name, "starts with",
                                reader.result.slice(0, 20));
                });
                reader.readAsText(file);
            }
        });
    </script>
  • Reading a file is done by creating a FileReader object, registering a "load" event handler for it, and calling its readAsText method, giving it the file we want to read. Once loading finishes, the reader’s result property contains the file’s content.

    FileReader 객체를 만들고 그 객체에 "load" 이벤트 핸들러를 등록한 다음, 그 객체의 readAsText에 읽고 싶은 파일을 넘겨주면 파일을 읽을 수 있다. 로드가 끝나면 리더의 result 프로퍼티가 파일의 내용을 갖게 된다.

  • FileReaders also fire an "error" event when reading the file fails for any reason. The error object itself will end up in the reader’s error property. This interface was designed before promises became part of the language. You could wrap it in a promise like this:

    FileReader가 파일 읽기를 실패했을 때 error 이벤트가 발생한다. 그 에러 객체는 리더의 error 프로퍼티에 담긴다.

  • function readFileText(file) {
        return new Promise((resolve, reject) => {
            let reader = new FileReader();
            reader.addEventListener(
                "load", () => resolve(reader.result));
            reader.addEventListener(
                "error", () => reject(reader.error));
            reader.readAsText(file);
        });
    }

Storing data client-side

  • Simple HTML pages with a bit of JavaScript can be a great format for “mini applications”—small helper programs that automate basic tasks.

    작은 애플리케이션

  • When such an application needs to remember something between sessions, you cannot use JavaScript bindings—those are thrown away every time the page is closed. You could set up a server, connect it to the Internet, and have your application store something there. But that’s a lot of extra work and complexity. Sometimes it is enough to just keep the data in the browser.

  • The localStorage object can be used to store data in a way that survives page reloads. This object allows you to file string values under names.

    localStorage 객체는 페이지가 다시 로드될 때도 유지되는 정보를 저장하는데 사용할 수 있다. 이 객체는 어떤 이름들 하에 문자열 값들을 쌓을 수 있도록 한다.

  • localStorage.setItem("username", "marijn");
    console.log(localStorage.getItem("username"));
    // marijn
    localStorage.removeItem("username");
  • A value in localStorage sticks around until it is overwritten, it is removed with removeItem, or the user clears their local data.

    localStorage의 값은 덮어 씌워지거나, removeItem에 의해 삭제되거나, 사용자가 그들의 로컬 데이터를 지울 때까지 보존된다. (+ localStorage.clear())

  • Sites from different domains get different storage compartments. That means data stored in localStorage by a given website can, in principle, be read (and overwritten) only by scripts on that same site.

    다른 도메인의 사이트들은 다른 저장 공간을 갖는다. 즉, 어떤 주어진 사이트의 localStorage 데이터는 원칙적으로 같은 사이트의 스크립트에 의해서만 접근 가능하다.

  • Browsers do enforce a limit on the size of the data a site can store in localStorage. That restriction, along with the fact that filling up people’s hard drives with junk is not really profitable, prevents the feature from eating up too much space.

    브라우저는 한 사이트가 localStorage에 저장할 수 있는 데이터의 크기를 엄격히 제약한다.

  • Notes: <select></select> <button>Add</button><br>
    <textarea style="width: 100%"></textarea>
    
    <script>
        let list = document.querySelector("select");
        let note = document.querySelector("textarea");
    
        let state;
        function setState(newState) {
            // NOTE: option들을 지운다;
            // list.options.length이 0인 것을 확인 가능
            list.textContent = "";
            for (let name of Object.keys(newState.notes)) {
                let option = document.createElement("option");
                option.textContent = name;
                if (newState.selected == name) option.selected = true;
                list.appendChild(option);
            }
            note.value = newState.notes[newState.selected];
    
            localStorage.setItem("Notes", JSON.stringify(newState));
            state = newState;
        }
        setState(JSON.parse(localStorage.getItem("Notes")) || {
            notes: {"shopping list": "Carrots\nRaisins"},
            selected: "shopping list"
        });
    
        list.addEventListener("change", () => {
            setState({notes: state.notes, selected: list.value});
        });
        // "input"이 아니라 "change"를 사용
        note.addEventListener("change", () => {
            setState({
                notes: Object.assign({}, state.notes,
                                     {[state.selected]: note.value}),
                selected: state.selected
            });
        });
        document.querySelector("button")
            .addEventListener("click", () => {
                let name = prompt("Note name");
                if (name) setState({
                    notes: Object.assign({}, state.notes, {[name]: ""}),
                    selected: name
                });
            });
    </script>
  • Reading a field that does not exist from localStorage will yield null. Passing null to JSON.parse will make it parse the string "null" and return null.

    localStorage에 없는 필드를 읽으면 null이 반환될 것이다. JSON.parsenull을 주면 JSON.parse는 문자열 "null"을 파싱하여 결국 null을 반환한다.

  • Object.assign takes its first argument and adds all properties from any further arguments to it. Thus, giving it an empty object will cause it to fill a fresh object. The square brackets notation in the third argument is used to create a property whose name is based on some dynamic value.

    Object.assign은 첫 번째 인자에 나머지 인자들의 모든 속성들을 더한다. 그러므로 빈 객체를 주는 것은 새로운 객체를 채우게 된다. 세 번째 인자의 [] 표기법은 동적인 값으로 프로퍼티를 생성하기 위해 사용되었다.

  • There is another object, similar to localStorage, called sessionStorage. The difference between the two is that the content of sessionStorage is forgotten at the end of each session, which for most browsers means whenever the browser is closed.

    localStorage와 비슷한 객체로 sessionStorage가 있다. sessionStorage의 내용은 매 세션이 끝날 때마다 사라진다. 대부분의 브라우저에서 이는 해당 브라우저가 닫혔을 때를 말한다.

Summary

  • A page may also contain forms, which allow information entered by the user to be sent as a request for a new page when the form is submitted.
  • ... Such fields can be inspected and manipulated with JavaScript. They fire the "change" event when changed, fire the "input" event when text is typed, and receive keyboard events when they have keyboard focus. Properties like value (for text and select fields) or checked (for checkboxes and radio buttons) are used to read or set the field’s content.
  • When a form is submitted, a "submit" event is fired on it. A JavaScript handler can call preventDefault on that event to disable the browser’s default behavior. Form field elements may also occur outside of a form tag.
  • The localStorage and sessionStorage objects can be used to save information in a way that survives page reloads. The first object saves the data forever (or until the user decides to clear it), and the second saves it until the browser is closed.

Exercises

Content negotiation

  • One of the things HTTP can do is called content negotiation. The Accept request header is used to tell the server what type of document the client would like to get. Many servers ignore this header, but when a server knows of various ways to encode a resource, it can look at this header and send the one that the client prefers.

    HTTP가 할 수 있는 것 중 하나로 컨텐츠 협상이라는 것이 있다. 리퀘스트 헤더 Accept는 어떤 타입의 문서를 클라이언트가 받고 싶은지를 명시한다. 많은 서버는 이를 무시하지만, 만약 서버가 한 리소스를 여러 방식으로 인코딩하는 방법들을 안다면, 이 헤더를 보고 클라이언트가 원하는 것을 보낼 수 있다.

  • fetch("https://eloquentjavascript.net/author", {
        headers: {Accept: "text/plain"}
    }).then(res => console.log(res.status));
    
    fetch("https://eloquentjavascript.net/author", {
        headers: {Accept: "text/html"}
    }).then(res => console.log(res.status));
    
    fetch("https://eloquentjavascript.net/author", {
        headers: {Accept: "application/json"}
    }).then(res => console.log(res.status));
    
    fetch("https://eloquentjavascript.net/author", {
        headers: {Accept: "application/rainbows+unicorns"}
    }).then(res => console.log(res.status));
    // 406
    // “Not acceptable”, which is the code a server should return
    // when it can’t fulfill the Accept header.
  • // solution
    const url = "https://eloquentjavascript.net/author";
    const types = ["text/plain",
                   "text/html",
                   "application/json",
                   "application/rainbows+unicorns"];
    
    async function showTypes() {
        for (let type of types) {
            let resp = await fetch(url, {headers: {accept: type}});
            console.log(`${type}: ${await resp.text()}\n`);
        }
    }
    
    showTypes();

A JavaScript workbench

  • <textarea id="code">return "hi";</textarea>
    <button id="button">Run</button>
    <pre id="output"></pre>
    
    <script>
        let code = document.querySelector("#code");
        let output = document.querySelector("#output");
    
        document.querySelector("#button")
            .addEventListener("click", () => {
                let result;
                // Make sure you wrap both the call to Function and 
                // the call to its result in a try block 
                // so you can catch the exceptions it produces. (why?)
                try {
                    result = Function(code.value)();
                } catch (e) {
                    result = e;
                }
                output.textContent += String(result);
            });
    </script>
  • // solution 
    document.querySelector("#button").addEventListener("click", () => {
        let code = document.querySelector("#code").value;
        let outputNode = document.querySelector("#output");
        try {
            let result = Function(code)();
            outputNode.innerText = String(result);
        } catch (e) {
            outputNode.innerText = "Error: " + e;
        }
    });
  • innerText vs. textContent

Conway’s Game of Life

  • <div id="grid"></div>
    <button id="next">Next generation</button>
    
    <script>
        const width = 10;
        const height = 10;
        let grid = document.querySelector("#grid");
    
        let rows = new Array(height);
        for (let i = 0; i < height; ++i) {
            rows[i] = [];
            let line = document.createElement("div");
            for (let j = 0; j < width; ++j) {
                let checkbox = document.createElement("input");
                checkbox.type = "checkbox";
                checkbox.checked = Math.floor(Math.random() * 2) == 1;
                rows[i].push(checkbox);
                line.appendChild(checkbox);
            }
            grid.appendChild(line);
        }
    
        const dr = [0, 0, 1, -1, 1, 1, -1, -1];
        const dc = [1, -1, 0, 0, 1, -1, 1, -1];
    
        let button = document.querySelector("#next");
        button.addEventListener("click", () => {
            for (let r = 0; r < height; ++r) {
                for (let c = 0; c < width; ++c) {
                    let curBox = rows[r][c];
                    function isVaild(r, c) {
                        return 0 <= r && r < height &&
                               0 <= c && c < width; 
                    }
    
                    let live = 0, dead = 0;
                    for (let i = 0; i < 8; ++i) {
                        let nr = r + dr[i];
                        let nc = c + dc[i];
                        if (!isVaild(nr, nc)) continue;
                        if (rows[nr][nc].checked) ++live;
                        else ++dead;
                    }
    
                    if (curBox.checked) {
                        if (live != 2 && live != 3) {
                            curBox.checked = false;
                        }
                    } else {
                        if (live == 3) curBox.checked = true;
                    }
                }
            }
        });
    
    </script>

    잘 못 풀었음; 먼저 생각을 깊게 하고 코딩하는 습관이 필요하다!

  • To solve the problem of having the changes conceptually happen at the same time, try to see the computation of a generation as a pure function, which takes one grid and produces a new grid that represents the next turn.

  • <!-- solution -->
    <!doctype html>
    <script src="code/chapter/18_http.js"></script>
    
    <div id="grid"></div>
    <button id="next">Next generation</button>
    <button id="run">Auto run</button>
    
    <script>
    const width = 30, height = 15;
    
    // I will represent the grid as an array of booleans.
    
    let gridNode = document.querySelector("#grid");
    // This holds the checkboxes that display the grid in the document.
    let checkboxes = [];
    for (let y = 0; y < height; y++) {
        for (let x = 0; x < width; x++) {
            let box = document.createElement("input");
            box.type = "checkbox";
            gridNode.appendChild(box);
            checkboxes.push(box);
        }
        gridNode.appendChild(document.createElement("br"));
    }
    
    function gridFromCheckboxes() {
        return checkboxes.map(box => box.checked);
    }
    function checkboxesFromGrid(grid) {
        grid.forEach((value, i) => checkboxes[i].checked = value);
    }
    function randomGrid() {
        let result = [];
        for (let i = 0; i < width * height; i++) {
            result.push(Math.random() < 0.3);
        }
        return result;
    }
    
    checkboxesFromGrid(randomGrid());
    
    // This does a two-dimensional loop over the square around the given
    // x,y position, counting all fields that have a cell but are not the
    // center field.
    function countNeighbors(grid, x, y) {
        let count = 0;
        for (let y1 = Math.max(0, y - 1); y1 <= Math.min(height - 1, y + 1); y1++) {
            for (let x1 = Math.max(0, x - 1); x1 <= Math.min(width - 1, x + 1); x1++) {
                if ((x1 != x || y1 != y) && grid[x1 + y1 * width]) {
                    count++;
                }
            }
        }
        return count;
    }
    
    function nextGeneration(grid) {
        let newGrid = new Array(width * height);
        for (let y = 0; y < height; y++) {
            for (let x = 0; x < width; x++) {
                let neighbors = countNeighbors(grid, x, y);
                let offset = x + y * width;
                if (neighbors < 2 || neighbors > 3) {
                    newGrid[offset] = false;
                } else if (neighbors == 2) {
                    newGrid[offset] = grid[offset];
                } else {
                    newGrid[offset] = true;
                }
            }
        }
        return newGrid;
    }
    
    function turn() {
        checkboxesFromGrid(nextGeneration(gridFromCheckboxes()));
    }
    
    document.querySelector("#next").addEventListener("click", turn);
    
    let running = null;
    document.querySelector("#run").addEventListener("click", () => {
        if (running) {
            clearInterval(running);
            running = null;
        } else {
            running = setInterval(turn, 400);
        }
    });
    </script>