Search code examples
javascriptbackbone.jshammer.js

Hammer.js: Swipe event not working on images


I'm using hammer.js for gesture functionality on my web application. I have used it to swipe a video element and it works perfect as expected. However, when I apply the following code to an image element it's not working.

App.Views.Photo = Backbone.View.extend({
template  : template('photoTemplate'),
className : 'photo',
parent    : null,

events: {
    'swipe' : 'swiped',
    // 'pan'    : 'dragged'
},

...

swiped: function(e) {

    this.remove();
    this.parent.newContent(this.model);
},

This exact same code is working for the video elements but not for the images. I also tried doing e.gesture.preventDefault(); inside the swiped function but that didn't work either. I'm testing the application on firefox at the moment.

Any help will be appreciated.

Thanks

[EDIT]: I'm initializing the hammer code as follows

render: function() {

    $(this.el).attr('id', this.model.attributes._id);
    this.$el.html( this.template( this.model.toJSON() ) );

    this.$el.hammer();

    return this;
},

Solution

  • Ok, so after banging my head on this problem for weeks I finally got the answer.

    in the initialize function I placed the following code

    $('img').on('dragstart', function(event) { event.preventDefault(); });
    

    So it looks like this

    initialize: function(opts) {
        this.render();
        this.parent = opts.parent;
    
        $('img').on('dragstart', function(event) { event.preventDefault(); });
    },
    

    What this does is that it prevents the image from being dragged like default and that did the trick.

    And now on swipe the image gets removed like I wanted.

    [EDIT] If you have multiple images on the page add this to the event like

    this.$('img').on('dragstart', function(event) { event.preventDefault(); });
    

    This will apply to all of the picture that are rendered with that view.