Basic JavaScript Syntax

Events

What are Events?

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:

  • onchange - some HTML element has been modified
  • onclick - an HTML element has been clicked on
  • onmouseover - an HTML element was hovered over
  • onmouseout - mouse cursor moves off HTML element
  • onkeydown - a keyboard button is pressed
  • onload - the HTML page has finished loading




Practice what you've learned!

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.

HTML code example of an onclick event that calls a JS function.
Image source: N.Dobbin (for HyperionDev Course IFS L1T18: Programming in JavaScript III_JSON, 2022)

JS file: the addBook() function is called when the event is triggered (i.e. the button is clicked).

JavaScript code example of an event onclick function.
Image source: N.Dobbin (for HyperionDev Course IFS L1T18: Programming in JavaScript III_JSON, 2022)

JS file: the event listener is added to the button element, which calls the addToFavourites() function when clicked.

JavaScript code example of an event listener.
Image source: N.Dobbin (for HyperionDev Course IFS L1T18: Programming in JavaScript III_JSON, 2022)

JS file: the addToFavourites() function is called when the event listener is triggered.

JavaScript code example of a function to add HTML inner content.
Image source: N.Dobbin (for HyperionDev Course IFS L1T18: Programming in JavaScript III_JSON, 2022)
Try adding some new book entries to the list.
To see what's going on behind the scenes, right-click anywhere on the page and click inspect.

Enter details of the book you want to add



My Favourite Books