views:

167

answers:

4

I'm trying to add an onClick handler to an embedded object. The handler needs to execute a function which is in an external .js file which is linked to the current html file via <script src="....

Do I need to reference the function differently due to it being located elsewhere?

Here is the code as it currently stands (which does not work, but also does not produce any errors):

<embed src="svg/button.svg" id="buttonEmbed" width="95" height="53" 
type="image/svg+xml" onClick="buttonEvent('buttonClicked')"/>
A: 

You can try the following:

<div onClick="javascript: alert('clicked!');">
<embed src="svg/button.svg" id="buttonEmbed" width="95" height="53" 
type="image/svg+xml" />
</div>
xil3
I don't think that's going to work.
Erik Dahlström
+2  A: 

You have to implement onclick inside the svg and link it to the external JavaScript function using javascript inside the svg. See the SVG wiki for examples.

Mario Menger
Thanks. I have placed the onclick inside the svg shape itself, however it now can't find the function it's looking for. Presumably because it's in an external .js file?
Jack Roscoe
How are you calling the external function from your SVG? Have you prefixed it with `top.` or `parent.` ?
Mario Menger
I have simply added onclick="buttonEvent()" (after testing with an alert, which worked). What should I prefix and where?
Jack Roscoe
Try using onclick="top.buttonEvent()" or onclick="parent.buttonEvent()" - hope either of these work!
Mario Menger
My mistake. I've appended it with parent. and it's now working. Thanks so much!
Jack Roscoe
+1  A: 

Use either javascript binding (Mario Menger answered that already).

If you can't or won't use the binding, you can use what xil3 answered with one modification:

Use an empty anchor tag <a href="javascript:someFunc()"></a> as the click consumer. Set it's z-index and position/size so it positioned over the svg object (for cross-browser compatibility).

Jaroslav Jandek
+1  A: 

Onclick should all be lowercase.

<embed src="svg/button.svg" id="buttonEmbed" width="95" height="53" 
type="image/svg+xml" onclick="alert('hello!');"/>
Tom Gullen