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.
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.
Part of Adding interactivity
- Introducing Javascript
- Your first Javascript program
- Variables
- Conditional logic
- Affecting the page
- Making a menu
- Responding to user actions
- Keep your Javascript accessible
- Get confident with Javascript
- Add interactivity to your prototypesP