Tips for creating editable SVGs without the need for inline SVG code

I am looking to incorporate SVG icons into my websites, but I have concerns about using <image> which limits the ability to modify SVG properties (such as changing fill color on hover).

I have come across the concept of in-line SVG, which appears to offer greater flexibility. However, I worry that embedding SVG drawing data directly into the HTML file may pose maintenance challenges in the future.

I am seeking a solution that allows me to...

  1. Save my SVG in an external file
  2. Reference that SVG from the external file in my HTML document
  3. Still be able to dynamically change the fill color within the HTML file

Is this possible? And if so, what keyword should I search for?

Answer №1

The outcome will vary depending on the programming language you opt for.

  • Using an HTML file with (iframe) will not give you the desired result.

  • In contrast, incorporating a PHP file with (include) will function as per your requirements.

For instance:

index.php includes a svgs.php file.


Alternatively, it may be beneficial to create an icon file utilizing SVG Sprites. [See]

This allows you to load and modify multiple icons from a single ".svg" file through concise commands like those listed below.

Keep in mind: This technology does not support certain SVG features such as Gradient. [1] [2]

<svg viewBox="0 0 24 24" class="icon">
  <use href="#foo"></use>
</svg>

<svg viewBox="0 0 24 24" class="icon">
  <use href="#bar"></use>
</svg>

Tool for automatically generating SVG sprites:


Finally, there are options available like utilizing third-party scripts such as SVG injectors.

https://i.sstatic.net/XhB3G.png

Answer №2

Others have mentioned that you can dynamically load the SVG into the document and access its elements through the HTML DOM. Here is my approach to doing this. You may notice a long line of code that resembles an inline SVG, but you can replace it with a valid URI pointing to an SVG file. I included the SVG inline for testing purposes to avoid CORS issues with fetch.

Don't forget to customize the data-url with your specific URI.

async function loadSVG(){
    const container=document.querySelector("#svgContainer");
    let svgContainer=container;
    let url=container.dataset.url;
    await fetch(url)
        .then(response=>response.text())
        .then(text=>{svgContainer.innerHTML=text})
        .catch(error=>console.log(error));
    let newSvg=svgContainer.firstChild;
    newSvg.setAttribute("id","newSvg");
    newSvg.setAttribute("width","32px");
    newSvg.setAttribute("height","32px");
}   
loadSVG();
#newSvg{
    animation: test 1s linear 0s infinite;
}
@keyframes test{
    0% {transform:translate(0%,0%);}
    20% {transform:translate(70%,0%);}
    80% {transform:translate(0%,70%);}
    100% {transform:translate(0%,0%);}
}
<div id="svgContainer" data-url="data:image/svg+xml,%3Csvg%20class=%22sIcon%22%20viewBox=%2210%20-6%201%2080%22%20xmlns=%22http://www.w3.org/2000/svg%22%3E%20%3Cg%3E%20%3Ccircle%20fill=%22rgb(255,0,0,1)%22%20transform=%22translate(0%200)%22%20cx=%2210%22%20cy=%2210%22%20r=%2210%22/%3E%20%3Ccircle%20fill=%22rgb(0,255,0,1)%22%20transform=%22translate(0%2024)%22%20cx=%2210%22%20cy=%2210%22%20r=%2210%22/%3E%20%3Ccircle%20fill=%22rgb(0,0,255,1)%22%20transform=%22translate(0%2048)%22%20cx=%2210%22%20cy=%2210%22%20r=%2210%22/%3E%20%3C/g%3E%20%3C/svg%3E"></div>

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

Tips for aligning images inside tab content areas

While using an "accordion" jQuery to show a contact list, I have encountered a challenge that may seem simple to someone experienced in this. Here is the code snippet: <!doctype html> <html lang="en> ... (Code continues) I am looking to add ...

Troubleshooting: CSS border-radius issue with embedded iframe

I am struggling to embed an iframe from my Blogger site into a specific section on my website and round its corners using CSS. I followed a tutorial that suggested using overflow: hidden;, but for some reason, it's not working in my case - see the ima ...

Is there a way to show text as symbols in Primeng components?

Check out this helpful example that demonstrates what I am attempting to achieve. I have implemented p-menu from primeng. Is there a method to convert text into symbols like &trade to ™ and &#8482 to ®? ...

What is the most straightforward method to access these four buttons?

