16

I am getting the Error: Uncaught TypeError: Object [object Object] has no method 'addEventListener' hammer.js:168

my code is like this:

<script type="text/javascript" src="js/hammer.js"></script>

On device ready function:

 var resim = $('#kaydir');

 Hammer(resim).on('swipeleft', function(ev){
     console.log('left: ', ev);
 });

It seems the error is in hammer.js . What should I do?

hdayi
  • 423
  • 2
  • 4
  • 13

2 Answers2

32

I imagine your issue is that you don't have Hammer.js's jQuery Plugin installed (GitHub).

Because of this, you cannot pass a jQuery object into the Hammer() function, your two options:

With the jQuery Plugin

Add the jQuery Plugin I've linked to above to your project, then call:

$('#kaydir').Hammer(...)

Without the jQuery Plugin

Pass only the element into Hammer() and not the jQuery object, by using [0]:

Hammer(resim[0]).on(...)

Or instead change your resim variable to hold the result of calling JavaScript's getElementById.

var resim = document.getElementById('kaydir');
Hammer(resim).on(...)
Community
  • 1
  • 1
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • I downvoted you for "Based on the information provided in the identical question you deleted yesterday..." What is the purpose of that? – Andre Bulatov Jun 11 '16 at 21:04
  • @Andre Bulatov this answer was based on information provided in the previous question. Without it, this answer would be nothing more than speculation. – James Donnelly Jun 12 '16 at 05:40
  • Hammer(resim[0]).on(...) its working great but what to do when I need to apply on all elements in resim?? – Madan Bhandari Jun 29 '16 at 10:27
  • @maddy use a loop. `for (var i = 0; i < resim.length; i++) { Hammer(resim[i]]).on(...) }` – James Donnelly Jun 29 '16 at 10:29
  • @JamesDonnelly But I am getting another problem http://stackoverflow.com/questions/38101901/jquery-functions-not-working-with-hammer-js – Madan Bhandari Jun 29 '16 at 14:00
  • @JamesDonnelly When using jQuery Plugin you should use the lower case ".hammer" ("$(...).hammer(...)" instead of "$(...).Hammer(...)") because it leads to error "$(...).Hammer is not a function" in Google Chrome otherwise. – ltlBeBoy Jun 29 '17 at 17:35
  • 1
    Passing a jQuery object to Hammer() doesn't work regardless of hammer's jQuery plugin pulled or not. But passing only element as in answer eg. `a=new Hammer($('.test')[0])` worked fine. – Maciek Rek Jun 30 '17 at 19:46
2

If you are using jQuery, you should use the jQuery Hammer version and use it like that:

var resim = $("#kaydir");
resim.hammer().on("swipeleft", function(ev) {
    console.log('left: ', ev);
});
flks
  • 610
  • 10
  • 28