How to detect mousemove event over iframe element

Problem

Try dragging the box with faster mouse movements. Whenever pointer gets into the iframe element with red background dragging stops.

Cause

This behavior is caused by how events are handled in iframe. According to the specification event bubbling is allowed only within a single document.

This upward propagation will continue up to and including the Document.
Document Object Model Events: Event bubbling

Since iframe represents a separate document therefore all events including mousemove event will terminate at the root of the iframe document and will not travel across the boundary into the host document.

Solution

At first I thought that the solution would be to pass all mousemove events from iframe to parent window.

However after finding this answer on StackOverflow, the solution turned out to be much easier.

You need to disable mouse events including mousemove event for iframe by setting pointer-events CSS property to none when dragging starts and restore it to auto when dragging stops.

For example:


$('#draggable').draggable({
   start: function(){
      // Temporarily disable mouse events for IFRAME for smooth dragging
      $('#draggable iframe').css('pointer-events', 'none');
   },
   stop: function(){
      // Re-enable mouse events for IFRAME
      $('#draggable iframe').css('pointer-events', 'auto');
   }      
});

You can also create a class with pointer-events: none and add/remove that class instead of manipulating CSS properties in the code.

It is worth noting that pointer-events CSS property is not supported in IE 10 or lower, see this page for more information.

See example below for code and demonstration.

You May Also Like

Comments

  1. Wow!! This just saved me a lot of time. Been working on getting this to work since last week. Thank you very much 

Leave a Reply to Ayomide Cancel reply

(optional)

This site uses Akismet to reduce spam. Learn how your comment data is processed.