Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG - click is not a function [duplicate]

I have an element like this.

<g id="box_w" onclick="recordResponseKeyboard('W');" onmousedown="svgFill('W');" onmouseup="svgUnfill('W');"> 
    <rect fill="#FFFFFF" height="68.522" stroke="#FFFFFF" stroke-miterlimit="10" width="119.297" x="306.673" y="384.406"></rect> 
</g>

From the chrome console, I can do to locate the element.

document.getElementById('box_w')

If i call click event,

document.getElementById('box_w').click()

It throws an error that click is not a function.

How to click on the element using console.?

like image 483
KitKarson Avatar asked Sep 26 '16 21:09

KitKarson


2 Answers

click() is a function that's only defined on HTML elements. Fortunately it's a convenience function and we can implement it ourselves pretty easily i.e.

document.getElementById('box_w').dispatchEvent(new Event('click'));

That's all the click() function does underneath the hood anyway.

Here's an example:

document.getElementById('box_w').dispatchEvent(new Event('click'));
<g id="box_w" onclick="alert('hi')"> 
    <rect fill="#FFFFFF" height="68.522" stroke="#FFFFFF" stroke-miterlimit="10" width="119.297" x="306.673" y="384.406"></rect> 
</g>
like image 56
Robert Longson Avatar answered Nov 17 '22 08:11

Robert Longson


Try to use onclick instead of click.

document.querySelector("g#box_w").onclick();

Remember that what we are doing here is calling the interface of the shape. So onclick needs to be defined in svg as it is in the question:

<g id="box_w" onclick="recordResponseKeyboard('W');"></g>
like image 1
Maciej Sikora Avatar answered Nov 17 '22 09:11

Maciej Sikora