Home > Back-end >  How to alter SVG-element on a web-page with contebnt from a new file?
How to alter SVG-element on a web-page with contebnt from a new file?

Time:11-03

I use SVGInject to load svg-images inline:

<img src="image1.svg" id="changeme" onl oad="SVGInject(this)" />

This works like a charm, and the image can be moved, rotated etc.
But is it possible to later "change" the image maybe?

document.getElementById('changeme').src = 'image2.svg';
SVGInject(document.getElementById('changeme'));

This does NOT work. Should the object be reloaded? Or the original destroyed and a new created...

cheers

CodePudding user response:

Replacing the svg won't work as svg-inject.js removes the original img element. Thus, document.getElementById('changeme') can't select or replace anything.

You might wrap the original SVGInject(el) function in a helper function that's cloning the img element before inlining svg.
This way you can replace the img src, remove the previously inlined svg and finally re-inject the changed svg url.

/// find and replace all svgs with class name "svg-replace"
var svgInjects = document.querySelectorAll('.svg-replace');
if(svgInjects.length){
    for(var i=0; i<svgInjects.length; i  ){
        var svgEl = svgInjects[i];
        // modified inject function
        SVGInjectCloned(svgEl); 
    }
}
  
  
function SVGInjectCloned(svgEl){
    var svgCloned = svgEl.cloneNode(true);
    svgEl.parentNode.appendChild(svgCloned);
    
    /// hide original 
    svgEl.setAttribute('style', 'display:none');

    // inline svg
    SVGInject(svgCloned);
    //console.log('svg inlined');
}


function replaceSvg(previousSvgEl, newSvgUrl){
    var svgEl = document.querySelector(previousSvgEl);

    // find and delete previously inlined svg
    var inlinedSvg = svgEl.nextElementSibling;
    if(inlinedSvg){
        inlinedSvg.remove();

        /// make original visible again
        svgEl.removeAttribute('style');

        // update svg src
        svgEl.src = newSvgUrl;

        // reclone svg element for inlining
        var svgCloned = svgEl.cloneNode(true);
        svgEl.parentNode.appendChild(svgCloned);

        /// hide original 
        svgEl.setAttribute('style', 'display:none');
        SVGInject(svgCloned);
    }   
}
  
  
// example button
var newSvgUrl =
"data:image/svg xml,";

var btnSvgReplace = document.querySelector('.btnSvgReplace');
if(btnSvgReplace){
btnSvgReplace.addEventListener('click', function(){
    replaceSvg('#firstSvg', 
    newSvgUrl
    );
});
}
  
 img,
 svg
 {
 width:100px;
 height:100px; 
 }
<script src="https://cdn.jsdelivr.net/npm/@iconfu/[email protected]/dist/svg-inject.min.js"></script>

<div class="svg-wrp">
      <img src="data:image/svg xml,
" class="svg-replace" id="firstSvg" />
  </div>  
<p><button class="btnSvgReplace">Replace svg</button></p>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related