Accepting User Input in a Web Browser
Javascript is an event-driven programming language, meaning that the flow of the program is determined by events. Some events are created by users, like keypress
and click
while others are emitted by the system like blur
, load
, and deviceorientation
.
Many events are handled by the system quietly behind the scenes to power your web browser. For instance, when the initial processing of HTML
code into the Document Object Model (DOM) is finished, it emits
a DOMContentLoaded event so that javascript can be configured to run only once the DOM elements
it depends on become available.
One of the most common behaviors of people online is clicking things. A lot of things. And not all of those things are links that take people to other pages on the web. Some of those clicks move fictional characters from one town to another, some save a blog draft, and others pay for products that will arrive in the mail just hours later.
All of this is done by creating a handler
and and adding it as an EventListener
to an element
. That isn't as daunting as it might sound. And don't worry, there are tons of articles on the topic if it is. No matter what libraries or framework you choose to use, under the hood this is what is happening, just maybe in an optimized manner.
Handler
A handler
is simply a function that receives an event and possibly does something with it, thereby "handling it".
Let's look at a very simple handler.
var clickHandler = function (event) {
console.log("Found an event:", event);
}
First we declare a variable called clickHandler
, then we create a function that takes a single parameter, event
, which is an object that represents the event being handled. The function simple calls console.log
in order to print a message and the event to the debugging console.
Note: Browser debugging tools is a large subject. Check out http://devtoolsecrets.com/ to learn more.
Element
An element
is more or less an HTML
tag's javascript representation. More precisely, it represents an object of the document
. You access them using methods of the document like querySelector and querySelectorAll.
Given HTML of <h1 id="header">Hello!</h1>
, an element
can be found like this:
var element = document.querySelector('#header');
Here we have declared a variable called element
and assigned it the element returned by calling the querySelector
method of the document
object. In particularly we have "selected" the element with id=header
in the HTML
using the selector #header
. Selectors give a powerful way to select elements to manipulate or listen to for events.
Note: element
objects all have a method on them called addEventListener
in Chrome and Firefox. It is by calling addEventListener
on an element
that we bind
a handler
to an element
for specific kinds of event
s.
Adding the Event Listener
Now that we have selected our element
and defined a handler
and know about document.querySelector
we can put it all together to handle the events created when a user clicks the header.
var element = document.querySelector('#header');
var clickHandler = function (event) {
alert("You clicked the header!");
};
element.addEventListener('click', clickHandler);
The new line is
element.addEventListener('click', clickHandler);
Here we call element.addEventListener
with two parameters. The first is a string that indicated which types of events to listen for and the second is an event handler
. What will happen as a result is the function clickHandler
will be called any time the element
matching the selector
#header
is clicked.
What now?!?!?
Now you can deal with users clicking on parts of your website. Experiment with doing different things.
Calling alert
, prompt
, and confirm
all add new ways to interact with users by providing them with information, requesting information, or confirming an action.
You can call other functions
from within the handler in order to run calculations or notify other parts of your program that an event has occured.
There are a boat load of events that you can replace 'click'
with in the example above to create other scenarios. Moving a character with arrow keys, saving with ctrl+s
, and placing an order can all be done with a keypress
event.
Stay Tuned to learn about modifying the DOM in response to user input