Posts Tagged ‘event handling’

JS 101 Week 5: Event handling

February 26, 2011 Leave a comment



Why is it better to use either trickling or bubbling of events? Why not just give the event to the node on which it was invoked?

There are two main reasons to use the trickling down or bubbling up of events. The first is performance. If we have 100 different images on a page and we want each one to respond to the hover event, it is very inefficient to create 100 different event listeners and attach them to each element. We can instead create a single hover event listener on the <div> which contains all of these pictures, and from within that event handler, determine which of its enclosed <img> elements was clicked. Additionally, when the event bubbles up the parent chain, the programmer is free to do interesting things like change the style of entire subtrees as a result of an event listener lower down in the hierarchy.

Can you think of one situation where you would want to prevent the browser from submitting a form after a user has clicked on the ‘submit’ button? How would you achieve this?

One example would be if we had some client side validation we wanted to take place before submitting a form to the server. For instance, we might want to validate that all the form fields are filled out, or that the values entered into these fields have a certain format (e.g. mm/dd/yyyy format for dates). When the form submit button is clicked and the validation routine takes place, if there is an error that function can call the preventDefault method on the corresponding event object.


12.1 of Eloquent Javascript

Write a function asHTML which, when given a DOM node, produces a string representing the HTML text for that node and its children. You may ignore attributes, just show nodes as . The escapeHTML function from chapter 10 is available to properly escape the content of text nodes.

Hint: Recursion!

function isTextNode(node) {
  return node.nodeType == 3;

function asHTML(node) {
  // we’re done recursing
  if (node.childNodes.length === 0) {
    if (isTextNode(node)) {
      return node.nodeValue;
      // This is unavailable in the jsFiddle environment 
      //return escapeHTML(node.nodeValue);
    else {
      return "<" + node.nodeName + ">";
  var returnString = "<" + node.nodeName + ">";
  for (var i = 0; i < node.childNodes.length; i++) {
    returnString += asHTML(node.childNodes[i]) + "\n";
  return returnString;


JSFiddle example

12.2 of Eloquent Javascript

Write the convenient function removeElement which removes the DOM node it is given as an argument from its parent node.

function removeElement(node) {

See an example

13.1 of Eloquent Javascript

Write a function called registerEventHandler to wrap the incompatibilities of these two models. It takes three arguments: first a DOM node that the handler should be attached to, then the name of the event type, such as “click” or “keypress”, and finally the handler function.

To determine which method should be called, look for the methods themselves ― if the DOM node has a method called attachEvent, you may assume that this is the correct method. Note that this is much preferable to directly checking whether the browser is Internet Explorer. If a new browser arrives which uses Internet Explorer’s model, or Internet Explorer suddenly switches to the standard model, the code will still work. Both are rather unlikely, of course, but doing something in a smart way never hurts.

// eventname is the name of the event without the ‘on’ prefix.  e.g.
// to register for a click event, the eventname value should be "click"
function registerEventHandler(node, eventname, handler) {
    // node has an attachEvent method; use that.  This is how ie works
    if (node.attachEvent) {
        node.attachEvent("on" + eventname, handler);
    // Mozilla model
    else if (node.addEventListener) {
        // false - use bubble up rather than trickle down
        node.addEventListener(eventname, handler, false);
    else {
        node["on" + eventname] = handler;

JSFiddle example – when mouse enters element, it becomes bold. After it leaves, it becomes normal

Create an HTML page and some Javascript to allow a user to add n numbers.

First display a simple form with the question “How many numbers do you want to add (max is 10)”. The user should enter a number between 2 to 10 and click on a button in the form. You have to validate the answer. If the user has entered a correct value (between 2 and 10), then dynamically create a form with n text input fields and an “Add” button. Once the form is displayed the user will enter n numbers in the n input fields and when they click on the “Add” button, dynamically create a span element with the result. You will have to perform validation on the values entered in the input fields to make sure that they are numbers. If they are not numbers, display an alert dialogue with an error message.

JSFiddle solution