jerkovicl
10/7/2014 - 9:13 AM

Click listener - for loop

Click listener - for loop

//examples

document.querySelector('.button')
.addEventListener('click', function(e) {
   //your code here
}, false);



function handlerWrapper(i) {
   return function() {
      console.log('You clicked element #' + i);
   }
}
 
var nodes = document.getElementsByTagName('button');
for (var i = 0; i < nodes.length; i++) {
   nodes[i].addEventListener('click', handlerWrapper(i));
}

//or using IIFE

var nodes = document.getElementsByTagName('button');
for (var i = 0; i < nodes.length; i++) {
   nodes[i].addEventListener('click', (function(i) {
      return function() {
         console.log('You clicked element #' + i);
      }
   })(i));
}

//using delegated events

/*
more complicated DOM that included icons and items that were supposed to be non-clickable
*/

/*
<ul class="toolbar">
  <li><button class="btn"><i class="fa fa-pencil"></i> Pencil</button></li>
  <li><button class="btn"><i class="fa fa-paint-brush"></i> Pen</button></li>
  <li class="separator"></li>
  <li><button class="btn"><i class="fa fa-eraser"></i> Eraser</button></li>
</ul>
*/

//a way to filter our events so we only react to elements we care about,
//or if our target element is contained by an element we care about.

/*
it walks though each element and their parents to see if it matches a criteria function. 
If it does, then it adds a property to the event object called delegateTarget, 
which is the element that matched our filtering criteria. And then invokes the listener. 
If nothing matches, the no handlers are fired.
*/
var delegate = function(criteria, listener) {
  return function(e) {
    var el = e.target;
    do {
      if (!criteria(el)) continue;
      e.delegateTarget = el;
      listener.apply(this, arguments);
      return;
    } while( (el = el.parentNode) );
  };
};

var toolbar = document.querySelector(".toolbar");
var buttonsFilter = function(elem) { return elem.classList && elem.classList.contains("btn"); };
var buttonHandler = function(e) {
  var button = e.delegateTarget;
  if(!button.classList.contains("active"))
    button.classList.add("active");
  else
    button.classList.remove("active");
};
toolbar.addEventListener("click", delegate(buttonsFilter, buttonHandler));

//helper functions:

var criteria = {
  isElement: function(e) { return e instanceof HTMLElement; },
  hasClass: function(cls) {
    return function(e) {
      return criteria.isElement(e) && e.classList.contains(cls);
    }
  }
  // More criteria matchers
};

var partialDelgate = function(criteria) {
  return function(handler) { 
    return delgate(criteria, handler);
  }
};