JSFiddle - React, Tailwind, and code Playground

by keshann

HTML

<iframe id="iframe"></iframe>
<div id="message"></div>

JavaScript

(function(mouseStopDelay) {
  var timeout;
  document.addEventListener('mousemove', function(e) {
    clearTimeout(timeout);
    timeout = setTimeout(function() {
      var event = new CustomEvent("mousestop", {
        detail: {
          clientX: e.clientX,
          clientY: e.clientY
        },
        bubbles: true,
        cancelable: true
      });
      e.target.dispatchEvent(event);
    }, mouseStopDelay);
  });
}(1000));

// Example use
document.getElementById('iframe').addEventListener('mousestop', function(e) {
  console.log('Mouse coordinates are: ', e.detail.clientX, e.detail.clientY);
  document.getElementById("message").innerHTML = 'Mouse coordinates are: ' + e.detail.clientX + ' ' + e.detail.clientY;
  // The event will bubble up to parent elements.
});

// This example assumes execution from the parent of the the iframe

function 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...