JavaScript Listeners

JavaScript

JavaScript is normally run on your page in one of three ways. First, if the script is written directly in a <script> HTML element or an attached JavaScript file, then it will run when it is loaded. So, the following script would run when a page is opened or refreshed:

alert("The page was reloaded.");

The second way is for a function to be called. So, let's say that we include the following script at the top of a page:

function CreateMyOwnPopup(){
  alert("Here's my popup.");
}

This script will register the CreateMyOwnPopup function, but the page won't actually do anything until something calls the function, such as if we included the following later in the page:

CreateMyOwnPopup();

And the third way that JavaScript is typically run on a webpage is in conjunction with a listener. Listeners are registered when the page is loaded, and then they run the script inside them when they hear the listener being activated. For instance, the following script would find a button with the id button1 and run the CreateMyOwnPopup function any time the button is clicked:

document.getElementById('button1').addEventListener('click', function() {
  CreateMyOwnPopup();
});

In this case, JavaScript registers a listener on the button1 element to do something every time the click event occurs (i.e., someone clicks on it). See below for this example in action:

Additionally, jQuery has a shorter way of adding the same shortcut as follows:

$('#button1').on('click', function() {
  CreateMyOwnPopup();
}

JavaScript can listen for many different types of events, and available events can vary based on the element you are listening to, but some common examples include click, change, keyup, keydown, and scroll.

This content is provided to you freely by EdTech Books.

Access it online or download it at https://edtechbooks.org/elearning_hacker/javascript_listeners.