7
<canvas id="MyCanvas" width="800" height="600"></canvas>

I want to simulate a click at some position (ex. x=200, y=150).

var MyCanvas = document.getElementById('MyCanvas');
MyCanvas.click(200, 150);

Above code does't work. The same with below slightly modified one:

var MyCanvas = document.getElementById('MyCanvas');
MyCanvas.click({pageX: 200, pageY: 150});

... and with below code copied from Simulate click at x/y coordinates using javascript.

function simulateClick(x, y) {
    var clickEvent = document.createEvent('MouseEvents');
    clickEvent.initMouseEvent(
        'click', true, true, window, 0,
        0, 0, x, y, false, false,
        false, false, 0, null
    );
    document.elementFromPoint(x, y).dispatchEvent(clickEvent);
}
simulateClick(200, 150);

Below is the code based on the above one but this doesn't work too.

function simulateClick(x, y){
    document.elementFromPoint(x, y).click();
}
simulateClick(200, 150);

The last code doesn't trigger a click as well.

function simulateClick(targetCanvas, x, y) {
    var clickEvent = new MouseEvent(
        "click",
        {
            clientX: x,
            clientY: y,
            bubbles: true
        }
    );
    targetCanvas.dispatchEvent(clickEvent);
}
var MyCanvas = document.getElementById('MyCanvas');
simulateClick(MyCanvas, 200, 150);
CanvasStudent
  • 141
  • 1
  • 5

1 Answers1

7

Thanks to @Emiel.Zuurbier's request for code that listens for the click event I discovered that my canvas listens to mousedown, not click event. So it was enough to change the type of event listened to by MyCanvas. The last code posted in my question works fine. The second way would be to leave listening for mousedown events and to set the triggered to this type of event instead of the click event.

Below is shortened version of that code, ideal for situation when we don't want to reuse the code with another X, Y values (in bookmarklet, for example).

document
    .getElementById('MyCanvas')
        .dispatchEvent(
            new MouseEvent(
                "click", // or "mousedown" if the canvas listens for such an event
                {
                    clientX: 200,
                    clientY: 150,
                    bubbles: true
                }
            )
        );
user2402877
  • 33
  • 1
  • 6
CanvasStudent
  • 141
  • 1
  • 5