Tutorial: JavaScript Events Pg. 2

Now it's time to write some more instructions, and extend our code some more. Below is a general idea for a game or a picture gallery. Once you understand about events, you can tell a browser how to respond.

Step 1:

The html/css setup (see page 1)

Step 2:

Create and save a new text file as myJS.js in a js folder. Link the file to your html right before you close the body tag, like this:

javascript link

A word about JavaScript events. Events occur all the time in your web page, when someone clicks, when the page loads, when the window is resized, etc. A good resources can be found at this page: http://www.javascriptkit.com/jsref/events.shtml. You can use these events to let the browser know when an event occurs, to capture that event to use, a process called event registration.

Event Propagation lets you register and propagate events using the DOM, during the capturing and bubbling phases, to cancel and respond, prevent default actions, right+clicks, context menus, and more. The developers' forum Stack Overflow has many good discussions of what you can do and how you can apply.

Remembering that JavaScript is called sequentially by the browser, and that browsers can read your DOM that has elements within elements (like a li within an ul that both have a handle for an event), it is this process that is called event propagation. It means that each browser determines whether to react from the outermost element (ul) to the innermost(li), which is called capturing or trickle down, or from the innermost element captured, then bubble up (propagate) to the outer elements.

It's important to know this because when you begin to have the browser create or remove elements in your DOM, you have to recognize some browsers will bubble up and others will trickle down. When calling the addEventListener() the last property is to make this propagation false.

Bubble up, trickle down.

Though it does essentially the same thing, by using this method, I can check for multiple events within a single call. This is called event propagation, and it has another advantage, allowing events to be triggered by non-dom elements by writing your own. Note: older browsers, particularly IE8 and below, supports an alternative method, attach event, that you will have to account for if coding for older browsers.

code IE8 attach event

Step 3:

Now you can write scripts that interact on events that you write, by the many different ways you can access DOM nodes. We will see how placing the addEventListener on a single event handler for a group of tags, like the ul in the above image li's. Let's access the document and use query selector to begin. In your current css, we will add just a bit of code to change the cursor so when we rollover the element, it will change.

If you have not already done so from the earlier example, add cursor:pointer; to your ul li selector. Because there's not really a link there, though we are treating it as that way, so it's kind of a smoke-and-mirrors thing.

Query selectors are a very effective way to select and use HTML elements, and you write it similarly to some of the jQuery api's you may have used. We will access the document with the query selector, then use dot notation to get the class name (the descriptor), and add the event listener right after. We will ask the browser to listen for a click, and when that occurs, we will ask it to run some function, written in curly braces.

Type the following into your myJs.js file:
document.querySelector(".grid").addEventListener("click", function(e) { });

Above, we added a function literal, an anonymous function or function with no name, and passed it the event variable, the (e) you see within the parenthesis of the function. Between the curly braces, you will put whatever you want returned when the element is clicked.

Step 4:

In programming, it is always easier if you test each step as you write your code. Let's test our event listener on our query selector and see how it works through our console.

Write document.querySelector(".grid").addEventListener("click", function(e) { console.log(e); }); then go to your browser and open the console. Click on a color and see the results. You should see that a mouse event has occurred and if you open up the results, you can see you get a lot of information back from that click.

screenshot console log

Step 5

After testing, we can get rid of the console.log and add the action we want to occur onClick.

First, we will need to remembe that html often contains elements within elements, and that just about anything can be made clickable or accessible. If I want to remove the image elements as my set up suggests, I will want to also remove the surrounding li so as not to leave an empty element in our code. We can use the event propagation to bubble up to the parent container of the image element, so add false to the end of the statement and write your action to occur within the brackets.

document.querySelector(".grid").addEventListener("click", function(e) {
	var removeTarget = e.target.parentNode);
  }, false);

Then we will remove the child of that parent node - the image element

document.querySelector(".grid").addEventListener("click", function(e) {
	var removeTarget = e.target.parentNode;
  // removeTarget removes the ul, parentNode removes the li, and removeChild removes the image   
  }, false);

Final Thoughts: The Beauty of HTML5

Though this is a tutorial on JavaScript, new semantic html added to the markup language has greatly extended interactions that can occur on the most basic level. Checkout HTML5 Rocks for HTML5 Events

1 | 2