1

I have an SVG in my tag. When I click on it, I want to redirect the page.

<object class="SVGClass centered" data="/Data/Blue_Force.svg" type="image/svg+xml" id="BF1SVG"style="margin:20px"></object>
<script>
var SVG1 = document.getElementById("BF1SVG");
var SVGElements1;
var SVGLoaded1 = false;
    if(!SVGLoaded){
        SVG1.addEventListener('load',function(){ 
            SVGLoaded1 = true;
            SVGElements1 = SVG1.contentDocument;

      SVGElements1.getElementById("svgCC").setAttributeNS(null, "onclick", "window.location.href='http://686amppi5.campus.nist.gov/cryoConceptsStateViewer.html'");
});
</script>

svgCC is the id of the external SVG. When i click on it, the object itself becomes the new page, like an embedded window, rather than redirecting the browser.

I've also tried:

document.getElementById("BF1SVG").setAttribute("onclick", "window.location.href='http://686amppi5.campus.nist.gov/cryoConceptsStateViewer.html'");

but that just does nothing. my svg is not clickable.

HAZRD
  • 63
  • 5

2 Answers2

1

You should not set the onclick attrbute that way... try this instead.

document.getElementById("BF1SVG").addEventListener(
    'click', 
    () => window.location.assign('http://686amppi5.campus.nist.gov/cryoConceptsStateViewer.html');
);
1

It looks like the problem is the object tags aren't clickable. The easiest way around it seems to be wrapping the object in a div or some other regular tag and then adding object { pointer-events: none; } to your stylesheet.

See these threads for more info: https://stackoverflow.com/a/17133804/11886299 and Add onclick event to newly added element in JavaScript

var SVG1 = document.getElementById("BF1SVG");
var SVGElements1;
var SVGLoaded1 = false;
    if(!SVGLoaded1){
        SVG1.addEventListener('load',function(){ 
            SVGLoaded1 = true;
            SVGElements1 = SVG1.contentDocument;
            this.parentElement.addEventListener(
              "click",
              function(){
                window.location.href="http://686amppi5.campus.nist.gov/cryoConceptsStateViewer.html"

            });
});
}
object { pointer-events: none; }
<div>
<object class="SVGClass centered" data="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/android.svg" type="image/svg+xml" id="BF1SVG"style="margin:20px"></object>

</div>
Mickey
  • 570
  • 3
  • 11