본문 바로가기

Develop/HTML & JavaScript & CSS

JavaScript logMessage

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; padding: 30px; }
            form { width: 100%; height: 50px; display: flex; column-gap: 10px; }
            input, button { border: 1px solid lightgrey; border-radius: 8px; }
            input { width: 100%; padding: 0 15px; outline: none; }
            button { width: 100px; background-color: #3498db; color: white; }
            button:hover { background-color: #2980b9; }
            ul { list-style: none; margin: 20px 10px; }
            li { border-bottom: 1px dotted lightgray; padding-bottom: 7px; margin-bottom: 7px; }
        </style>
    </head>
    <body>
        <div><input type="text" placeholder="할 일을 입력하세요." /><button type="button">등록</button></div>
        <ul></ul>
        <div class="flex">
            <pre id="console-log"></pre>
        </div>
        <script>
            const button = document.querySelector("button");
            const input = document.querySelector("input");
            const consoleLog = document.querySelector("#console-log");
            const ul = document.querySelector("ul");

            function logMessage(message) {
                consoleLog.innerText += `${message}\n`;
            }

            button.addEventListener("click", (event) => {
                console.log(input.value);

                if (input.value === "") return false;

                const li = document.createElement("li");
                li.innerText = input.value;
                ul.appendChild(li);
                input.value = "";
            });

            input.addEventListener("keyup", (event) => {
                logMessage(`Key "${event.key}" released [event: keyup]`);

                if (event.key === "Enter") {
                    button.click();
                }
            });
        </script>
    </body>
</html>