Skip to content

Instantly share code, notes, and snippets.

@connor
Created March 29, 2012 00:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save connor/2231977 to your computer and use it in GitHub Desktop.
Save connor/2231977 to your computer and use it in GitHub Desktop.
learning jQuery issue #79 progress

Introduction to Events

Events are at the heart of most pages utilizing JavaScript. For our JavaScript to perform an action, we must wait for a specific event to happen, and then execute the predefined action.

What an event is

While it was hinted at earlier, events are things that happen on the page. The majority of events utilized in JavaScript applications are user-driven, like: clicking a button, hovering over an element, and pressing a key. However, there are many other events that the browser fires, like: loading all of the resources on a page or going offline. MDN has a good reference of available DOM events.

Performing an action when an event happens

Now that we have a basic understanding of what DOM events are, we can perform an action when an event occurs.

There are two general ways that we can perform an action when an event occurs: inline event handlers and event listeners.

Inline Event Handlers

An example of using an inline event handler is like so:

<button id="myButton" onclick="alert('This is bad');">Click Me!</button>

As you probably guessed from reading what was within the alert - using inline event handlers is a bad practice that we don't recommend.

Instead, it's best to separate your markup from your logic by using event listeners.

Event Listeners

An example of using an event listener is like so:

<button id="myButton">Click Me!</button>
var element = document.getElementById('myButton');
element.addEventListener('click', function() {
  alert("This is good!");
}, false)

Like mentioned in the previous section, using event listeners have several advantages, such as: separating the markup (HTML) from the behavior (JavaScript) and not duplicating code. This is what people mean by using Unobtrusive JavaScript: it stays separate from your markup and doesn't repeat itself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment