Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use click function on SVG tags? I tried element.click() on a <polygon>. Trying to simulate the click using javascript. Doesn't work

//Trying to retrieve the HTML element from the below HTML and attempting to click on it using the Javascript code below

    <html>
        <svg width="300" height="200">
        <polygon points="100,10 40,198 190,78 10,78 160,198"
  style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" />
        </svg>
    </html>

    <script>
        var polygons = document.getElementsByTagName('polygon');
        if(polygons.length>0)
        {
            //This statement doesn't work. Trying to simulate the click on the polygon element. The click function doesn't click it
            polygons[0].click();
        }
    </script>
like image 452
Shibu Avatar asked Jan 02 '23 14:01

Shibu


1 Answers

Contrarily to my fellow, I will purposely and kindly disregard the fact that you didn't set a click event listener, but will instead answer the question that everyone missed here.


The click method you are trying to use is the HTMLElement.click method.
This method is available to all elements inheriting from HTMLElement, but your <polygon> is an SVGPolygonElement, which does not inherit from HTMLElement.

So no, you can not use this method on this element, because it has no such method defined in its prototype chain.

// an SVGElement
var poly = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
// an HTMLElement
var unknown = document.createElement('foo');

console.log('<polygon> (SVG element)');
console.log('has click method:', !!poly.click);
console.log('inherits from HTMLElement:', poly instanceof HTMLElement);

console.log('//////////////////');

console.log('<foo> (HTML element)');
console.log('has click method:', !!unknown.click);
console.log('inherits from HTMLElement:', unknown instanceof HTMLElement);

But even though this method is not available, you can well trigger a click event programmatically, e.g with the EventTarget.dispatchEvent method.

var poly = document.getElementById('poly');
poly.dispatchEvent(new Event('click'));

function _log(evt) {
  console.log('clicked');
}
<svg>
<polygon id="poly" points="60,20 100,40 100,80 60,100 20,80 20,40" onclick="_log()"/>
</svg>

Or since your issue seems to be related to WPT (that I really don't know), it seems that you can also do the same with the sendClick method, but once again, I don't know WPT and I just got it from a fast-read of the docs.

like image 61
Kaiido Avatar answered Jan 05 '23 03:01

Kaiido