4

Below I grab the container and on swipe left and right I trigger a click which is another function to do some fancy animation jazz.

var element = document.getElementsByClassName('container');
var hammertime = new Hammer(element);
hammertime.on('swiperight', function(ev) {
  $('.btn-left').trigger('click');
});
hammertime.on('swipeleft', function(ev) {
  $('.btn-right').trigger('click');
});

I keep getting this error about my Hammerjs library i've included (http://hammerjs.github.io/dist/hammer.min.js) Uncaught TypeError: a.addEventListener is not a function.

I did some research and found another stackoverflow question that says I can't pass jQuery through Hammerjs thus I should use jQuery Hammer. I took a look at the repo and it's not been updated in nearly two years.

Do I need to use the jQuery Hammer (https://github.com/hammerjs/jquery.hammer.js) extension, or can I pass through jQuery without needing it.

1 Answer 1

5

The problem is that new Hammer() is expecting a single element, and getElementsByClassName is returning a NodeList.

If you change it to

var hammertime = new Hammer(element[0])

that should work as expected, since you'll be passing the first element that matches .container. If you want to bind it to all elements that have the .container class, you'll need to loop through them on your own. I rarely use jQuery for anything, so I usually include this little helper function for looping through NodeLists

function doToAll(elems, fn){
  var len = elems.length
  while(--len > -1){
    fn(elems[len])
  }
}

In this case, you'd use it like this:

doToAll(document.getElementsByClassName('container'), function(element){
  var hammertime = new Hammer(element)
  //add in the rest of your functionality
})
1
  • Alternatively, if you only ever expect a single .container, you could grab it with document.querySelector('.container').
    – ajm
    Commented Mar 4, 2016 at 16:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.