TOC
wwworkshop
Uni Köln

3.3
User input

To make things a little more dynamic, we can accept some basic input from the user. In this case, we add an input element and react to changes to it in the script.

  1. Add an input element to the HTML and give it an id, so it can be referenced from our script.

  2. In the script, obtain a reference to the element using its id. In this case we use document.querySelector and the # notation to query by id.

  3. Add an event listener to the element to be able to react to it. In this case, we use the blur event, which occurs when the user leaves the input element.

  4. Within the event listener, we use the code to append a new element from the last section, only this time we replace the static text with the current value of the input element.

index.html

<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Titel</title>
</head>
<body>
    <input type="text" id="input">
    <script src="script.js"></script>
</body>
</html>

script.js

const inputElement = document.querySelector('#input')

inputElement.addEventListener('blur', () => {
    const paragraph = document.createElement('p')
    paragraph.innerText = inputElement.value
    document.body.appendChild(paragraph)
})