Search code examples
javascripttouch-event

Call touch event on parent from iframe


I'm trying to call a touch move event when a user interacts with an iframe.

This code is at the top level page which contains the iframe.

var myIframe = document.getElementById('iFrame');
var myIframeDoc = myIframe.contentWindow.document;
myIframeDoc.addEventListener('touchmove', function(event){

    console.log('iframe touched');

    var e = document.createEvent('TouchEvent');
    //e.touches = [{pageX: 10, pageY: 10}];
    //e.initTouchEvent('touchstart', true, true);
    e.initUIEvent('touchstart', true, true);

}, false);

So when the user touch moves on the iframe it will then call one of the events below (also at the top level page).

document.addEventListener("touchmove", function(event){

    alert('touchmove');

});

document.addEventListener("touchstart", function(event){

    alert('touchstart');

});

document.addEventListener("touchend", function(event){

    alert('touchend');

});

However the touch events don't fire on the parent layer... But the console log works fine, so it is picking up the iframe touchmove, but the TouchEvent part doesn't seem to be working.

In short, I need to be able to get the events to fire as though a user has touched the parent page when they interact with the iframe.


Solution

  • You are not dispatching the event. I also had to create it as a MouseEvent.

    document.addEventListener("touchstart", function (event) {
        alert('touchstart');
    });
    // Fix 1 (test in mobile, it may need to be feature detected)
    // Or not work reliably across browsers, some clients will need TouchEvent
    var e = document.createEvent('MouseEvent');
    e.initUIEvent('touchstart', true, true);
    //Fix 2
    document.dispatchEvent(e);