Looking to create 4 interactive buttons with a unique behavior. When clicked, the chosen button will change its background image while the other 3 buttons retain their original background image unless hovered over by the user. Additionally, hovering over a ...

What is the reason behind the default disabling of bootstrap multiselect options?

Just diving into the world of bootstrap and I'm puzzled as to why my simple multiselect options aren't responding when clicked. UPDATE The first multiselect option on the test-site linked below is the one giving me trouble. I've tried it o ...

The Chrome browser on a PC is displaying the mobile version rather than the desktop version

I am currently working on a website project using bootstrap, and I ran into an unexpected issue where the mobile version of the site is being displayed in Google Chrome on my laptop instead of the desktop version. This happens even when Inspect Element is ...

Steps for resetting the ng-multiselect-dropdown

Is it necessary to wrap the ng-multiselect-dropdown in a form in order to reset it? code - app.component.html <div> <p id = "node">Select a Root API Object - </p> <p style="width:50%"> <ng-multiselect-dropdown [placeho ...

Dimming the background of my page as the Loader makes its grand entrance

Currently, I am in the process of developing a filtering system for my content. The setup involves displaying a loader in the center of the screen whenever a filter option is clicked, followed by sorting and displaying the results using JQuery. I have a v ...

The sub-menu options are constantly shifting... How can I keep them in place?

Here we go again... I'm having trouble with my sub-menu elements moving when I hover over them. I've searched for a solution but haven't found anything helpful. The previous advice I received about matching padding and adding transparent bo ...

Select a radio button when it is in focus

I am having trouble figuring out how to automatically check a radio button when a user clicks on an input field. The code I have attempted is not working as expected... $(function() { $('.searchInput').focus(function() { $(this).prev( ...

Changing the Date Display format of a new Date() instance

Just starting out with the MEAN Stack I'm currently utilizing the new date() function to retrieve the date, but I prefer not to display the time offset. ...

Set the height of the main div container to a fixed size

I am facing an issue with my div container (mapInfo-Container) which contains multiple div blocks. I want the container to have a fixed height of 250px, and be scrollable for any content exceeding this height. Here is the code snippet: http://jsfiddle.net ...

Struggling to make Tumblr Javascript function properly

I have integrated the following code snippet: <script type="text/javascript" src="http://underlineent.tumblr.com/api/read/json"> </script> Unfortunately, my Tumblr blog is not appearing on this site. Can anyone provide assistance? The provid ...

Guide to implementing the onchange event in JavaScript for this specific scenario

How can the onchange event be utilized in this scenario using JavaScript? First, input data into the input with id="one". Subsequently, the data in the input with id="two" will be updated to match the data in the input with id="one". However, when the da ...

Tips on maintaining the consistent color of an active link until selecting a different link

Is it possible to make a link change color when clicked, and have that color stay until another link is clicked? How can I achieve this using the "active" attribute? I attempted it, but the link reverts back to its original color after clicking. &l ...

Freezing the OrderBy Directive in AngularJS ng-repeat While Editing

I am currently utilizing md-data-table and have implemented sorting options based on column. Below is my HTML code in pug format: table(md-table md-row-select multiple='' ng-model='vm.selected' md-progress='promise') //- col ...

Error 404: Troubleshooting an Azure Issue with Custom TrueType Font in .NET MVC 5

I am encountering an issue that has been previously addressed. Despite implementing the suggested solutions, the problem persists. In an effort to enhance my project, I downloaded two custom ttf fonts called Monterey and Bakery. Both fonts have been succ ...

`Understanding Unique Identifiers in HTML: Questions on Element Naming`

Is it problematic to use a space character in an element ID? For example, like this: <li id='something with spaces'>Test123</li> I typically avoid using spaces in IDs, but I've encountered a situation where it might be necessar ...

Leveraging the power of JavaScript to reveal concealed div elements

I've got a collection of divs (five in total) with a hidden class applied to them in my CSS stylesheet. Each div also has its own unique ID. My goal is to use JavaScript to reveal these divs one by one. Here's an example of what I'm looking ...

The alignment of Div elements is off in IE8

I have been struggling to align two divs side by side without any empty spaces on IE 8. Everything looks perfect on Chrome Version 35.0.1916.153 m and Firefox 30.0, but IE 8 seems to be causing some issues. All I want is a main div with two child divs ali ...