Learn

You can add interactivity to DOM elements by assigning a function to run based on an event. Events can include anything from a click to a user mousing over an element. We will learn more about events in the upcoming DOM Events with JavaScript lesson. For now, let’s take a look at how to modify an element when a click event happens.

The .onclick property allows you to assign a function to run on when a click event happens on an element:

let element = document.querySelector('button'); element.onclick = function() { element.style.backgroundColor = 'blue' };

You can also assign the .onclick property to a function by name:

let element = document.querySelector('button'); function turnBlue() { element.style.backgroundColor = 'blue'; } element.onclick = turnBlue;

In the above example code, when the <button> element detects a click event, the backgroundColor will change to 'blue'.

Instructions

1.

Inside the turnButtonRed() function, add the code to modify the button stored in the element variable as follows:

  1. Assign the .style.backgroundColor to 'red'
  2. Assign the .style.color to 'white'
  3. Modify the .innerHTML to 'Red Button'
2.

Below our turnButtonRed() function definition, trigger the turnButtonRed() function when the element detects a click event.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?