Detect mousemove when over an iframe? Detect mousemove when over an iframe? javascript javascript

Detect mousemove when over an iframe?


If your target isn't Opera 9 or lower and IE 9 or lower you can use css attribute pointer-events: none.

I found it the best way just to ignore iframe. I add class with this attribute to iframe in onMouseDown event and remove in onMouseUp event.

Works perfect for me.


Iframes capture mouse events, but you can transfer the events to the parent scope if the cross-domain policy is satisfied. Here's how:

// This example assumes execution from the parent of the the iframefunction bubbleIframeMouseMove(iframe){    // Save any previous onmousemove handler    var existingOnMouseMove = iframe.contentWindow.onmousemove;    // Attach a new onmousemove listener    iframe.contentWindow.onmousemove = function(e){        // Fire any existing onmousemove listener         if(existingOnMouseMove) existingOnMouseMove(e);        // Create a new event for the this window        var evt = document.createEvent("MouseEvents");        // We'll need this to offset the mouse move appropriately        var boundingClientRect = iframe.getBoundingClientRect();        // Initialize the event, copying exiting event values        // for the most part        evt.initMouseEvent(             "mousemove",             true, // bubbles            false, // not cancelable             window,            e.detail,            e.screenX,            e.screenY,             e.clientX + boundingClientRect.left,             e.clientY + boundingClientRect.top,             e.ctrlKey,             e.altKey,            e.shiftKey,             e.metaKey,            e.button,             null // no related element        );        // Dispatch the mousemove event on the iframe element        iframe.dispatchEvent(evt);    };}// Get the iframe element we want to track mouse movements onvar myIframe = document.getElementById("myIframe");// Run it through the function to setup bubblingbubbleIframeMouseMove(myIframe);

You can now listen for mousemove on the iframe element or any of its parent elements -- the event will bubble up as you would expect.

This is compatible with modern browsers. If you need it to work with IE8 and below, you'll need to use the IE-specific replacements of createEvent, initMouseEvent, and dispatchEvent.


Another way to solve this that work well for me is to disable mouse move events on the iframe(s) with something like on the mouse down:

$('iframe').css('pointer-events', 'none');

and then, re-enable mouse move events on the iframe(s) on the mouse up:

$('iframe').css('pointer-events', 'auto');

I tried some of the other approaches above and they work, but this seems to be the simplest approach.

Credit to: https://www.gyrocode.com/articles/how-to-detect-mousemove-event-over-iframe-element/