Skip to Content

svgImgs()

Convert img tags to raw SVG code.

JavaScript February 22, 2017

Usage

JavaScript
.svg

Parameters

This function does not accept any parameters. Is this incorrect?

Examples

HTML
<img class="svg" src="<?php echo get_template_directory_uri(); ?>/images/logo.svg" />

Demo


Additional Notes

It is recommended to export SVG images using the following settings, and then run them through SVGOMG. This will prevent conflicts in selectors when multiple SVGs are on a page! It is also strongly recommended to also save out an optimized transparent .png file at the same size.

Source File

Located in /assets/js/nebula.js on line 3608.

JavaScript
nebula.svgImgs = function(){
    jQuery('img.svg').each(function(){
        var oThis = jQuery(this);

        if ( oThis.attr('src').indexOf('.svg') >= 1 ){
            jQuery.get(oThis.attr('src'), function(data){
                var theSVG = jQuery(data).find('svg'); //Get the SVG tag, ignore the rest
                theSVG = theSVG.attr('id', oThis.attr('id')); //Add replaced image's ID to the new SVG
                theSVG = theSVG.attr('class', oThis.attr('class') + ' replaced-svg'); //Add replaced image's classes to the new SVG
                theSVG = theSVG.attr('role', 'img');
                theSVG = theSVG.attr('data-original-src', oThis.attr('src')); //Add an attribute of the original SVG location
                theSVG = theSVG.removeAttr('xmlns:a'); //Remove invalid XML tags

                oThis.replaceWith(theSVG); //Replace image with new SVG

                //Move alt attribute to title element within the SVG
                if ( oThis.attr('alt') ){
                    theSVG.prepend('<title>' + nebula.sanitize(oThis.attr('alt')) + '</title>'); //Sanitized to prevent XSS
                }

                //Move the title attribute to the description element within the SVG
                if ( oThis.attr('title') ){
                    theSVG.prepend('<description>' + nebula.sanitize(oThis.attr('title')) + '</description>'); //Sanitized to prevent XSS
                }
            }, 'xml');
        }
    });
};

Override

To override or disable this JavaScript function, simply redeclare it with the exact same function name.

JavaScript
nebula.svgImgs = function(){
    //Write your own code here, leave it blank, or return false.
}