Matt Stevens
Matt Stevens

Reputation: 1124

How to get onclick working on emdedded SVG images

<embed id="bottom" src="img/model/skirt.svg" onclick="control.colorClothes(this)" title="bottom" type="image/svg+xml" width="325" height="500"> </embed>

I want to cause an event to fire on a mouse click.
The above works if I use onload and onmouseover, but not onclick or onmouseup/down.

Any thoughts?

** Edit **

My thanks to the posters. The code I was looking for is
onload="this.getSVGDocument().onclick = function(event){alert(333);};"

It overcomes three separate problems.

  1. The delay in loading the svg file causing issues with code trying to execute on an svg file that didn't exist yet.

  2. That the onclick event has to be attached to the svg element. I'm not sure why, Tanzeels post showed this & my experiments confirmed it.

  3. The way I was trying to write the onclick="alert(333)" wasn't working. The above does. Again I'm not sure why, but at this point I'm just happy to go with the flow.

Upvotes: 2

Views: 4917

Answers (2)

Tanzeel Kazi
Tanzeel Kazi

Reputation: 3827

You will need to assign the click handler onto the SVG. Do something on the following lines:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function getClick(event) {
            var clickedElement = event.target;
            alert(clickedElement);
            //console.log(clickedElement);
            return;
        }

        function addClick() {
            var embedObj = document.getElementById("bottom");
            embedObj.getSVGDocument().onclick = function (event) {
                return getClick(event);
            };
            return;
        }
    </script>
</head>
<body onload="addClick();">
    <embed id="bottom" src="img/model/skirt.svg" title="bottom" type="image/svg+xml"
        width="628" height="709"></embed>
</body>
</html>

The event.target will return the SVG node that was clicked.

Note that this approach will not work for cross-domain SVG resources as the browser will throw a permission denied error when assigning the onclick event handler.

Upvotes: 3

Damon Smith
Damon Smith

Reputation: 1790

it might be worth trying to wrap the embed tag in a div and put the onclick handler on that. I'm not sure if click events bubble out of svgs into the normal DOM but if they do then you should be ok. Like this:

<div onclick="control.colorClothes(this)"><embed id="bottom" src="img/model/skirt.svg" onclick="control.colorClothes(this)" title="bottom" type="image/svg+xml" width="325" height="500"></embed></div>

Upvotes: 0

Related Questions