Is it possible to update the CSS file of an external SVG file in real-time?

Is there a way for an SVG image to reference another CSS file?

  • A webpage contains an SVG file.
  • A button allows users to switch between classic colors and high contrast mode on the entire webpage, including the SVG image.

Attempt

w.css (white background)

svg { background-color:white; }
path{ fill:none; stroke:black; stroke-width:8px; }

b.css (black background)

svg { background-color:black; }
path{ fill:none; stroke:white; stroke-width:10px; }

image.svg

<?xml version="1.0"?>
<?xml-stylesheet type="text/css" href="w.css" title="classic" ?>
<?xml-stylesheet type="text/css" href="b.css" title="contrast" alternate="yes" ?>
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
   <path d="M150,100 H50 V300 H150 M250,300 H300" />
</svg>

example.html

<html>
<body>

<embed id="svg_image" src="image.svg" type="image/svg+xml" /> 

<script type="text/javascript">
var embed = document.getElementById("svg_image");
function change_css(file){
    var svgdoc = embed.getSVGDocument();
    var b = svgdoc.childNodes;
    for (var i=0; i<b.length; i++){
        var itm = b.item(i);
        itm.Data = "href='"+ file +"' type='text/css'" ;
    }
}
</script>

<input name="c" type="radio" onclick="change_css('b.css');">High contrast<br>
<input name="c" type="radio" onclick="change_css('w.css');" checked="yes">Classic

</body>
</html>

WEB SEARCH: No answer found in 2011

UPDATE: See also question about correctly structuring javascript, css, and svg
Maybe jQuery SVG (keith-wood.name)...

Answer №1

Consider this alternative approach instead of switching actual stylesheets: set a CSS class on a high level element and then manipulate that class with Javascript. This way, you can consolidate all your CSS rules in one file and simplify your selectors like so:

<svg xmlns="http://www.w3.org/2000/svg" class="someclass">
    <style>
        .someclass .mypath { stroke: blue; }
        .someotherclass .mypath { stroke: red; }
    </style>
    <path d="M150,100 H50 V300 H150 M250,300 H300" class="mypath" />
</svg>

Think of it as an if...else construct. If the element is a descendant of someclass, apply the blue color, otherwise apply the red color.

Keep in mind though, some browsers may encounter issues with external stylesheets in SVG documents.

Answer №2

Looking to manipulate style sheets with JavaScript for SVG? Check out this resource: . It provides a guide on how to toggle style sheets using JavaScript and could potentially be adapted for use with SVG.

I decided to test it out myself by using Firebug on a webpage that included an SVG with an external CSS reference.

let objects = document.getElementsByTagName("object");
let svgDoc = objects[0].getSVGDocument();
svgDoc.styleSheets[0].disabled = true;

The experiment yielded successful results, indicating that the method is effective.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Showing PHP array in the JavaScript console

I have a straightforward AJAX script that sends 3 variables to an external PHP script. The external script then adds them into an array and sends the array back. I want to output this array in the JavaScript console to check if the variables are being pass ...

I seem to be facing some difficulty in dynamically calling my buttons in AngularJS

Can you assist me in solving this problem? I am new to Angular and just starting out. Initially, there is only one button on load called "Add list". When the user clicks on this button, they are able to add multiple lists. Each list contains a button labe ...

Removing   from a text node using JavaScript DOM

I am currently working with xhtml in javascript. To retrieve the text content of a div node, I am concatenating the nodeValue from all child nodes where nodeType is Node.TEXT_NODE. However, sometimes the resulting string includes a non-breaking space enti ...

Issue with Swiper js "autoheight" not resizing correctly for the height of the first slide upon page initialization

Hey everyone, I'm encountering a problem with my reactapp and I'm not sure how to resolve it. I've spent a considerable amount of time searching on stackoverflow but haven't come across any helpful solutions. The issue is related to a ...

Bringing in an external .js file into nuxt.config.js

Having trouble importing config.js with the project's API keys and getting undefined as a return value. //config.js var config = { fbAPI: "key" } - //nuxt.config.js const cfg = require('./config') env: { fbAPI: cfg.apiKey } Wonder ...

