BETAThis is a new service – your feedback will help us to improve it.

Responding to user actions

We now know how to change how a page looks and works by adding and removing classes.

Now, let's look at how to make this happen in response to a user's actions.

Javascript allows us to set event listeners. We "listen" for particular events on a webpage, such as a user clicking a button, hovering over a menu, or scrolling down the page, or even waiting for the webpage to finish loading.

We can run whatever code we want once the event happens.

Delete everything from the previous lesson in the JS panel, and follow with the code examples given here. Keep the HTML and CSS.

Create an event listener

Continuing with our previous example, we want the <h1> text to turn red when the user clicks it.

First, let's select the HTML and save it as a variable.

const heading = document.querySelector("h1")

Next, we can attach an event listener to that HTML, which will fire on a 'click' event.

heading.addEventListener('click', function(){
	console.log("Heading has been clicked!")
})

You should now find that if you click the heading, the message should be logged to the console.

We can put whatever code we like inside the curly brackets.

heading.addEventListener('click', function(){
	heading.classList.add('red-text')
})

If we replace the console.log() with the line adding the CSS class, the text should turn red when clicked.

Other event listeners

We can create event listeners for any of the dozens of events browsers support. Another popular one is the "hover" event, which triggers when a user's cursor hovers over something.

Any of these events can be attached to any HTML element on our page.

Next, we'll apply this knowledge to a real webpage.

Lessons last updated 12th July 2019. You can improve this lesson on Github.
Part of Adding interactivity
  1. Introducing Javascript
  2. Your first Javascript program
  3. Variables
  4. Conditional logic
  5. Affecting the page
  6. Making a menu
  7. Responding to user actions
  8. Keep your Javascript accessible
  9. Get confident with Javascript
  10. Add interactivity to your prototypesP