Uni Köln

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.


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


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

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