Utilize SoundCloud API to generate user profiles according to their unique identification within the system

In my system, I have implemented a process that takes an array of SoundCloud user IDs. These IDs are then iterated through a series of SC.get functions to gather information about each user, such as their user ID, username, followings, and genre preference ...

Benefits of using props destructuring in React - beyond just being a syntactic shortcut

This idea might not be exclusive to React, but I've struggled to discover a compelling reason beyond concise and easier-to-read code. ...

Utilize jQuery's .append() function to dynamically insert content into your webpage

I currently have tab elements set up like this: <div class="tab-pane fade active in" id="tab-a"> </div> To populate the content of that tab with a JavaScript string array, I am using the following code snippet: var full_list = ""; for (var ...

Double f span causing unusual behavior in Chrome browser

Why does the highlight focus on "ort" instead of "fort"? It appears this occurs when there are two f's. When I substitute f with other letters, like d, it shows correctly. Could this be a bug in Chrome? Chrome version is chrome83. add: It seems to be ...

Customize elements such as MuiTab that rely on media queries

Looking to customize the font size for MuiTab using CSS overrides. While following the material-ui documentation for CSS overrides, I successfully adjusted the font size for most elements. However, I encountered an issue with elements that utilize media q ...

Fixed width layout in Bootstrap 3 with a footer that spans the full width of the

Currently, I am utilizing Bootstrap 3 with a fixed width set-up. The footer on my site consists of two columns, each with a different background color. In order to ensure that the content in the footer aligns properly with the rest of the website, I want ...

AngularJS - let's make pagination more interactive by adding an active class to the current page

Check out this fiddle I created: http://jsfiddle.net/tbuchanan/eqtxLkbg/4/ Everything is working as intended, but I'm looking to add an active class to the current page when navigating through the pages: <ul class="pagination-controle pagination" ...

The error prop in Material UI DatePicker does not function properly when combined with yup and react-hook-form

Currently, I am working on enhancing a registration form using tools such as yup, react-hook-form, and Material UI DatePicker/TextField. My goal is to include a date of birth field that validates whether the user is over 18 years old. Although the error me ...

Struggling to combine select dropdown choices in one calculation

​​I'm currently working on a project where I need to create a website that multiplies three numbers selected from dropdown menus together. However, when I attempt to perform the calculation, I only get the result "1" displayed. I've spent sev ...

Tips for modifying a user's tags with Quickblox's JavaScript SDK

Is there a way to update a user's tags using the Quickblox JavaScript SDK? I have attempted using the parameter names listed below: user_tags tags with var params = { user_tags: ["testing"] }; Kindly avoid suggesting alternatives like "custom ...

"Uncovering the dangers of XMLHttpRequest: How automatic web-page refresh can lead

Hello, I have been developing a web interface for some hardware that utilizes an 8-bit microcontroller. The webpage includes HTML, JavaScript, JSON, and XHR (XMLHttpRequest) for communication purposes. My goal is to create a page that updates every 250 ...

Utilizing JavaScript to trigger an email with PHP variables included

i am trying to pass a few php variables using a javascript trigger. Everything seems to be working with the variables, databases, and script but I am struggling with the PHP part. Here is my attempt at the PHP code, although it clearly has some issues. I ...

Is there a way to retrieve all results from a ReactiveList?

My attempt to retrieve all data has been unsuccessful as I am only able to obtain the number of results specified in the 'size' parameter. Below is a snippet of my code. <ReactiveList componentId="results" dataField="original_title" siz ...

Splitting with Regex - One Time Operation

Here is some of my Jquery code along with Regex: $("[class^=ipsum-img],[class^=ipsum-img-]").each(function(){ var x = $(this).attr("class"); console.log(x.length); if (x.length>8) { var m = x.split(/(\d+)[^-]*$/g); cons ...

What are the steps to fix a timeout error with React.js and socket.io acknowledgements?

My setup includes a Node.js server and a React.js client application. Data is exchanged between them using socket.io, but I'm running into an issue with implementing acknowledgment. Whenever I try to implement acknowledgment, I receive a timeout error ...