to class -- to about -- to syllabus -- to people -- to the library

hello js!

This class introduces basic Javascript and some other ideas about interactivity, looking at events and console debugging.

lecture: i n t e r a c t i v i t y

Today we’ll explore ways to make your webpage interactive – something that responds to user input. Many of you already might have tried this in your metaphor class – which, for some of you, really tested the limits of CSS. We’ll introduce some fundamental concepts of Javascript as a language, which will lay the ground for the work that we’ll do over the next few weeks.

interactive CSS
We’re not going to spend much time on this, as this is a class about Javascript. However, there are some built-in CSS interactions that can be pretty useful for very basic kinds of interactivity. A lot of these use something called CSS ‘pseudo-classes’, which are used to specify special states of elements. Some often-used examples of these are.

Think of these as a kind of selector (indeed, pseudo-classes like :first-child and :root operate much more like these), but one that’s also aware of the state of the page.

JS principles
Javascript is the programming language of the web. It is the only programming language that natively runs in the browser, and until a while back that was all it did. (These days it’s possible to run Javascript outside of a browser too, and we’ll do a bit of that later in the semester.)

What is a programming language? Up until now, we’ve been dealing with HTML and CSS: these, while allowing us to change our webpages, are not technically programming languages, but markup and styling languages. While CSS pseudo-classes offer a limited kind of programmability, that’s not what CSS is made for: what we want, to make interactive, dynamic websites, is Javascript.

Programming languages are sets of ordered instructions that tell the computer to do something, normally based on something else. Javascript is what’s called an interpreted language – when your browswer runs Javascript, it just reads it line by line, and completes the steps in order. This is different to some other kinds of computer language, which need to be translated into a different form before they can be used.

events
The first way a lot of people encounter Javascript is dealing with events in webpages. These are often actually properties of the HTML, but we can set up some Javascript to ‘react’ when an event occurs. One of the most common of these is the ‘onclick’ event:

<!DOCTYPE html>
<html>
<body>

<h1>wow, clicking button?</h1>

<button type="button" onclick="console.log('heeeeeeeeeeeyyyyy')">
	im gonna click it
</button>

</body>
</html>

So – we’ve got this onclick part: that’s a property, which we’re familiar with. It belongs to the HTML element. The next part might be a bit less familiar: console.log('heeeeeeeeeeeyyyyy'). Let’s break it down:

The ‘console’ part here is the same console we’ve been using to look at our code in the browser. It’s also what we’re able to use to see what’s going on with Javascript. What other parts are there? The ‘.’ in the middle is a pretty common idea in Javascript, and we’ll use it a lot. It means ‘this thing on the left, before me – it has a property (that thing on the right) that I want to access’. In this instance, we’re accessing the property – this method – ‘log’ of the console. This is a cool property! Whatever we put in the brackets after the ‘log’, it’ll print them out (or log them) to the console.

so – give it a click! take a look at the console!

Javascript, all by itself (almost)
That’s all very well and good, but it’s not actually much room for our Javascript. No worries, as we can actually use a whole different file to hold it. This is normally a good idea if you’re doing anything more complicated than a single event, as it makes it much easier to read your code.

When you include a Javascript file in your HTML page, your browser reads it in and immediately starts to follow any instructions you’ve left lying around in it. This is normally pretty useful.

In main.js, we’re going to write:

console.log('ay carumba');

Now, re-load the page! The browser read the line, and then ran it.

a very brief look at functions
Functions are one of the building blocks of all kinds of programming languages, and essentially they’re a neat way of storing some code that we want to use and saving it for later. Some functions, like console.log() are just built into browsers. We can run them anytime, and the job they do is always the same.

Some we’re allowed to write ourselves.

in the HTML:

<!DOCTYPE html>
<html>
<head>
	<script type="text/javascript" src=main.js></script>
</head>
<body>

<h1>wow, clicking button?</h1>

<button type="button" onclick="printWord()">
	im gonna click it
</button>

</body>
</html>

In main.js:

function printWord () {
	console.log('heeeeyyyyy');
}

We have the same thing we were doing before, logging to the console, but now we’ve wrapped it up in something called a function. Our browser doesn’t really mind where we put things, so long as the HTML knows about them – and we’ve included the file in our script tag, so the browser has read the file already, and knows all about printWord(), and what it’s supposed to do. So, when we tell it to perform the function, it just… goes and does it!

It’s important to note that things labelled function don’t run automatically when the page loads! They need to be ‘called’ somewhere. Here, we call printWord() when we click the button.

