So you know the basics of HTML and CSS, but not Javascript?
Suppose we have a webpage with the following HTML:
Our goal is to add the text “You clicked me!” to
#output
every time #my-button
is clicked.
This can be done with JavaScript.
Internally, browsers see a page as a heirarchy of nodes—building blocks that make up a page. This heirarchy is sometimes called the Document Object Model, or DOM. JavaScript can access the DOM to react to events initiated by the user, such as clicks or taps, and it can manipulate the DOM in real-time by adding, changing, or removing nodes.
One type of node is an element, which roughly corresponds to tags in an HTML page. For instance, a p
element represents an opening <p>
tag and its corresponding closing tag. Everything in between these two tags are referred to as children of the element.
One such type of child is called a text node, which represents text inside an element.
Here's what the DOM of the HTML at the top of this page looks like:
JavaScript can be hard to learn: there are lots of funny symbols in it
like {
and ;
that have to be entered in just
the right order, or else nothing will happen. Having to deal with this and learning the DOM at the same time can be frustrating, so instead of typing
JavaScript directly, you can use the Blockly-based interface below to write the JavaScript for you. (Don’t
worry, you’ll be learning to write JavaScript yourself soon!)
Try experimenting with the editor below by dragging blocks from the palette on the left side to the workspace area on the right.
The above block-code can be expressed in JavaScript by adding the following to the bottom of our webpage:
And here’s the final webpage, rendered in your browser:
And here's the DOM of the above webpage:
Now see if you can get the text “You clicked me!” to be added to the output every time you click the button labeled “Click me!”.