06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8<br />

Working with browser events<br />

When are you developing for browsers, you will have to deal with user interactions<br />

and events associated to them, for example, text typed in the textbox, scrolling of the<br />

page, mouse button press, and others. When the user does something on the page,<br />

an event takes place. Some events are not triggered by user interaction, for example,<br />

load event does not require a user input.<br />

When you are dealing with mouse or keyboard events in the browser, you can't<br />

predict when and in which order these events will occur. You will have to constantly<br />

look for a key press or mouse move to happen. It's like running an endless<br />

background loop listening to some key or mouse event to happen. In traditional<br />

programming, this was known as polling. There were many variations of these<br />

where the waiting thread used to be optimized using queues; however, polling is still<br />

not a great idea in general.<br />

Browsers provide a much better alternative to polling. Browsers provide you with<br />

programmatic means to react when an event occurs. These hooks are generally called<br />

listeners. You can register a listener that reacts to a particular event and executes an<br />

associated callback function when the event is triggered. Consider this example:<br />

<br />

addEventListener("click", function() {<br />

...<br />

});<br />

<br />

The addEventListener function registers its second argument as a callback function.<br />

This callback is executed when the event specified in the first argument is triggered.<br />

What we saw just now was a generic listener for the click event. Similarly, every<br />

DOM element has its own addEventListener method, which allows you to listen<br />

specifically on this element:<br />

Submit<br />

No handler here.<br />

<br />

var button = document.getElementById("#Bigbutton");<br />

button.addEventListener("click", function() {<br />

console.log("Button clicked.");<br />

});<br />

<br />

[ 193 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!