Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iframe conflicting with hammer.js gestures

I'm using hammer.js [the jQuery plugin version] to provide simple touch gestures – in this case, I'm just using swipeleft and swiperight – to navigate between pages. All works good, except...

On some pages I have an <iframe> to display a Youtube video. When the gesture begins within the <iframe>, the javascript to load the next page doesn't run, as the context is the <iframe>, not the rest of the page. If the gesture begins anywhere else on the page [even if it ends in the <iframe>] the next page loads properly.

What I want to have happen is for the gesture to be recognized anywhere in the window, and not be affected by the iframe.

I've done a fair amount of googling, but I've yet to come up with a working solution.

Here is my Hammer JS code:

var hammertime = Hammer('html').on("swipeleft", function(event) {
  document.location = "http://www.example.com/";
});

And, here is the standard YouTube <iframe> code:

<iframe width="100%" src="http://www.youtube.com/embed/Gh5XWWXHVQk?rel=0" frameborder="0" allowfullscreen></iframe>

I'm also a bit of a JS newbie.

Any help that you can give would be greatly appreciated.

Ryan

like image 812
RyanS Avatar asked Jun 25 '13 21:06

RyanS


1 Answers

I had a similar requirement, and what I did was attach my swipe events to the iframes <body> like this:

// Get <iFrame>
var iframe = document.getElementById('iframeElement');

iframe.onload = function () {
    // Once content is available, get body
    var iframeBody = iframe.contentWindow.document.body;

    // Register gestures as normal
    Hammer(iframeBody).on("swipeleft", function (event) {
        // Dosomething
        SwipeLeft();
    });
}

The onload ensures that the document has finished loading and the element you want is available for binding.

Now swiping left anywhere in the iframe will trigger SwipeLeft(), you could couple this with bindings on the main document to achieve a 'full screen' swipe.

like image 54
JDandChips Avatar answered Oct 17 '22 12:10

JDandChips