Interactivity with JavaScript
| English | Chinese | Pinyin |
|---|---|---|
| DOM | 文档对象模型 | wén dàng duì xiàng mó xíng |
| event | 事件 | shì jiàn |
| function | 函数 | hán shù |
The page changes after it has loaded
- HTML and CSS produce a page. JavaScript makes it respond to what the visitor does.
- It runs in the browser, on the visitor's machine, which is why it is fast and why it can never be trusted with a secret.
- At this level the goal is small and reliable: validate a form, toggle a menu, filter a list.
The DOM
- The DOM 文档对象模型 is the loaded page represented as a tree of objects your code can read and change.
document.querySelector('#menu')finds an element; changing its properties changes the page immediately.- The DOM exists only after the HTML has been parsed, which is why a script that runs too early finds nothing.
What is the DOM?
It exists only after the HTML is parsed, which is why a script that runs too early finds nothing.
Events
- An event 事件 is something that happens: a click, a submit, a key press, a scroll.
- You attach a function 函数 to an event, and the browser calls it when the event occurs.
- ⚠ You do not write a loop that waits for the click. The browser does the waiting; your code is what happens next.
Which method attaches a function to an event on an element?
button.addEventListener("click", fn). The browser does the waiting; your function is what happens next.
A menu button that opens a panel.
const button = document.querySelector('#menu-button');
const panel = document.querySelector('#menu-panel');
button.addEventListener('click', () => {
panel.hidden = !panel.hidden;
});
Three lines of work: find the two elements, listen for the click, flip one property. Most useful interactivity at this level is this shape, and reaching for a library before you can write these three lines is what makes a site fragile.
Put the three steps of a simple interactive feature in order.
Most useful interactivity at this level is exactly this shape, in about five lines.
Build the page so it works before the JavaScript runs. A menu that is a plain list until a script turns it into a dropdown still works when the script fails. A menu that only exists in JavaScript disappears entirely.
Your menu only exists once JavaScript runs. What happens if the script fails?
Build it as a plain list that a script enhances, and a failure costs the enhancement rather than the content.
Client-side validation is a convenience, not a defence. A visitor can bypass anything the browser checks, so the same rules must be checked again on the server — which is exactly what the first unit of GAC017 is about.
If the browser checks a form, the server does not need to check it again.
A visitor can bypass anything the browser checks. Client-side validation is convenience, not defence.