Can a SVGStyleElement be disabled like an HTMLStyleElement can?

Short version:

Unlike the HTMLStyleElement the SVGStyleElement has no disabled property (according to the MDN docs)

Question: can a whole SVGStyleElement be disabled/toggled?

Longer playground version:

Question: Which Browsers are doing what right?

<template id=TEMPLATE>
  <style onload="this.disabled=true">
    body { background: red; }
    circle { fill:green; }
  </style>
  <circle cx="50%" cy="50%" r="45%"></circle>
</template>
<div id=DIV></div>
<svg id=SVG width="40" height="40"></svg>
<script>
let STYLE;// global
  function inject(id) {
    DIV.innerHTML=``;SVG.innerHTML=``;  // wipe all
    INNER.innerHTML=``;DISABLEDSTATE.innerHTML=``;
    id.innerHTML = TEMPLATE.innerHTML; // set innerHTML in DIV or SVG
    INNER.append(TEMPLATE.innerHTML); // show template HTML as text
    setTimeout(() => { // wait till DOM is fully updated
        STYLE = id.querySelector("style"); // get style tag in DIV or SVG
        DISABLEDSTATE.append(STYLE.constructor.name,' - disabled state: ',STYLE.disabled);
    })
  }
  function toggle(){
    STYLE.disabled = !STYLE.disabled;
    DISABLEDSTATE.innerHTML =``;
    DISABLEDSTATE.append(STYLE.constructor.name,' - disabled state: ',STYLE.disabled);
  }
</script>
<hr>
<button onclick="inject(DIV)">inject Template in DIV</button>
<button onclick="toggle()">toggle STYLE disabled state</button>
<button onclick="inject(SVG)">inject Template in SVG</button>
<hr><b>Injected HTML:</b><div id=INNER></div>
<b>Style disabled state:</b><div id=DISABLEDSTATE></div>

Upvotes: 1

Views: 144

Answers (2)

Robert Longson
Robert Longson

Reputation: 124029

Chrome and Firefox have implemented disabled on SVGStyleElement for some time now.

The SVG 2 specification says this about the style element

SVG 2 ‘style’ element shall be aligned with the HTML5 ‘style’ element.

Upvotes: 1

Sphinxxx
Sphinxxx

Reputation: 13017

Both elements support the media property, so you can use the media="not all" hack found here: https://stackoverflow.com/a/59572781/1869660

Edit: Looks like SVGStyleElement.media is read-only in Chrome, so you need to start with a normal (enabled) style sheet and use both techniques:

<template id=TEMPLATE>
  <style>
    body { background: red; }
    circle { fill:green; }
  </style>
  <circle cx="50%" cy="50%" r="45%"></circle>
</template>
function toggle() {
  if ((STYLE.media === 'all') || !STYLE.media) {
    STYLE.media = 'not all'; //Firefox
    STYLE.disabled = true;   //Chrome
  }
  else {
    STYLE.media = 'all';     //Firefox
    STYLE.disabled = false;  //Chrome
  }
  DISABLEDSTATE.innerHTML = ``;
  DISABLEDSTATE.append(STYLE.constructor.name, ' state: ', STYLE.media);
}

https://jsfiddle.net/mvb9fkay/

Upvotes: 1

Related Questions