<p id=”text”>
<button onclick=”showName()”>My name is?</button>
<script>
function showName() {
document.getElementById(‘text’).innerHTML=‘Paul’
}
</script>
This extracts the code out into its own function, which makes the code far more maintainable and easier to read. This is the preferred method of assigning actions to events.
As we established earlier, there are many different events that JavaScript can react to. The full list of events we can watch out for are as follows:
- Onchange. Event is triggered when an HTML element has been changed in some way, such as when a user has input some information into a web form.
- Onclick. Event is triggered when an HTML element is clicked. This can be any element, such as a div, a table, an image, etc.
- Onmouseover. Event is triggered when a user hovers their mouse over an HTML element; once again, this can be on any element.
- Onmouseout. Event is triggered when a user stops hovering over the HTML element. Again, this can run on any element and is usually paired with the onmouseover event.
- Onkeydown. Event is triggered when a user presses a key on their keyboard. This is a good event to watch for on forms.
- Onload. Event is triggered when the webpage has finished loading. This is good for when we want to wait for all of the images, etc, to finish generating their size on page load, so that we can perform operations based on their size attributes.
We can make use of any of these events by simply adding the event text to the responsible HTML element like we did before. Let’s see a few examples of this in action.