What advantage does this give us?? Aren’t we just doing the same thing, but way more complex? In short: yes! We are! But this added structure is going to help us a lot in a couple of minutes.

variables

What if we wanted to print more than one word? Naively, we could make 2 functions: one called printWord1() and another called printWord2(). But what if you wanted to print 10 different words? or a word you didn’t know yet? This is where variables come in.

in the HTML:

<!DOCTYPE html>
<html>
<head>
	<script type="text/javascript" src=main.js></script>
</head>
<body>

<h1>wow, clicking button?</h1>

<button type="button" onclick="printWord('heeeeyyyyy')">
	im gonna click it
</button>

<button type="button" onclick="printWord('hoooooooo')">
	im gonna click it
</button>

</body>
</html>

In main.js:

function printWord (word) {
	console.log(word);
}

What we’ve done in the example above is to create something called a ‘variable’. We have this word we want to print out (‘heeeeyyyyy’), and we can send it to the Javascript to print it. But we need to tell the Javascript what it’s going to print each time.

The thing in brackets at the top of the function, (word) is a bit like an empty box called word. Whatever we put inside it, the code that comes after is gonna perform those actions on that thing. This is called abstraction: we have an abstract representation of something we want to do things to, a word, any word, and when we pass any word to that function, it’ll just… print it! Try adding a second button:

<button type="button" onclick="printWord('ay carumba')">
	im gonna click this one too
</button>

Incidentally, you notice how our variable does’t get surrounded by quotation marks? That’s on purpose. Javascript recognises things in quotation marks as bits of data called strings, and knows that they won’t change. ‘heyyy’ something called a string. word, on the other hand, is different. We’ll talk more about variables in the coming weeks.

talking to the DOM
We can’t expect visitors to our websites to open up the web console every time they want to see what’s going on on the page. (that said, a lot of websites put stuff in the console so people who know what’s up on the web can see secret messages. Examples include The Guardian, Harvard Business Review, and bits of jodi.org).

Instead, we need to talk to the DOM – the Document Object Model. We’ve been thinking about the DOM for a while now, when we wanted to select things using CSS. We use a similar idea when we write Javascript that changes things on webpages, though we write it a bit differently.

<!DOCTYPE html>
<html>
<body>

<h1 id="heading">wow, clicking button?</h1>

<button type="button" onclick="document.getElementById('heading').style.backgroundColor="lightblue">
	im gonna click it
</button>

</body>
</html>

Remember the ‘.’ from console.log? it comes in here too! Now we have this thing called document, with the method (a method is a built-in function) called ‘getElementById’. The ‘document’ here is the DOM, and the getElementById(‘heading’) does the same thing #heading does in CSS: it selects an element with a particular ID from the page.

That element in turn has a method called style (another .! .’s all day), which has a method called backgroundColor… you can see where this is going.

Oof though, that works, but it’s hard to read, long and ugly. Thank goodness for functions! Let’s change the colour of the body while we’re at it!

HTML:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="main.js"></script>
</head>
<body>

<h1 id="heading">wow, clicking button?</h1>

<button type="button" onclick="changeHeading()">
	im gonna click it
</button>

</body>
</html>

In main.js:

function changeHeading () {
	document.getElementById('heading').style.backgroundColor="lightblue"
}

Now we can do a lot of fun stuff:

function changeHeading () {
	document.getElementById('heading').innerHTML="i clicked the button"
}

Some things to note, before we go any further:

web console
Before we get into playing with some JS, I’ll show you a couple of nice things you can do with the console itself. An important concept to get early on (and one that will feature large in your next assignment) is that, just like CSS, you can keep adding Javascript on top of an existing webpage. Not only will the page still run, but you’re able to manipulate its contents.

  document.designMode=’on’
  document.body.style
  twitter screamer
  console api

in class assignment

Have a go at doing the following with the code we’ve just been using. Before moving onto the next step, make sure the code you have is working as expected.

  1. Try and change the heading to a different color.

  2. Try passing the name of the colour to the function as a variable.

  3. Make 2 buttons that each turn the page a different colour. Can you make them both work using the same function?

  4. Experiment with changing the text inside the heading.

  5. Add a new page element. Can you change the text of multiple page elements at once?

  6. Have a go at styling the page. You’re allowed to add new HTML, but you may only change the style of the page using Javascript! no CSS today!

Assignment

due: 02/27

Style a plain HTML webpage (that I will give you) using only Javascript. Think about how the page might change as different events occur.

Resources

  list of DOM Events   debugging Javascript with the console
  google console tools mozilla