Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Hammer.js does not seem to work with Zepto

I am trying to use jQuery.Hammer.js with Zepto v1.1.3. But for some reason I am getting this error:

Uncaught TypeError: undefined is not a function

Here is part of my code:

var element = $('#wrapper'); //document.getElementById('main');
console.log(element);
element.hammer({prevent_default: false, stop_browser_behavior: false}).on("dragleft"...

The console.log(element) is giving me:

[div#wrapper.hfeed, selector: "#wrapper", forEach: function, reduce: function, push: function, sort: function…]

What could be causing this?

like image 711
jnbdz Avatar asked Jan 25 '26 01:01

jnbdz


1 Answers

As you can see in the official documentation, the syntax is a bit different:

var hammertime = new Hammer(myElement, myOptions);
    hammertime.on('pan', function(ev) {
    console.log(ev);
});

To use it thew way you do, i.e. element.hammer... you need the jQuery plugin for Hammer.js

Is that all? Not really, if you check the source of this plugin, you see these two lines:

Line 9: jQuery(this.element).triggerHandler({

Line 25: })(jQuery, Hammer, "hammer");

The problem is that Zepto does not recognize jQuery. You could rename the occurences by Zepto but a better solution is the one defined by gondo:

jQuery = Zepto;
$.fn.extend = function(obj) {
    $.extend($.fn, obj);
};

Your code would then become:

<script src="/path/to/zepto.js"></script>
<script src="/path/to/hammer.js"></script>
<script>
    // We load this code _before_ jquery.hammer.js
    jQuery = Zepto; // We just need this one line
</script>
<script src="/path/to/jquery.hammer.js"></script>
<script>
    var element = $('#wrapper');
    element.hammer({prevent_default: false, stop_browser_behavior: false}).on("dragleft", function(e)...
</script>
like image 192
Andreas Schwarz Avatar answered Jan 26 '26 14:01

Andreas Schwarz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!