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
Inside the turnButtonRed()
function, add the code to modify the button stored in the element
variable as follows:
- Assign the
.style.backgroundColor
to'red'
- Assign the
.style.color
to'white'
- Modify the
.innerHTML
to'Red Button'
Below our turnButtonRed()
function definition, trigger the turnButtonRed()
function when the element
detects a click event.