0

I would like to simulate a mouse move event. The setup is as follows

I have this element

<div class="target"></div>

Which in this test setup follows the mouse: DEMO

I have already a working simulation of the mousedown event (click the button). The code that generated this event looks like this:

function triggerMouseEvent (node, eventType) {
    var clickEvent = document.createEvent ('MouseEvents');
    clickEvent.initEvent (eventType, true, true);
    node.dispatchEvent (clickEvent);
}

source

But how do I create a fake movemove event? Because I also need to provide a pageX and pageY for it. How do I provide this information when I create an event as shown above?

Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333
  • You cannot create a `mousemove` event that will move the mouse. It is read only. Can you describe in more detail what your eventual goal is? There might be another way to achieve it. – Todd Chaffee Apr 27 '19 at 21:34
  • I don't want to move the mouse, I just want to create a mousemove event and dispatch it, such that the callback is executed – Jeanluca Scaljeri Apr 28 '19 at 07:36

1 Answers1

0

I've updated your example code to show how to create a mousemove event. Note that your code uses the deprecated document​.create​Event(), and you should consider replacing that with the newer MouseEvent, which I used in the part of the code I added.

const target = document.querySelector('.target');

document.querySelector('main')
  .addEventListener('mousemove', (e) => {
    if (e.clientY > 60) {
      target.style.top = (e.clientY - 25) + 'px';
    }
      target.style.left = (e.clientX - 25) + 'px'; 
  });

target.addEventListener('mousedown', () => {
   console.log('mouse down');
})

const butt = document.querySelector('.sim-move');
butt.addEventListener('click', () => {

 let evt = new MouseEvent("mousemove", {
    clientX: 150,
    clientY: 5,
    bubbles: true,
    cancelable: true,
    view: window
  });
  
  let canceled = !target.dispatchEvent(evt);  

});

const butt1 = document.querySelector('.sim-down');
butt1.addEventListener('click', () => {
    triggerMouseEvent(target, 'mousedown');
});
function triggerMouseEvent (node, eventType) {
    var clickEvent = document.createEvent ('MouseEvents');
    clickEvent.initEvent (eventType, true, true);
    node.dispatchEvent (clickEvent);
}
html, body, main {
  height: 100%;
  padding: 0;
  margin: 0;
}

body {
  margin: 20px;
  }

main {
  display: block;
  border: 1px solid #000;
  height: calc(100% - 42px);
}

div {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 50px;
  height: 50px;
  background-color: green;
}
<button class="sim-move">Simulate mousemove</button>
<button class="sim-down">Simulate mousedown</button>
<main>
  <div class='target'></div>
</main>
Todd Chaffee
  • 6,754
  • 32
  • 41