JavaScript in the Browser
Overview
Terms defined: CSS selector, Document Object Model (DOM), event handler, JavaScript `async` keyword, JavaScript `await` keyword, red-green-blue (RGB) color
Outline
- JavaScript was created to make web pages interactive
- Load into page (several ways)
- Trigger execution (also several ways)
- Manipulate Document Object Model (DOM)
log_on_load.html
- Put code directly in
<script>
tag in head of page - Executed as the page loads
- View output in console tab in browser's developer tools
- But this is not reliable
- Code may run while browser is still converting HTML to DOM (or loading other assets)
- Put code directly in
show_headings.html
finds things in the DOMdocument
refers to the content of the pagegetElementsByTagName
finds nodes match a CSS selector
- But it doesn't show anything
- Code may run etc.
show_headings_onload.html
is a better approach- Define a function
- Use the
onload
attribute ofbody
to run it when the body has fully loaded
emphasize_headings.html
modifies the DOM- JavaScript changes in-memory representation of page
- Browser decides what to re-draw and when
emphasize_multistep.html
does the same thing by explicitly manufacturing new nodesbutton_click.html
adds a button with an event handler- Browser standards define lots of different events you can listen to
- You provide the function, you browser calls it when something happens
emphasize_click.html
show_hide.html
controls visibility of elements- But now we have to manage state
async_fetch.html
introduces two new ideas- Put the code in
async_fetch.js
- Use
async
andawait
keywords to wait for things server.py
returns RGB color components- Use
style
property rather thansetAttribute
because style can have many sub-properties
- Put the code in