MDN Web Docs describes events as “actions or occurrences that happen in the system you are programming, which the system tells you about so your code can react to them.” They are things that happen to HTML elements (such as button clicks or page loads), which JavaScript can react to. For example, if the user clicks a button on a webpage, one reaction to that action could be to display an information box. Events are often used in combination with functions, and the function is not executed before the event takes place (check out the functions page's practice section for an example of an event and a function working together).
Some common events in DOM manipulation include:
This example is a program that stores information about a user's favourite books, and allows the user to add a new book to the list. The HTML event onclick is defined in the button element and calls the addBook() JavaScript function. An event listener is also added to the button element, which calls the addToFavourites() function that appends the newly added book to the Favourites list in the HTML file.
HTML file: the onclick event is defined in the button element below, calling the addBook() function.
JS file: the addBook() function is called when the event is triggered (i.e. the button is clicked).
JS file: the event listener is added to the button element, which calls the addToFavourites() function when clicked.
JS file: the addToFavourites() function is called when the event listener is triggered.
Enter details of the book you want to add