The importance of timing when working with the DOM
While working with the students in my bootcamp I helped a few of them navigate one problem: timing.
In particular, thereโs one thing that might not be apparent at first.
When you access the value of a DOM element and you store it into a variable, that variable is NOT going to be updated with the new value when the DOM element changes.
Suppose you have an input field in a form <input id="temperature">
, and you get its value in this way:
const temperature = document.querySelector('input#temperature').value
The temperature
variable gets the value of the state of the input field at the moment the browser executes this statement, and then the value stays the same forever.
This is why you canโt do like this:
const temperature = document.querySelector('input#temperature').value
document.querySelector('form')
.addEventListener('submit', event => {
//send the temperature value to your server
})
but you need to access the temperature value when you submit the form:
document.querySelector('form')
.addEventListener('submit', event => {
const temperature = document.querySelector('input#temperature').value
//send the temperature value to your server
})
Alternatively you can store the input field reference in a variable, and use that to access its value at submit:
const temperatureElement = document.querySelector('input#temperature')
document.querySelector('form')
.addEventListener('submit', event => {
const temperature = temperatureElement.value
//send the temperature value to your server
})
THE VALLEY OF CODE
THE WEB DEVELOPER's MANUAL
You might be interested in those things I do:
- Learn to code in THE VALLEY OF CODE, your your web development manual
- Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
- I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
- Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
- Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
- Find me on X