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.

Recommended For You

Books

Online Courses

You Might Also Like

Leave a Reply

You may use simple HTML to add links or lists to your comment. Also use <pre><code class="language-*">...</code></pre> to mark up code snippets. We support language-js, language-markup and language-css for comments.
(Optional)