Skip to main content
Participant
January 13, 2020
Answered

Access SVG object with JavaScript

  • January 13, 2020
  • 2 replies
  • 3502 views

I want to add custom behavior to SVG images in my Captivate project though JavaScript code. However, it seems like the SVG object is not loaded when the JavaScript code attempts to access it. The object is listed in the innerhtml parameter of the surrounding div (SVG_1c contains SVG_1c_object), but this element comes back empty or null no matter how I try to access it.

 

var mySVG = document.getElementById("SVG_1c");
console.log(mySVG.innerHTML);
^This returns an empty string.
 
var mySVG = document.getElementById("SVG_1c_object");
console.log(mySVG);
^This returns null (undefined).
 
Is there a way to access this object in HTML, perhaps by waiting for the image to be loaded before running the rest of the script?
This topic has been closed for replies.
Correct answer TLCMediaDesign

Try wrapping your code in a setTimeout or setInterval to wait for the svg to be rendered. It should be there in 100ms or so.

2 replies

TLCMediaDesign
TLCMediaDesignCorrect answer
Inspiring
January 13, 2020

Try wrapping your code in a setTimeout or setInterval to wait for the svg to be rendered. It should be there in 100ms or so.

Participant
January 14, 2020

This worked perfectly! I currently have a piece of code like this and it functions exactly as I hoped:

setTimeout(function(){
   var mySVG = document.getElementById("SVG_1c_object").contentDocument.children[0].children[0]; //g
   //More code of course
}, 100);
 
 
Stagprime2687219
Legend
January 13, 2020

What sort of custome behavior are we talking about?

I was successful with both of these options...

 

This one changed the state to be a different color.

cp.changeState("SVG_1","on");

 This one caused the SVG to fade out.

$("#SVG_1c").fadeOut(500);

 

Participant
January 14, 2020

To answer your first question, I am attempting to get around a boundingbox issue. I have multiple irregularly shaped SVGs in the same area that I use as buttons. However, their bounding boxes regularly overlap. I intended to apply CSS code like this in order to ignore the bounding boxes of the SVGs: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

 

Though the answer by TLCMediaDesign below helped me access the SVG very directly, sadly I have still not found a workaround for this overlapping bounding box issue.

Your code also works to access aspects of the SVG object, and I think they should come in use too. Thank you!

Known Participant
April 9, 2024

Hi, 

This post is 4 years old but still facing the same kind of limitations with overlaping SVG buttons. Yout last answer seeems to evoque a possible solution. By any chance (if your are still here), could you share your solution?

Thanks