The topic of last week’s Tech Tuesday was CSS, which determines the look and feel of the content of a web page (where the content itself is described in HTML). Today we will learn about Javascript, which is a programming language that lets us control the behavior of the web page (both by itself and in reaction to what the user does). Together HTML, CSS and Javascript determine what a web browser does in Steps 7 and 8 of the web cycle.
What is a programming language? It is a language that lets us tell a computer what to do which is really all that programming is. Javascript was originally developed specifically for telling a web browser what to do, but it is a completely general programming language and has more recently been used to program servers.
Let’s jump into a simple example that will allow us to illustrate the basic idea. Say we have a web page with a list of headlines. For each headline we also have a summary of the story but we only want to show that when someone clicks on the headline so that we can show more headlines and make the page less cluttered. Now we could make each headline a link and set off a web request cycle to go to a new page for that headline but that would be slow and clumsy. As an alternative we could put the headlines at the top of the page and the summaries below and use URLs with fragment identifiers to jump to the summary but that too would make the page scroll around like crazy.
With Javascript we have another alternative. We can keep each summary below its headline but have the summary be hidden and show it only when someone clicks on the headline. How would that work? Let’s first take a look at how we might structure the HTML, i.e. the content itself:
This looks very similar to the HTML we have seen with some extra attributes thrown in which we will use in a second. In order to keep the summaries hidden when the page first loads, we will use some CSS as follows
The .summary is a CSS selector, that picks out all the elements on the page that have the class=“summary” attribute set. By styling these elements with “display: none” we get the web browser not to display them. But they are still part of the HTML and so they are sitting right there on the page, just not visible.
Now we need to sprinkle on a tiny bit of Javascript to let us make a summary visible when the headline above it is clicked. Here is what that might look like: